am 21bd4af8: Simplify the VPN service implementation.

Merge commit '21bd4af88a24d0df020f68683f7c60698ebcc76a'

* commit '21bd4af88a24d0df020f68683f7c60698ebcc76a':
  Simplify the VPN service implementation.
diff --git a/Android.mk b/Android.mk
index 011e59e..8a4acbe 100644
--- a/Android.mk
+++ b/Android.mk
@@ -65,8 +65,11 @@
 ## READ ME: ########################################################
 LOCAL_SRC_FILES += \
 	core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl \
-  core/java/android/accessibilityservice/IEventListener.aidl \
-	core/java/android/accounts/IAccountsService.aidl \
+	core/java/android/accessibilityservice/IEventListener.aidl \
+	core/java/android/accounts/IAccountManager.aidl \
+	core/java/android/accounts/IAccountManagerResponse.aidl \
+	core/java/android/accounts/IAccountAuthenticator.aidl \
+	core/java/android/accounts/IAccountAuthenticatorResponse.aidl \
 	core/java/android/app/IActivityController.aidl \
 	core/java/android/app/IActivityPendingResult.aidl \
 	core/java/android/app/IActivityWatcher.aidl \
@@ -87,7 +90,6 @@
 	core/java/android/backup/IRestoreSession.aidl \
 	core/java/android/bluetooth/IBluetoothA2dp.aidl \
 	core/java/android/bluetooth/IBluetoothDevice.aidl \
-	core/java/android/bluetooth/IBluetoothDeviceCallback.aidl \
 	core/java/android/bluetooth/IBluetoothHeadset.aidl \
 	core/java/android/content/IContentService.aidl \
 	core/java/android/content/IIntentReceiver.aidl \
@@ -195,7 +197,10 @@
 # relative to the root of the build tree.
 # ============================================================
 aidl_files := \
-	frameworks/base/core/java/android/accounts/IAccountsService.aidl \
+	frameworks/base/core/java/android/accounts/IAccountManager.aidl \
+	frameworks/base/core/java/android/accounts/IAccountManagerResponse.aidl \
+	frameworks/base/core/java/android/accounts/IAccountAuthenticator.aidl \
+	frameworks/base/core/java/android/accounts/IAccountAuthenticatorResponse.aidl \
 	frameworks/base/core/java/android/app/Notification.aidl \
 	frameworks/base/core/java/android/app/PendingIntent.aidl \
 	frameworks/base/core/java/android/content/ComponentName.aidl \
@@ -357,6 +362,34 @@
 		-hdf sdk.rel.id $(framework_docs_SDK_REL_ID) \
 		-hdf sdk.current $(framework_docs_SDK_CURRENT_DIR)
 
+# ====  the api stubs and current.xml ===========================
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:=$(framework_docs_LOCAL_SRC_FILES)
+LOCAL_INTERMEDIATE_SOURCES:=$(framework_docs_LOCAL_INTERMEDIATE_SOURCES)
+LOCAL_JAVA_LIBRARIES:=$(framework_docs_LOCAL_JAVA_LIBRARIES)
+LOCAL_MODULE_CLASS:=$(framework_docs_LOCAL_MODULE_CLASS)
+LOCAL_DROIDDOC_SOURCE_PATH:=$(framework_docs_LOCAL_DROIDDOC_SOURCE_PATH)
+LOCAL_DROIDDOC_HTML_DIR:=$(framework_docs_LOCAL_DROIDDOC_HTML_DIR)
+LOCAL_ADDITIONAL_JAVA_DIR:=$(framework_docs_LOCAL_ADDITIONAL_JAVA_DIR)
+
+LOCAL_MODULE := api-stubs
+
+LOCAL_DROIDDOC_OPTIONS:=\
+		$(framework_docs_LOCAL_DROIDDOC_OPTIONS) \
+		-stubs $(TARGET_OUT_COMMON_INTERMEDIATES)/JAVA_LIBRARIES/android_stubs_current_intermediates/src \
+		-apixml $(INTERNAL_PLATFORM_API_FILE) \
+		-nodocs
+
+LOCAL_DROIDDOC_CUSTOM_TEMPLATE_DIR:=build/tools/droiddoc/templates-sdk
+LOCAL_DROIDDOC_CUSTOM_ASSET_DIR:=assets-sdk
+
+include $(BUILD_DROIDDOC)
+
+$(full_target): $(framework_built)
+$(INTERNAL_PLATFORM_API_FILE): $(full_target)
+$(call dist-for-goals,sdk,$(INTERNAL_PLATFORM_API_FILE))
+
 # ====  static html in the sdk ==================================
 include $(CLEAR_VARS)
 
@@ -375,10 +408,7 @@
 		-title "Android SDK" \
 		-proofread $(OUT_DOCS)/$(LOCAL_MODULE)-proofread.txt \
 		-todo $(OUT_DOCS)/$(LOCAL_MODULE)-docs-todo.html \
-		-stubs $(TARGET_OUT_COMMON_INTERMEDIATES)/JAVA_LIBRARIES/android_stubs_current_intermediates/src \
-		-apixml $(INTERNAL_PLATFORM_API_FILE) \
 		-sdkvalues $(OUT_DOCS) \
-		-warning 3 \
 		-hdf android.whichdoc offline
 
 LOCAL_DROIDDOC_CUSTOM_TEMPLATE_DIR:=build/tools/droiddoc/templates-sdk
@@ -394,8 +424,6 @@
 
 $(full_target): $(static_doc_index_redirect)
 $(full_target): $(framework_built)
-$(INTERNAL_PLATFORM_API_FILE): $(full_target)
-$(call dist-for-goals,sdk,$(INTERNAL_PLATFORM_API_FILE))
 
 
 # ==== docs for the web (on the google app engine server) =======================
@@ -480,5 +508,3 @@
 ifeq (,$(ONE_SHOT_MAKEFILE))
 include $(call first-makefiles-under,$(LOCAL_PATH))
 endif
-
-
diff --git a/api/current.xml b/api/current.xml
index d56263f..e76686f 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -122,6 +122,28 @@
  visibility="public"
 >
 </field>
+<field name="ACCOUNT_MANAGER_SERVICE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.permission.ACCOUNT_MANAGER_SERVICE&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUTHENTICATE_ACCOUNTS"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.permission.AUTHENTICATE_ACCOUNTS&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="BATTERY_STATS"
  type="java.lang.String"
  transient="false"
@@ -573,6 +595,17 @@
  visibility="public"
 >
 </field>
+<field name="MANAGE_ACCOUNTS"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.permission.MANAGE_ACCOUNTS&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="MANAGE_APP_TOKENS"
  type="java.lang.String"
  transient="false"
@@ -1079,6 +1112,17 @@
  visibility="public"
 >
 </field>
+<field name="USE_CREDENTIALS"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.permission.USE_CREDENTIALS&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="VIBRATE"
  type="java.lang.String"
  transient="false"
@@ -1420,7 +1464,7 @@
  type="int"
  transient="false"
  volatile="false"
- value="17432583"
+ value="17432609"
  static="true"
  final="true"
  deprecated="not deprecated"
@@ -1431,7 +1475,7 @@
  type="int"
  transient="false"
  volatile="false"
- value="17432585"
+ value="17432611"
  static="true"
  final="true"
  deprecated="not deprecated"
@@ -1442,7 +1486,7 @@
  type="int"
  transient="false"
  volatile="false"
- value="17432586"
+ value="17432612"
  static="true"
  final="true"
  deprecated="not deprecated"
@@ -1614,6 +1658,61 @@
  visibility="public"
 >
 </field>
+<field name="donut_resource_pad22"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="17432587"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="donut_resource_pad23"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="17432586"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="donut_resource_pad24"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="17432585"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="donut_resource_pad25"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="17432584"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="donut_resource_pad26"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="17432583"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="donut_resource_pad3"
  type="int"
  transient="false"
@@ -1717,7 +1816,7 @@
  type="int"
  transient="false"
  volatile="false"
- value="17432587"
+ value="17432613"
  static="true"
  final="true"
  deprecated="not deprecated"
@@ -1728,7 +1827,7 @@
  type="int"
  transient="false"
  volatile="false"
- value="17432584"
+ value="17432610"
  static="true"
  final="true"
  deprecated="not deprecated"
@@ -1989,6 +2088,17 @@
  visibility="public"
 >
 </field>
+<field name="accountType"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16843424"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="action"
  type="int"
  transient="false"
@@ -2979,6 +3089,17 @@
  visibility="public"
 >
 </field>
+<field name="contentAuthority"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16843425"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="contentDescription"
  type="int"
  transient="false"
@@ -10813,6 +10934,28 @@
  visibility="public"
 >
 </field>
+<field name="donut_resource_pad41"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="17301672"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="donut_resource_pad42"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="17301671"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="donut_resource_pad5"
  type="int"
  transient="false"
@@ -12203,7 +12346,7 @@
  type="int"
  transient="false"
  volatile="false"
- value="17301671"
+ value="17301713"
  static="true"
  final="true"
  deprecated="not deprecated"
@@ -12214,7 +12357,7 @@
  type="int"
  transient="false"
  volatile="false"
- value="17301672"
+ value="17301714"
  static="true"
  final="true"
  deprecated="not deprecated"
@@ -15813,6 +15956,2196 @@
 </field>
 </class>
 </package>
+<package name="android.accounts"
+>
+<class name="AbstractAccountAuthenticator"
+ extends="java.lang.Object"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="AbstractAccountAuthenticator"
+ type="android.accounts.AbstractAccountAuthenticator"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="context" type="android.content.Context">
+</parameter>
+</constructor>
+<method name="addAccount"
+ return="android.os.Bundle"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.AccountAuthenticatorResponse">
+</parameter>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="requiredFeatures" type="java.lang.String[]">
+</parameter>
+<parameter name="options" type="android.os.Bundle">
+</parameter>
+<exception name="NetworkErrorException" type="android.accounts.NetworkErrorException">
+</exception>
+</method>
+<method name="confirmCredentials"
+ return="android.os.Bundle"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.AccountAuthenticatorResponse">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+</method>
+<method name="confirmPassword"
+ return="boolean"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.AccountAuthenticatorResponse">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="password" type="java.lang.String">
+</parameter>
+<exception name="NetworkErrorException" type="android.accounts.NetworkErrorException">
+</exception>
+</method>
+<method name="editProperties"
+ return="android.os.Bundle"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.AccountAuthenticatorResponse">
+</parameter>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+</method>
+<method name="getAuthToken"
+ return="android.os.Bundle"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.AccountAuthenticatorResponse">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="loginOptions" type="android.os.Bundle">
+</parameter>
+<exception name="NetworkErrorException" type="android.accounts.NetworkErrorException">
+</exception>
+</method>
+<method name="getAuthTokenLabel"
+ return="java.lang.String"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+</method>
+<method name="getIAccountAuthenticator"
+ return="android.accounts.IAccountAuthenticator"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="hasFeatures"
+ return="android.os.Bundle"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.AccountAuthenticatorResponse">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="features" type="java.lang.String[]">
+</parameter>
+<exception name="NetworkErrorException" type="android.accounts.NetworkErrorException">
+</exception>
+</method>
+<method name="updateCredentials"
+ return="android.os.Bundle"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.AccountAuthenticatorResponse">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="loginOptions" type="android.os.Bundle">
+</parameter>
+</method>
+</class>
+<class name="Account"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.Parcelable">
+</implements>
+<constructor name="Account"
+ type="android.accounts.Account"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="name" type="java.lang.String">
+</parameter>
+<parameter name="type" type="java.lang.String">
+</parameter>
+</constructor>
+<constructor name="Account"
+ type="android.accounts.Account"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="in" type="android.os.Parcel">
+</parameter>
+</constructor>
+<method name="describeContents"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="writeToParcel"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="dest" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<field name="CREATOR"
+ type="android.os.Parcelable.Creator"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="mName"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="mType"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<class name="AccountAuthenticatorActivity"
+ extends="android.app.Activity"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="AccountAuthenticatorActivity"
+ type="android.accounts.AccountAuthenticatorActivity"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<method name="setAccountAuthenticatorResult"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="result" type="android.os.Bundle">
+</parameter>
+</method>
+</class>
+<class name="AccountAuthenticatorResponse"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.Parcelable">
+</implements>
+<constructor name="AccountAuthenticatorResponse"
+ type="android.accounts.AccountAuthenticatorResponse"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.IAccountAuthenticatorResponse">
+</parameter>
+</constructor>
+<constructor name="AccountAuthenticatorResponse"
+ type="android.accounts.AccountAuthenticatorResponse"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="parcel" type="android.os.Parcel">
+</parameter>
+</constructor>
+<method name="describeContents"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="onError"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="errorCode" type="int">
+</parameter>
+<parameter name="errorMessage" type="java.lang.String">
+</parameter>
+</method>
+<method name="onRequestContinued"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="onResult"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="result" type="android.os.Bundle">
+</parameter>
+</method>
+<method name="writeToParcel"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="dest" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<field name="CREATOR"
+ type="android.os.Parcelable.Creator"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<class name="AccountManager"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="addAccount"
+ return="android.accounts.Future2"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="requiredFeatures" type="java.lang.String[]">
+</parameter>
+<parameter name="addAccountOptions" type="android.os.Bundle">
+</parameter>
+<parameter name="activity" type="android.app.Activity">
+</parameter>
+<parameter name="callback" type="android.accounts.Future2Callback">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="addAccountExplicitly"
+ return="android.accounts.Future1&lt;java.lang.Boolean&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.Boolean&gt;">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="password" type="java.lang.String">
+</parameter>
+<parameter name="extras" type="android.os.Bundle">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="addOnAccountsUpdatedListener"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="listener" type="android.accounts.OnAccountsUpdatedListener">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+<parameter name="updateImmediately" type="boolean">
+</parameter>
+</method>
+<method name="blockingAddAccountExplicitly"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="password" type="java.lang.String">
+</parameter>
+<parameter name="extras" type="android.os.Bundle">
+</parameter>
+</method>
+<method name="blockingClearPassword"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+</method>
+<method name="blockingGetAccounts"
+ return="android.accounts.Account[]"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="blockingGetAccountsByType"
+ return="android.accounts.Account[]"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+</method>
+<method name="blockingGetAccountsWithTypeAndFeatures"
+ return="android.accounts.Account[]"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="type" type="java.lang.String">
+</parameter>
+<parameter name="features" type="java.lang.String[]">
+</parameter>
+<exception name="AuthenticatorException" type="android.accounts.AuthenticatorException">
+</exception>
+<exception name="IOException" type="java.io.IOException">
+</exception>
+<exception name="OperationCanceledException" type="android.accounts.OperationCanceledException">
+</exception>
+</method>
+<method name="blockingGetAuthToken"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="notifyAuthFailure" type="boolean">
+</parameter>
+<exception name="AuthenticatorException" type="android.accounts.AuthenticatorException">
+</exception>
+<exception name="IOException" type="java.io.IOException">
+</exception>
+<exception name="OperationCanceledException" type="android.accounts.OperationCanceledException">
+</exception>
+</method>
+<method name="blockingGetAuthenticatorTypes"
+ return="android.accounts.AuthenticatorDescription[]"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="blockingGetPassword"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+</method>
+<method name="blockingGetUserData"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="key" type="java.lang.String">
+</parameter>
+</method>
+<method name="blockingInvalidateAuthToken"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+<parameter name="authToken" type="java.lang.String">
+</parameter>
+</method>
+<method name="blockingPeekAuthToken"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+</method>
+<method name="blockingRemoveAccount"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+</method>
+<method name="blockingSetAuthToken"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="authToken" type="java.lang.String">
+</parameter>
+</method>
+<method name="blockingSetPassword"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="password" type="java.lang.String">
+</parameter>
+</method>
+<method name="blockingSetUserData"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="key" type="java.lang.String">
+</parameter>
+<parameter name="value" type="java.lang.String">
+</parameter>
+</method>
+<method name="clearPassword"
+ return="android.accounts.Future1&lt;java.lang.Void&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.Void&gt;">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="confirmCredentials"
+ return="android.accounts.Future2"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="activity" type="android.app.Activity">
+</parameter>
+<parameter name="callback" type="android.accounts.Future2Callback">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="confirmPassword"
+ return="android.accounts.Future1&lt;java.lang.Boolean&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="password" type="java.lang.String">
+</parameter>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.Boolean&gt;">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="editProperties"
+ return="android.accounts.Future2"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+<parameter name="activity" type="android.app.Activity">
+</parameter>
+<parameter name="callback" type="android.accounts.Future2Callback">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="get"
+ return="android.accounts.AccountManager"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="context" type="android.content.Context">
+</parameter>
+</method>
+<method name="getAccounts"
+ return="android.accounts.Future1&lt;android.accounts.Account[]&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;android.accounts.Account[]&gt;">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="getAccountsByType"
+ return="android.accounts.Future1&lt;android.accounts.Account[]&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;android.accounts.Account[]&gt;">
+</parameter>
+<parameter name="type" type="java.lang.String">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="getAccountsWithTypeAndFeatures"
+ return="android.accounts.Future2"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="type" type="java.lang.String">
+</parameter>
+<parameter name="features" type="java.lang.String[]">
+</parameter>
+<parameter name="callback" type="android.accounts.Future2Callback">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="getAuthToken"
+ return="android.accounts.Future2"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="loginOptions" type="android.os.Bundle">
+</parameter>
+<parameter name="activity" type="android.app.Activity">
+</parameter>
+<parameter name="callback" type="android.accounts.Future2Callback">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="getAuthToken"
+ return="android.accounts.Future2"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="notifyAuthFailure" type="boolean">
+</parameter>
+<parameter name="callback" type="android.accounts.Future2Callback">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="getAuthTokenByFeatures"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="features" type="java.lang.String[]">
+</parameter>
+<parameter name="activityForPrompting" type="android.app.Activity">
+</parameter>
+<parameter name="addAccountOptions" type="android.os.Bundle">
+</parameter>
+<parameter name="loginOptions" type="android.os.Bundle">
+</parameter>
+<parameter name="callback" type="android.accounts.Future2Callback">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="getAuthenticatorTypes"
+ return="android.accounts.Future1&lt;android.accounts.AuthenticatorDescription[]&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;android.accounts.AuthenticatorDescription[]&gt;">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="getPassword"
+ return="android.accounts.Future1&lt;java.lang.String&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.String&gt;">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="getUserData"
+ return="android.accounts.Future1&lt;java.lang.String&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.String&gt;">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="key" type="java.lang.String">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="invalidateAuthToken"
+ return="android.accounts.Future1&lt;java.lang.Void&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.Void&gt;">
+</parameter>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+<parameter name="authToken" type="java.lang.String">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="peekAuthToken"
+ return="android.accounts.Future1&lt;java.lang.String&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.String&gt;">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="removeAccount"
+ return="android.accounts.Future1&lt;java.lang.Void&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.Void&gt;">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="removeOnAccountsUpdatedListener"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="listener" type="android.accounts.OnAccountsUpdatedListener">
+</parameter>
+</method>
+<method name="setAuthToken"
+ return="android.accounts.Future1&lt;java.lang.Void&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.Void&gt;">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="authToken" type="java.lang.String">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="setPassword"
+ return="android.accounts.Future1&lt;java.lang.Void&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.Void&gt;">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="password" type="java.lang.String">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="setUserData"
+ return="android.accounts.Future1&lt;java.lang.Void&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.accounts.Future1Callback&lt;java.lang.Void&gt;">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="key" type="java.lang.String">
+</parameter>
+<parameter name="value" type="java.lang.String">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+<method name="updateCredentials"
+ return="android.accounts.Future2"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="loginOptions" type="android.os.Bundle">
+</parameter>
+<parameter name="activity" type="android.app.Activity">
+</parameter>
+<parameter name="callback" type="android.accounts.Future2Callback">
+</parameter>
+<parameter name="handler" type="android.os.Handler">
+</parameter>
+</method>
+</class>
+<class name="AuthenticatorDescription"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.Parcelable">
+</implements>
+<constructor name="AuthenticatorDescription"
+ type="android.accounts.AuthenticatorDescription"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="type" type="java.lang.String">
+</parameter>
+<parameter name="packageName" type="java.lang.String">
+</parameter>
+<parameter name="labelId" type="int">
+</parameter>
+<parameter name="iconId" type="int">
+</parameter>
+</constructor>
+<method name="describeContents"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="newKey"
+ return="android.accounts.AuthenticatorDescription"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="type" type="java.lang.String">
+</parameter>
+</method>
+<method name="writeToParcel"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="dest" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<field name="CREATOR"
+ type="android.os.Parcelable.Creator"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="iconId"
+ type="int"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="labelId"
+ type="int"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="packageName"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="type"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<class name="AuthenticatorException"
+ extends="java.lang.Exception"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="AuthenticatorException"
+ type="android.accounts.AuthenticatorException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<constructor name="AuthenticatorException"
+ type="android.accounts.AuthenticatorException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="message" type="java.lang.String">
+</parameter>
+</constructor>
+<constructor name="AuthenticatorException"
+ type="android.accounts.AuthenticatorException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="message" type="java.lang.String">
+</parameter>
+<parameter name="cause" type="java.lang.Throwable">
+</parameter>
+</constructor>
+<constructor name="AuthenticatorException"
+ type="android.accounts.AuthenticatorException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="cause" type="java.lang.Throwable">
+</parameter>
+</constructor>
+</class>
+<class name="ChooseAccountActivity"
+ extends="android.app.ListActivity"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="ChooseAccountActivity"
+ type="android.accounts.ChooseAccountActivity"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<method name="onCreate"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="savedInstanceState" type="android.os.Bundle">
+</parameter>
+</method>
+</class>
+<class name="Constants"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<field name="ACCOUNTS_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;accounts&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACCOUNT_AUTHENTICATOR_RESPONSE_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;accountAuthenticatorResponse&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACCOUNT_MANAGER_RESPONSE_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;accountManagerResponse&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACCOUNT_NAME_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;authAccount&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACCOUNT_TYPE_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;accountType&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUTHENTICATOR_ATTRIBUTES_NAME"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;account-authenticator&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUTHENTICATOR_INTENT_ACTION"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.accounts.AccountAuthenticator&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUTHENTICATOR_META_DATA_NAME"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.accounts.AccountAuthenticator&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUTHENTICATOR_TYPES_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;authenticator_types&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUTHTOKEN_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;authtoken&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUTH_FAILED_MESSAGE_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;authFailedMessage&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="AUTH_TOKEN_LABEL_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;authTokenLabelKey&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="BOOLEAN_RESULT_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;booleanResult&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_CODE_BAD_ARGUMENTS"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="7"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_CODE_BAD_REQUEST"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="8"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_CODE_CANCELED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="4"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_CODE_INVALID_RESPONSE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="5"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_CODE_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;errorCode&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_CODE_NETWORK_ERROR"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="3"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_CODE_REMOTE_EXCEPTION"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_CODE_UNSUPPORTED_OPERATION"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="6"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_MESSAGE_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;errorMessage&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="INTENT_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;intent&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="LOGIN_ACCOUNTS_CHANGED_ACTION"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.accounts.LOGIN_ACCOUNTS_CHANGED&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="USERDATA_KEY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;userdata&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<interface name="Future1"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="java.util.concurrent.Future">
+</implements>
+<method name="getResult"
+ return="V"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<exception name="OperationCanceledException" type="android.accounts.OperationCanceledException">
+</exception>
+</method>
+<method name="getResult"
+ return="V"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="timeout" type="long">
+</parameter>
+<parameter name="unit" type="java.util.concurrent.TimeUnit">
+</parameter>
+<exception name="OperationCanceledException" type="android.accounts.OperationCanceledException">
+</exception>
+</method>
+</interface>
+<interface name="Future1Callback"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="run"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="future" type="android.accounts.Future1&lt;V&gt;">
+</parameter>
+</method>
+</interface>
+<interface name="Future2"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="java.util.concurrent.Future">
+</implements>
+<method name="getResult"
+ return="android.os.Bundle"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<exception name="AuthenticatorException" type="android.accounts.AuthenticatorException">
+</exception>
+<exception name="IOException" type="java.io.IOException">
+</exception>
+<exception name="OperationCanceledException" type="android.accounts.OperationCanceledException">
+</exception>
+</method>
+<method name="getResult"
+ return="android.os.Bundle"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="timeout" type="long">
+</parameter>
+<parameter name="unit" type="java.util.concurrent.TimeUnit">
+</parameter>
+<exception name="AuthenticatorException" type="android.accounts.AuthenticatorException">
+</exception>
+<exception name="IOException" type="java.io.IOException">
+</exception>
+<exception name="OperationCanceledException" type="android.accounts.OperationCanceledException">
+</exception>
+</method>
+</interface>
+<interface name="Future2Callback"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="run"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="future" type="android.accounts.Future2">
+</parameter>
+</method>
+</interface>
+<interface name="IAccountAuthenticator"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.IInterface">
+</implements>
+<method name="addAccount"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.IAccountAuthenticatorResponse">
+</parameter>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="requiredFeatures" type="java.lang.String[]">
+</parameter>
+<parameter name="options" type="android.os.Bundle">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="confirmCredentials"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.IAccountAuthenticatorResponse">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="confirmPassword"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.IAccountAuthenticatorResponse">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="password" type="java.lang.String">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="editProperties"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.IAccountAuthenticatorResponse">
+</parameter>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="getAuthToken"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.IAccountAuthenticatorResponse">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="options" type="android.os.Bundle">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="getAuthTokenLabel"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.IAccountAuthenticatorResponse">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="hasFeatures"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.IAccountAuthenticatorResponse">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="features" type="java.lang.String[]">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="updateCredentials"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="response" type="android.accounts.IAccountAuthenticatorResponse">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authTokenType" type="java.lang.String">
+</parameter>
+<parameter name="options" type="android.os.Bundle">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+</interface>
+<class name="IAccountAuthenticator.Stub"
+ extends="android.os.Binder"
+ abstract="true"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.accounts.IAccountAuthenticator">
+</implements>
+<constructor name="IAccountAuthenticator.Stub"
+ type="android.accounts.IAccountAuthenticator.Stub"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<method name="asBinder"
+ return="android.os.IBinder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="asInterface"
+ return="android.accounts.IAccountAuthenticator"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="obj" type="android.os.IBinder">
+</parameter>
+</method>
+<method name="onTransact"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="code" type="int">
+</parameter>
+<parameter name="data" type="android.os.Parcel">
+</parameter>
+<parameter name="reply" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+</class>
+<interface name="IAccountAuthenticatorResponse"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.IInterface">
+</implements>
+<method name="onError"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="errorCode" type="int">
+</parameter>
+<parameter name="errorMessage" type="java.lang.String">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="onRequestContinued"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="onResult"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="value" type="android.os.Bundle">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+</interface>
+<class name="IAccountAuthenticatorResponse.Stub"
+ extends="android.os.Binder"
+ abstract="true"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.accounts.IAccountAuthenticatorResponse">
+</implements>
+<constructor name="IAccountAuthenticatorResponse.Stub"
+ type="android.accounts.IAccountAuthenticatorResponse.Stub"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<method name="asBinder"
+ return="android.os.IBinder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="asInterface"
+ return="android.accounts.IAccountAuthenticatorResponse"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="obj" type="android.os.IBinder">
+</parameter>
+</method>
+<method name="onTransact"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="code" type="int">
+</parameter>
+<parameter name="data" type="android.os.Parcel">
+</parameter>
+<parameter name="reply" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+</class>
+<class name="NetworkErrorException"
+ extends="java.lang.Exception"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="NetworkErrorException"
+ type="android.accounts.NetworkErrorException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<constructor name="NetworkErrorException"
+ type="android.accounts.NetworkErrorException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="message" type="java.lang.String">
+</parameter>
+</constructor>
+<constructor name="NetworkErrorException"
+ type="android.accounts.NetworkErrorException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="message" type="java.lang.String">
+</parameter>
+<parameter name="cause" type="java.lang.Throwable">
+</parameter>
+</constructor>
+<constructor name="NetworkErrorException"
+ type="android.accounts.NetworkErrorException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="cause" type="java.lang.Throwable">
+</parameter>
+</constructor>
+</class>
+<interface name="OnAccountsUpdatedListener"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="onAccountsUpdated"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="accounts" type="android.accounts.Account[]">
+</parameter>
+</method>
+</interface>
+<class name="OperationCanceledException"
+ extends="java.lang.Exception"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="OperationCanceledException"
+ type="android.accounts.OperationCanceledException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<constructor name="OperationCanceledException"
+ type="android.accounts.OperationCanceledException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="message" type="java.lang.String">
+</parameter>
+</constructor>
+<constructor name="OperationCanceledException"
+ type="android.accounts.OperationCanceledException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="message" type="java.lang.String">
+</parameter>
+<parameter name="cause" type="java.lang.Throwable">
+</parameter>
+</constructor>
+<constructor name="OperationCanceledException"
+ type="android.accounts.OperationCanceledException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="cause" type="java.lang.Throwable">
+</parameter>
+</constructor>
+</class>
+</package>
 <package name="android.app"
 >
 <class name="Activity"
@@ -25179,6 +27512,75 @@
 </package>
 <package name="android.content"
 >
+<class name="AbstractCursorEntityIterator"
+ extends="java.lang.Object"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.content.EntityIterator">
+</implements>
+<constructor name="AbstractCursorEntityIterator"
+ type="android.content.AbstractCursorEntityIterator"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="db" type="android.database.sqlite.SQLiteDatabase">
+</parameter>
+<parameter name="entityCursor" type="android.database.Cursor">
+</parameter>
+</constructor>
+<method name="close"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="hasNext"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="newEntityFromCursorLocked"
+ return="android.content.Entity"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="cursor" type="android.database.Cursor">
+</parameter>
+</method>
+<method name="next"
+ return="android.content.Entity"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+</class>
 <class name="ActivityNotFoundException"
  extends="java.lang.RuntimeException"
  abstract="false"
@@ -26008,6 +28410,21 @@
  visibility="public"
 >
 </constructor>
+<method name="applyBatch"
+ return="android.content.ContentProviderResult[]"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="operations" type="java.util.ArrayList&lt;android.content.ContentProviderOperation&gt;">
+</parameter>
+<exception name="OperationApplicationException" type="android.content.OperationApplicationException">
+</exception>
+</method>
 <method name="attachInfo"
  return="void"
  abstract="false"
@@ -26127,6 +28544,21 @@
 <parameter name="values" type="android.content.ContentValues">
 </parameter>
 </method>
+<method name="insertEntity"
+ return="android.net.Uri"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="entity" type="android.content.Entity">
+</parameter>
+</method>
 <method name="isTemporary"
  return="boolean"
  abstract="false"
@@ -26245,6 +28677,25 @@
 <parameter name="sortOrder" type="java.lang.String">
 </parameter>
 </method>
+<method name="queryEntities"
+ return="android.content.EntityIterator"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="selection" type="java.lang.String">
+</parameter>
+<parameter name="selectionArgs" type="java.lang.String[]">
+</parameter>
+<parameter name="sortOrder" type="java.lang.String">
+</parameter>
+</method>
 <method name="setPathPermissions"
  return="void"
  abstract="false"
@@ -26303,6 +28754,671 @@
 <parameter name="selectionArgs" type="java.lang.String[]">
 </parameter>
 </method>
+<method name="updateEntity"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="entity" type="android.content.Entity">
+</parameter>
+</method>
+</class>
+<class name="ContentProviderClient"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="applyBatch"
+ return="android.content.ContentProviderResult[]"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="operations" type="java.util.ArrayList&lt;android.content.ContentProviderOperation&gt;">
+</parameter>
+<exception name="OperationApplicationException" type="android.content.OperationApplicationException">
+</exception>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="bulkInsert"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="url" type="android.net.Uri">
+</parameter>
+<parameter name="initialValues" type="android.content.ContentValues[]">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="delete"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="url" type="android.net.Uri">
+</parameter>
+<parameter name="selection" type="java.lang.String">
+</parameter>
+<parameter name="selectionArgs" type="java.lang.String[]">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="getLocalContentProvider"
+ return="android.content.ContentProvider"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getType"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="url" type="android.net.Uri">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="insert"
+ return="android.net.Uri"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="url" type="android.net.Uri">
+</parameter>
+<parameter name="initialValues" type="android.content.ContentValues">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="insertEntity"
+ return="android.net.Uri"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="entity" type="android.content.Entity">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="openAssetFile"
+ return="android.content.res.AssetFileDescriptor"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="url" type="android.net.Uri">
+</parameter>
+<parameter name="mode" type="java.lang.String">
+</parameter>
+<exception name="FileNotFoundException" type="java.io.FileNotFoundException">
+</exception>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="openFile"
+ return="android.os.ParcelFileDescriptor"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="url" type="android.net.Uri">
+</parameter>
+<parameter name="mode" type="java.lang.String">
+</parameter>
+<exception name="FileNotFoundException" type="java.io.FileNotFoundException">
+</exception>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="query"
+ return="android.database.Cursor"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="url" type="android.net.Uri">
+</parameter>
+<parameter name="projection" type="java.lang.String[]">
+</parameter>
+<parameter name="selection" type="java.lang.String">
+</parameter>
+<parameter name="selectionArgs" type="java.lang.String[]">
+</parameter>
+<parameter name="sortOrder" type="java.lang.String">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="queryEntities"
+ return="android.content.EntityIterator"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="selection" type="java.lang.String">
+</parameter>
+<parameter name="selectionArgs" type="java.lang.String[]">
+</parameter>
+<parameter name="sortOrder" type="java.lang.String">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="release"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="update"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="url" type="android.net.Uri">
+</parameter>
+<parameter name="values" type="android.content.ContentValues">
+</parameter>
+<parameter name="selection" type="java.lang.String">
+</parameter>
+<parameter name="selectionArgs" type="java.lang.String[]">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="updateEntity"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="entity" type="android.content.Entity">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+</class>
+<class name="ContentProviderOperation"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.Parcelable">
+</implements>
+<method name="apply"
+ return="android.content.ContentProviderResult"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="provider" type="android.content.ContentProvider">
+</parameter>
+<parameter name="backRefs" type="android.content.ContentProviderResult[]">
+</parameter>
+<parameter name="numBackRefs" type="int">
+</parameter>
+<exception name="OperationApplicationException" type="android.content.OperationApplicationException">
+</exception>
+</method>
+<method name="describeContents"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getUri"
+ return="android.net.Uri"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="isReadOperation"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="isWriteOperation"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="newCountQuery"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+</method>
+<method name="newDelete"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+</method>
+<method name="newInsert"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+</method>
+<method name="newUpdate"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+</method>
+<method name="resolveSelectionArgsBackReferences"
+ return="java.lang.String[]"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="backRefs" type="android.content.ContentProviderResult[]">
+</parameter>
+<parameter name="numBackRefs" type="int">
+</parameter>
+</method>
+<method name="resolveValueBackReferences"
+ return="android.content.ContentValues"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="backRefs" type="android.content.ContentProviderResult[]">
+</parameter>
+<parameter name="numBackRefs" type="int">
+</parameter>
+</method>
+<method name="writeToParcel"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="dest" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<field name="CREATOR"
+ type="android.os.Parcelable.Creator"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<class name="ContentProviderOperation.Builder"
+ extends="java.lang.Object"
+ abstract="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="build"
+ return="android.content.ContentProviderOperation"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="withExpectedCount"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="count" type="int">
+</parameter>
+</method>
+<method name="withSelection"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="selection" type="java.lang.String">
+</parameter>
+<parameter name="selectionArgs" type="java.lang.String[]">
+</parameter>
+</method>
+<method name="withSelectionBackReference"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="selectionArgIndex" type="int">
+</parameter>
+<parameter name="previousResult" type="int">
+</parameter>
+</method>
+<method name="withValue"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="key" type="java.lang.String">
+</parameter>
+<parameter name="value" type="java.lang.Object">
+</parameter>
+</method>
+<method name="withValueBackReference"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="key" type="java.lang.String">
+</parameter>
+<parameter name="previousResult" type="int">
+</parameter>
+</method>
+<method name="withValueBackReferences"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="backReferences" type="android.content.ContentValues">
+</parameter>
+</method>
+<method name="withValues"
+ return="android.content.ContentProviderOperation.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="values" type="android.content.ContentValues">
+</parameter>
+</method>
+</class>
+<class name="ContentProviderResult"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.Parcelable">
+</implements>
+<constructor name="ContentProviderResult"
+ type="android.content.ContentProviderResult"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+</constructor>
+<constructor name="ContentProviderResult"
+ type="android.content.ContentProviderResult"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="count" type="int">
+</parameter>
+</constructor>
+<constructor name="ContentProviderResult"
+ type="android.content.ContentProviderResult"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="source" type="android.os.Parcel">
+</parameter>
+</constructor>
+<method name="describeContents"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="writeToParcel"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="dest" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<field name="CREATOR"
+ type="android.os.Parcelable.Creator"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="count"
+ type="java.lang.Integer"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="uri"
+ type="android.net.Uri"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 </class>
 <class name="ContentQueryMap"
  extends="java.util.Observable"
@@ -26406,6 +29522,66 @@
 <parameter name="context" type="android.content.Context">
 </parameter>
 </constructor>
+<method name="acquireContentProviderClient"
+ return="android.content.ContentProviderClient"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+</method>
+<method name="acquireContentProviderClient"
+ return="android.content.ContentProviderClient"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="name" type="java.lang.String">
+</parameter>
+</method>
+<method name="addStatusChangeListener"
+ return="java.lang.Object"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="mask" type="int">
+</parameter>
+<parameter name="callback" type="android.content.SyncStatusObserver">
+</parameter>
+</method>
+<method name="applyBatch"
+ return="android.content.ContentProviderResult[]"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="authority" type="java.lang.String">
+</parameter>
+<parameter name="operations" type="java.util.ArrayList&lt;android.content.ContentProviderOperation&gt;">
+</parameter>
+<exception name="OperationApplicationException" type="android.content.OperationApplicationException">
+</exception>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
 <method name="bulkInsert"
  return="int"
  abstract="false"
@@ -26428,12 +29604,27 @@
  synchronized="false"
  static="false"
  final="false"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 <parameter name="uri" type="android.net.Uri">
 </parameter>
 </method>
+<method name="cancelSync"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authority" type="java.lang.String">
+</parameter>
+</method>
 <method name="delete"
  return="int"
  abstract="false"
@@ -26451,6 +29642,43 @@
 <parameter name="selectionArgs" type="java.lang.String[]">
 </parameter>
 </method>
+<method name="getMasterSyncAutomatically"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getSyncAdapterTypes"
+ return="android.content.SyncAdapterType[]"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getSyncAutomatically"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authority" type="java.lang.String">
+</parameter>
+</method>
 <method name="getType"
  return="java.lang.String"
  abstract="false"
@@ -26479,6 +29707,36 @@
 <parameter name="values" type="android.content.ContentValues">
 </parameter>
 </method>
+<method name="isSyncActive"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authority" type="java.lang.String">
+</parameter>
+</method>
+<method name="isSyncPending"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authority" type="java.lang.String">
+</parameter>
+</method>
 <method name="notifyChange"
  return="void"
  abstract="false"
@@ -26613,6 +29871,27 @@
 <parameter name="sortOrder" type="java.lang.String">
 </parameter>
 </method>
+<method name="queryEntities"
+ return="android.content.EntityIterator"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="selection" type="java.lang.String">
+</parameter>
+<parameter name="selectionArgs" type="java.lang.String[]">
+</parameter>
+<parameter name="sortOrder" type="java.lang.String">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
 <method name="registerContentObserver"
  return="void"
  abstract="false"
@@ -26630,6 +29909,66 @@
 <parameter name="observer" type="android.database.ContentObserver">
 </parameter>
 </method>
+<method name="removeStatusChangeListener"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="handle" type="java.lang.Object">
+</parameter>
+</method>
+<method name="requestSync"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authority" type="java.lang.String">
+</parameter>
+<parameter name="extras" type="android.os.Bundle">
+</parameter>
+</method>
+<method name="setMasterSyncAutomatically"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="sync" type="boolean">
+</parameter>
+</method>
+<method name="setSyncAutomatically"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="authority" type="java.lang.String">
+</parameter>
+<parameter name="sync" type="boolean">
+</parameter>
+</method>
 <method name="startSync"
  return="void"
  abstract="false"
@@ -26637,7 +29976,7 @@
  synchronized="false"
  static="false"
  final="false"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 <parameter name="uri" type="android.net.Uri">
@@ -26752,7 +30091,7 @@
  value="&quot;account&quot;"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -26785,6 +30124,17 @@
  value="&quot;force&quot;"
  static="true"
  final="true"
+ deprecated="deprecated"
+ visibility="public"
+>
+</field>
+<field name="SYNC_EXTRAS_MANUAL"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;force&quot;"
+ static="true"
+ final="true"
  deprecated="not deprecated"
  visibility="public"
 >
@@ -28369,6 +31719,17 @@
  visibility="public"
 >
 </field>
+<field name="ACCOUNT_SERVICE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;account&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="ACTIVITY_SERVICE"
  type="java.lang.String"
  transient="false"
@@ -29885,6 +33246,186 @@
 </parameter>
 </method>
 </interface>
+<class name="Entity"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.Parcelable">
+</implements>
+<constructor name="Entity"
+ type="android.content.Entity"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="values" type="android.content.ContentValues">
+</parameter>
+</constructor>
+<method name="addSubValue"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="values" type="android.content.ContentValues">
+</parameter>
+</method>
+<method name="describeContents"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getEntityValues"
+ return="android.content.ContentValues"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getSubValues"
+ return="java.util.ArrayList&lt;android.content.Entity.NamedContentValues&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="writeToParcel"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="dest" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<field name="CREATOR"
+ type="android.os.Parcelable.Creator"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<class name="Entity.NamedContentValues"
+ extends="java.lang.Object"
+ abstract="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="Entity.NamedContentValues"
+ type="android.content.Entity.NamedContentValues"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="values" type="android.content.ContentValues">
+</parameter>
+</constructor>
+<field name="uri"
+ type="android.net.Uri"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="values"
+ type="android.content.ContentValues"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<interface name="EntityIterator"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="close"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="hasNext"
+ return="boolean"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="next"
+ return="android.content.Entity"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+</interface>
 <interface name="IIntentReceiver"
  abstract="true"
  static="false"
@@ -32067,7 +35608,7 @@
  type="java.lang.String"
  transient="false"
  volatile="false"
- value="&quot;android.intent.action.ACTION_POWER_CONNECTED&quot;"
+ value="&quot;android.intent.action.POWER_CONNECTED&quot;"
  static="true"
  final="true"
  deprecated="not deprecated"
@@ -32078,7 +35619,7 @@
  type="java.lang.String"
  transient="false"
  volatile="false"
- value="&quot;android.intent.action.ACTION_POWER_DISCONNECTED&quot;"
+ value="&quot;android.intent.action.POWER_DISCONNECTED&quot;"
  static="true"
  final="true"
  deprecated="not deprecated"
@@ -32118,6 +35659,17 @@
  visibility="public"
 >
 </field>
+<field name="ACTION_REMOTE_INTENT"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.intent.action.REMOTE_INTENT&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="ACTION_RUN"
  type="java.lang.String"
  transient="false"
@@ -32700,6 +36252,17 @@
  visibility="public"
 >
 </field>
+<field name="EXTRA_REMOTE_INTENT_TOKEN"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.intent.extra.remote_intent_token&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="EXTRA_REPLACING"
  type="java.lang.String"
  transient="false"
@@ -34326,6 +37889,55 @@
 </parameter>
 </method>
 </class>
+<class name="OperationApplicationException"
+ extends="java.lang.Exception"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="OperationApplicationException"
+ type="android.content.OperationApplicationException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<constructor name="OperationApplicationException"
+ type="android.content.OperationApplicationException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="message" type="java.lang.String">
+</parameter>
+</constructor>
+<constructor name="OperationApplicationException"
+ type="android.content.OperationApplicationException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="message" type="java.lang.String">
+</parameter>
+<parameter name="cause" type="java.lang.Throwable">
+</parameter>
+</constructor>
+<constructor name="OperationApplicationException"
+ type="android.content.OperationApplicationException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="cause" type="java.lang.Throwable">
+</parameter>
+</constructor>
+</class>
 <class name="ReceiverCallNotAllowedException"
  extends="android.util.AndroidRuntimeException"
  abstract="false"
@@ -34816,6 +38428,116 @@
 </parameter>
 </method>
 </interface>
+<class name="SyncAdapterType"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.Parcelable">
+</implements>
+<constructor name="SyncAdapterType"
+ type="android.content.SyncAdapterType"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="authority" type="java.lang.String">
+</parameter>
+<parameter name="accountType" type="java.lang.String">
+</parameter>
+</constructor>
+<constructor name="SyncAdapterType"
+ type="android.content.SyncAdapterType"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="source" type="android.os.Parcel">
+</parameter>
+</constructor>
+<method name="describeContents"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="writeToParcel"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="dest" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<field name="CREATOR"
+ type="android.os.Parcelable.Creator"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="accountType"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="authority"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<interface name="SyncStatusObserver"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="onStatusChanged"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="which" type="int">
+</parameter>
+</method>
+</interface>
 <class name="UriMatcher"
  extends="java.lang.Object"
  abstract="false"
@@ -36886,6 +40608,19 @@
 <parameter name="flags" type="int">
 </parameter>
 </method>
+<method name="getInstallerPackageName"
+ return="java.lang.String"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="packageName" type="java.lang.String">
+</parameter>
+</method>
 <method name="getInstrumentationInfo"
  return="android.content.pm.InstrumentationInfo"
  abstract="true"
@@ -38274,7 +42009,7 @@
  volatile="false"
  static="false"
  final="false"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -42088,6 +45823,32 @@
 <parameter name="columnIndex" type="int">
 </parameter>
 </method>
+<method name="isFloat"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="columnIndex" type="int">
+</parameter>
+</method>
+<method name="isLong"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="columnIndex" type="int">
+</parameter>
+</method>
 <method name="isNull"
  return="boolean"
  abstract="false"
@@ -42101,6 +45862,19 @@
 <parameter name="columnIndex" type="int">
 </parameter>
 </method>
+<method name="isString"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="columnIndex" type="int">
+</parameter>
+</method>
 <method name="setWindow"
  return="void"
  abstract="false"
@@ -43181,6 +46955,36 @@
 <parameter name="col" type="int">
 </parameter>
 </method>
+<method name="isFloat"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="row" type="int">
+</parameter>
+<parameter name="col" type="int">
+</parameter>
+</method>
+<method name="isLong"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="row" type="int">
+</parameter>
+<parameter name="col" type="int">
+</parameter>
+</method>
 <method name="isNull"
  return="boolean"
  abstract="false"
@@ -43196,6 +47000,21 @@
 <parameter name="col" type="int">
 </parameter>
 </method>
+<method name="isString"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="row" type="int">
+</parameter>
+<parameter name="col" type="int">
+</parameter>
+</method>
 <method name="newFromParcel"
  return="android.database.CursorWindow"
  abstract="false"
@@ -44391,6 +48210,21 @@
 <exception name="FileNotFoundException" type="java.io.FileNotFoundException">
 </exception>
 </method>
+<method name="readExceptionWithOperationApplicationExceptionFromParcel"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="reply" type="android.os.Parcel">
+</parameter>
+<exception name="OperationApplicationException" type="android.content.OperationApplicationException">
+</exception>
+</method>
 <method name="sqlEscapeString"
  return="java.lang.String"
  abstract="false"
@@ -62762,6 +66596,19 @@
 <exception name="IOException" type="java.io.IOException">
 </exception>
 </method>
+<method name="setZoomCallback"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="cb" type="android.hardware.Camera.ZoomCallback">
+</parameter>
+</method>
 <method name="startPreview"
  return="void"
  abstract="false"
@@ -62801,6 +66648,25 @@
 <parameter name="jpeg" type="android.hardware.Camera.PictureCallback">
 </parameter>
 </method>
+<method name="takePicture"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="shutter" type="android.hardware.Camera.ShutterCallback">
+</parameter>
+<parameter name="raw" type="android.hardware.Camera.PictureCallback">
+</parameter>
+<parameter name="postview" type="android.hardware.Camera.PictureCallback">
+</parameter>
+<parameter name="jpeg" type="android.hardware.Camera.PictureCallback">
+</parameter>
+</method>
 <field name="CAMERA_ERROR_SERVER_DIED"
  type="int"
  transient="false"
@@ -63202,6 +67068,29 @@
 >
 </field>
 </class>
+<interface name="Camera.ZoomCallback"
+ abstract="true"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="onZoomUpdate"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="zoomLevel" type="int">
+</parameter>
+<parameter name="camera" type="android.hardware.Camera">
+</parameter>
+</method>
+</interface>
 <class name="GeomagneticField"
  extends="java.lang.Object"
  abstract="false"
@@ -69566,7 +73455,7 @@
  value="1"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -69577,7 +73466,7 @@
  value="0"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -69588,7 +73477,7 @@
  value="2"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -69599,6 +73488,358 @@
  value="3"
  static="true"
  final="true"
+ deprecated="deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_INVALID"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="-1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_BACK"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="524288"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_BACK_PROCESSED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="8388608"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_DEFAULT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="0"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_FRONT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="262144"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_FRONT_PROCESSED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="4194304"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_LEFT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="65536"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_LEFT_PROCESSED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1048576"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_MONO"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="262144"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_PRESSURE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16777216"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_RIGHT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="131072"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_RIGHT_PROCESSED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="2097152"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_STEREO"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="196608"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_X_AXIS"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="33554432"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_Y_AXIS"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="67108864"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_IN_Z_AXIS"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="134217728"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_5POINT1"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="63"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_7POINT1"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="255"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_BACK_CENTER"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="256"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_BACK_LEFT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_BACK_RIGHT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="32"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_DEFAULT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="0"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_FRONT_CENTER"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="4"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_FRONT_LEFT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_FRONT_LEFT_OF_CENTER"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="64"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_FRONT_RIGHT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="2"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_FRONT_RIGHT_OF_CENTER"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="128"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_LOW_FREQUENCY"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="8"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_MONO"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_QUAD"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="51"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_STEREO"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="3"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CHANNEL_OUT_SURROUND"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="263"
+ static="true"
+ final="true"
  deprecated="not deprecated"
  visibility="public"
 >
@@ -69716,6 +73957,19 @@
  visibility="public"
 >
 </method>
+<method name="getParameters"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="keys" type="java.lang.String">
+</parameter>
+</method>
 <method name="getRingerMode"
  return="int"
  abstract="false"
@@ -69834,6 +74088,17 @@
  visibility="public"
 >
 </method>
+<method name="isWiredHeadsetOn"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="loadSoundEffects"
  return="void"
  abstract="false"
@@ -69880,7 +74145,7 @@
  synchronized="false"
  static="false"
  final="false"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 <parameter name="on" type="boolean">
@@ -69925,6 +74190,19 @@
 <parameter name="mode" type="int">
 </parameter>
 </method>
+<method name="setParameters"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="keyValuePairs" type="java.lang.String">
+</parameter>
+</method>
 <method name="setRingerMode"
  return="void"
  abstract="false"
@@ -70030,6 +74308,19 @@
 <parameter name="vibrateSetting" type="int">
 </parameter>
 </method>
+<method name="setWiredHeadsetOn"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="deprecated"
+ visibility="public"
+>
+<parameter name="on" type="boolean">
+</parameter>
+</method>
 <method name="shouldVibrate"
  return="boolean"
  abstract="false"
@@ -70402,7 +74693,7 @@
  value="-1"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -70424,7 +74715,7 @@
  value="16"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -70435,7 +74726,7 @@
  value="4"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -70446,7 +74737,7 @@
  value="1"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -70457,7 +74748,7 @@
  value="8"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -70468,7 +74759,7 @@
  value="2"
  static="true"
  final="true"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </field>
@@ -70483,6 +74774,17 @@
  visibility="public"
 >
 </field>
+<field name="STREAM_DTMF"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="8"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="STREAM_MUSIC"
  type="int"
  transient="false"
@@ -72218,6 +76520,21 @@
  visibility="public"
 >
 </method>
+<method name="invoke"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="request" type="android.os.Parcel">
+</parameter>
+<parameter name="reply" type="android.os.Parcel">
+</parameter>
+</method>
 <method name="isLooping"
  return="boolean"
  abstract="false"
@@ -72240,6 +76557,17 @@
  visibility="public"
 >
 </method>
+<method name="newRequest"
+ return="android.os.Parcel"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="pause"
  return="void"
  abstract="false"
@@ -72645,6 +76973,17 @@
  visibility="public"
 >
 </field>
+<field name="MEDIA_INFO_METADATA_UPDATE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="802"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="MEDIA_INFO_NOT_SEEKABLE"
  type="int"
  transient="false"
@@ -103971,6 +108310,17 @@
  visibility="public"
 >
 </field>
+<field name="GROUP_SYNC_ACCOUNT_TYPE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;group_sync_account_type&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="GROUP_SYNC_ID"
  type="java.lang.String"
  transient="false"
@@ -105913,6 +110263,17 @@
  visibility="public"
 >
 </field>
+<field name="_SYNC_ACCOUNT_TYPE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;_sync_account_type&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 </interface>
 <class name="LiveFolders"
  extends="java.lang.Object"
@@ -109920,6 +114281,17 @@
  visibility="public"
 >
 </field>
+<field name="ALARM_ALERT"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;alarm_alert&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="ALWAYS_FINISH_ACTIVITIES"
  type="java.lang.String"
  transient="false"
@@ -110040,6 +114412,16 @@
  visibility="public"
 >
 </field>
+<field name="DEFAULT_ALARM_ALERT_URI"
+ type="android.net.Uri"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="DEFAULT_NOTIFICATION_URI"
  type="android.net.Uri"
  transient="false"
@@ -110963,6 +115345,170 @@
 >
 </field>
 </class>
+<class name="SyncStateContract"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="SyncStateContract"
+ type="android.provider.SyncStateContract"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+</class>
+<interface name="SyncStateContract.Columns"
+ abstract="true"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.provider.BaseColumns">
+</implements>
+<field name="ACCOUNT_NAME"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;account_name&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACCOUNT_TYPE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;account_type&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="DATA"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;data&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</interface>
+<class name="SyncStateContract.Constants"
+ extends="java.lang.Object"
+ abstract="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.provider.SyncStateContract.Columns">
+</implements>
+<constructor name="SyncStateContract.Constants"
+ type="android.provider.SyncStateContract.Constants"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<field name="CONTENT_DIRECTORY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;syncstate&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<class name="SyncStateContract.Helpers"
+ extends="java.lang.Object"
+ abstract="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="SyncStateContract.Helpers"
+ type="android.provider.SyncStateContract.Helpers"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<method name="get"
+ return="byte[]"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="provider" type="android.content.ContentProviderClient">
+</parameter>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+<method name="newSetOperation"
+ return="android.content.ContentProviderOperation"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="data" type="byte[]">
+</parameter>
+</method>
+<method name="set"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="provider" type="android.content.ContentProviderClient">
+</parameter>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="data" type="byte[]">
+</parameter>
+<exception name="RemoteException" type="android.os.RemoteException">
+</exception>
+</method>
+</class>
 <class name="UserDictionary"
  extends="java.lang.Object"
  abstract="false"
@@ -117116,7 +121662,7 @@
 >
 <parameter name="uri" type="android.net.Uri">
 </parameter>
-<parameter name="account" type="java.lang.String">
+<parameter name="accountName" type="java.lang.String">
 </parameter>
 <parameter name="authority" type="java.lang.String">
 </parameter>
@@ -119356,6 +123902,19 @@
 <parameter name="flags" type="int">
 </parameter>
 </method>
+<method name="getInstallerPackageName"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="packageName" type="java.lang.String">
+</parameter>
+</method>
 <method name="getInstrumentationInfo"
  return="android.content.pm.InstrumentationInfo"
  abstract="false"
@@ -125855,6 +130414,27 @@
 <parameter name="flags" type="int">
 </parameter>
 </method>
+<method name="formatDateRange"
+ return="java.util.Formatter"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="context" type="android.content.Context">
+</parameter>
+<parameter name="formatter" type="java.util.Formatter">
+</parameter>
+<parameter name="startMillis" type="long">
+</parameter>
+<parameter name="endMillis" type="long">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+</method>
 <method name="formatDateTime"
  return="java.lang.String"
  abstract="false"
@@ -134290,6 +138870,62 @@
 >
 </method>
 </class>
+<class name="Pair"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="Pair"
+ type="android.util.Pair"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="first" type="F">
+</parameter>
+<parameter name="second" type="S">
+</parameter>
+</constructor>
+<method name="create"
+ return="android.util.Pair&lt;A, B&gt;"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="a" type="A">
+</parameter>
+<parameter name="b" type="B">
+</parameter>
+</method>
+<field name="first"
+ type="F"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="second"
+ type="S"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
 <class name="PrintStreamPrinter"
  extends="java.lang.Object"
  abstract="false"
@@ -137260,6 +141896,17 @@
  visibility="public"
 >
 </field>
+<field name="VIRTUAL_KEY"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 </class>
 <class name="InflateException"
  extends="java.lang.RuntimeException"
@@ -138100,6 +142747,17 @@
  visibility="public"
 >
 </method>
+<method name="isCanceled"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="isModifierKey"
  return="boolean"
  abstract="false"
@@ -138215,6 +142873,17 @@
  visibility="public"
 >
 </field>
+<field name="FLAG_CANCELED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="32"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="FLAG_EDITOR_ACTION"
  type="int"
  transient="false"
@@ -138259,6 +142928,17 @@
  visibility="public"
 >
 </field>
+<field name="FLAG_VIRTUAL_HARD_KEY"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="64"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="FLAG_WOKE_HERE"
  type="int"
  transient="false"
@@ -140703,6 +145383,21 @@
 <parameter name="pos" type="int">
 </parameter>
 </method>
+<method name="getHistoricalPressure"
+ return="float"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="pointer" type="int">
+</parameter>
+<parameter name="pos" type="int">
+</parameter>
+</method>
 <method name="getHistoricalSize"
  return="float"
  abstract="false"
@@ -140716,6 +145411,34 @@
 <parameter name="pos" type="int">
 </parameter>
 </method>
+<method name="getHistoricalSize"
+ return="float"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="pointer" type="int">
+</parameter>
+<parameter name="pos" type="int">
+</parameter>
+</method>
+<method name="getHistoricalX"
+ return="float"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="pos" type="int">
+</parameter>
+</method>
 <method name="getHistoricalX"
  return="float"
  abstract="false"
@@ -140726,6 +145449,8 @@
  deprecated="not deprecated"
  visibility="public"
 >
+<parameter name="pointer" type="int">
+</parameter>
 <parameter name="pos" type="int">
 </parameter>
 </method>
@@ -140742,6 +145467,21 @@
 <parameter name="pos" type="int">
 </parameter>
 </method>
+<method name="getHistoricalY"
+ return="float"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="pointer" type="int">
+</parameter>
+<parameter name="pos" type="int">
+</parameter>
+</method>
 <method name="getHistorySize"
  return="int"
  abstract="false"
@@ -140764,6 +145504,17 @@
  visibility="public"
 >
 </method>
+<method name="getPointerCount"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="getPressure"
  return="float"
  abstract="false"
@@ -140775,6 +145526,19 @@
  visibility="public"
 >
 </method>
+<method name="getPressure"
+ return="float"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="pointer" type="int">
+</parameter>
+</method>
 <method name="getRawX"
  return="float"
  abstract="false"
@@ -140808,6 +145572,19 @@
  visibility="public"
 >
 </method>
+<method name="getSize"
+ return="float"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="pointer" type="int">
+</parameter>
+</method>
 <method name="getX"
  return="float"
  abstract="false"
@@ -140819,6 +145596,19 @@
  visibility="public"
 >
 </method>
+<method name="getX"
+ return="float"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="pointer" type="int">
+</parameter>
+</method>
 <method name="getXPrecision"
  return="float"
  abstract="false"
@@ -140841,6 +145631,19 @@
  visibility="public"
 >
 </method>
+<method name="getY"
+ return="float"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="pointer" type="int">
+</parameter>
+</method>
 <method name="getYPrecision"
  return="float"
  abstract="false"
@@ -140903,6 +145706,43 @@
 </parameter>
 <parameter name="action" type="int">
 </parameter>
+<parameter name="pointers" type="int">
+</parameter>
+<parameter name="x" type="float">
+</parameter>
+<parameter name="y" type="float">
+</parameter>
+<parameter name="pressure" type="float">
+</parameter>
+<parameter name="size" type="float">
+</parameter>
+<parameter name="metaState" type="int">
+</parameter>
+<parameter name="xPrecision" type="float">
+</parameter>
+<parameter name="yPrecision" type="float">
+</parameter>
+<parameter name="deviceId" type="int">
+</parameter>
+<parameter name="edgeFlags" type="int">
+</parameter>
+</method>
+<method name="obtain"
+ return="android.view.MotionEvent"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="downTime" type="long">
+</parameter>
+<parameter name="eventTime" type="long">
+</parameter>
+<parameter name="action" type="int">
+</parameter>
 <parameter name="x" type="float">
 </parameter>
 <parameter name="y" type="float">
@@ -141027,6 +145867,17 @@
  visibility="public"
 >
 </field>
+<field name="ACTION_MASK"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="255"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="ACTION_MOVE"
  type="int"
  transient="false"
@@ -141049,6 +145900,116 @@
  visibility="public"
 >
 </field>
+<field name="ACTION_POINTER_1_DOWN"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="5"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACTION_POINTER_1_UP"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="6"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACTION_POINTER_2_DOWN"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="261"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACTION_POINTER_2_UP"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="262"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACTION_POINTER_3_DOWN"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="517"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACTION_POINTER_3_UP"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="518"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACTION_POINTER_DOWN"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="5"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACTION_POINTER_MASK"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="65280"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACTION_POINTER_SHIFT"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="8"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACTION_POINTER_UP"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="6"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="ACTION_UP"
  type="int"
  transient="false"
@@ -158494,6 +163455,25 @@
 <parameter name="contentLength" type="long">
 </parameter>
 </method>
+<method name="onExceededDatabaseQuota"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="url" type="java.lang.String">
+</parameter>
+<parameter name="databaseIdentifier" type="java.lang.String">
+</parameter>
+<parameter name="currentQuota" type="long">
+</parameter>
+<parameter name="quotaUpdater" type="android.webkit.WebStorage.QuotaUpdater">
+</parameter>
+</method>
 <method name="onFormResubmission"
  return="void"
  abstract="false"
@@ -160135,6 +165115,25 @@
 <parameter name="resultMsg" type="android.os.Message">
 </parameter>
 </method>
+<method name="onExceededDatabaseQuota"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="url" type="java.lang.String">
+</parameter>
+<parameter name="databaseIdentifier" type="java.lang.String">
+</parameter>
+<parameter name="currentQuota" type="long">
+</parameter>
+<parameter name="quotaUpdater" type="android.webkit.WebStorage.QuotaUpdater">
+</parameter>
+</method>
 <method name="onJsAlert"
  return="boolean"
  abstract="false"
@@ -160520,6 +165519,28 @@
  visibility="public"
 >
 </method>
+<method name="getDatabaseEnabled"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getDatabasePath"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="getDefaultFixedFontSize"
  return="int"
  abstract="false"
@@ -160758,7 +165779,7 @@
  synchronized="true"
  static="false"
  final="false"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 </method>
@@ -160860,6 +165881,32 @@
 <parameter name="font" type="java.lang.String">
 </parameter>
 </method>
+<method name="setDatabaseEnabled"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="flag" type="boolean">
+</parameter>
+</method>
+<method name="setDatabasePath"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="databasePath" type="java.lang.String">
+</parameter>
+</method>
 <method name="setDefaultFixedFontSize"
  return="void"
  abstract="false"
@@ -161192,7 +166239,7 @@
  synchronized="true"
  static="false"
  final="false"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 <parameter name="use" type="boolean">
@@ -161414,6 +166461,44 @@
 >
 </method>
 </class>
+<class name="WebStorage"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="WebStorage"
+ type="android.webkit.WebStorage"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+</class>
+<interface name="WebStorage.QuotaUpdater"
+ abstract="true"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="updateQuota"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="newQuota" type="long">
+</parameter>
+</method>
+</interface>
 <class name="WebSyncManager"
  extends="java.lang.Object"
  abstract="true"
@@ -165517,6 +170602,17 @@
  visibility="public"
 >
 </method>
+<method name="getDropDownBackground"
+ return="android.graphics.drawable.Drawable"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="getDropDownHeight"
  return="int"
  abstract="false"
@@ -165528,6 +170624,28 @@
  visibility="public"
 >
 </method>
+<method name="getDropDownHorizontalOffset"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getDropDownVerticalOffset"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="getDropDownWidth"
  return="int"
  abstract="false"
@@ -165751,6 +170869,32 @@
 <parameter name="id" type="int">
 </parameter>
 </method>
+<method name="setDropDownBackgroundDrawable"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="d" type="android.graphics.drawable.Drawable">
+</parameter>
+</method>
+<method name="setDropDownBackgroundResource"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="id" type="int">
+</parameter>
+</method>
 <method name="setDropDownHeight"
  return="void"
  abstract="false"
@@ -165764,6 +170908,32 @@
 <parameter name="height" type="int">
 </parameter>
 </method>
+<method name="setDropDownHorizontalOffset"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="offset" type="int">
+</parameter>
+</method>
+<method name="setDropDownVerticalOffset"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="offset" type="int">
+</parameter>
+</method>
 <method name="setDropDownWidth"
  return="void"
  abstract="false"
@@ -175464,6 +180634,30 @@
 <parameter name="isExpanded" type="boolean">
 </parameter>
 </method>
+<method name="getViewBinder"
+ return="android.widget.SimpleCursorTreeAdapter.ViewBinder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="setViewBinder"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="viewBinder" type="android.widget.SimpleCursorTreeAdapter.ViewBinder">
+</parameter>
+</method>
 <method name="setViewImage"
  return="void"
  abstract="false"
@@ -175479,7 +180673,47 @@
 <parameter name="value" type="java.lang.String">
 </parameter>
 </method>
+<method name="setViewText"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="v" type="android.widget.TextView">
+</parameter>
+<parameter name="text" type="java.lang.String">
+</parameter>
+</method>
 </class>
+<interface name="SimpleCursorTreeAdapter.ViewBinder"
+ abstract="true"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="setViewValue"
+ return="boolean"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="view" type="android.view.View">
+</parameter>
+<parameter name="cursor" type="android.database.Cursor">
+</parameter>
+<parameter name="columnIndex" type="int">
+</parameter>
+</method>
+</interface>
 <class name="SimpleExpandableListAdapter"
  extends="android.widget.BaseExpandableListAdapter"
  abstract="false"
@@ -286593,7 +291827,11 @@
  deprecated="not deprecated"
  visibility="public"
 >
-<parameter name="val" type="int">
+<parameter name="buf" type="byte[]">
+</parameter>
+<parameter name="off" type="int">
+</parameter>
+<parameter name="nbytes" type="int">
 </parameter>
 </method>
 <method name="update"
@@ -286606,11 +291844,7 @@
  deprecated="not deprecated"
  visibility="public"
 >
-<parameter name="buf" type="byte[]">
-</parameter>
-<parameter name="off" type="int">
-</parameter>
-<parameter name="nbytes" type="int">
+<parameter name="val" type="int">
 </parameter>
 </method>
 </interface>
diff --git a/camera/libcameraservice/Android.mk b/camera/libcameraservice/Android.mk
index 96cc512..be78a62 100644
--- a/camera/libcameraservice/Android.mk
+++ b/camera/libcameraservice/Android.mk
@@ -42,6 +42,7 @@
 LOCAL_SHARED_LIBRARIES:= \
     libui \
     libutils \
+    libbinder \
     libcutils \
     libmedia
 
diff --git a/camera/libcameraservice/CameraHardwareStub.h b/camera/libcameraservice/CameraHardwareStub.h
index 0d26d47..efae935 100644
--- a/camera/libcameraservice/CameraHardwareStub.h
+++ b/camera/libcameraservice/CameraHardwareStub.h
@@ -21,8 +21,8 @@
 #include "FakeCamera.h"
 #include <utils/threads.h>
 #include <ui/CameraHardwareInterface.h>
-#include <utils/MemoryBase.h>
-#include <utils/MemoryHeapBase.h>
+#include <binder/MemoryBase.h>
+#include <binder/MemoryHeapBase.h>
 #include <utils/threads.h>
 
 namespace android {
diff --git a/camera/libcameraservice/CameraService.cpp b/camera/libcameraservice/CameraService.cpp
index e4b6791..e7c1fbb 100644
--- a/camera/libcameraservice/CameraService.cpp
+++ b/camera/libcameraservice/CameraService.cpp
@@ -20,12 +20,12 @@
 #define LOG_TAG "CameraService"
 #include <utils/Log.h>
 
-#include <utils/IServiceManager.h>
-#include <utils/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/IPCThreadState.h>
 #include <utils/String16.h>
 #include <utils/Errors.h>
-#include <utils/MemoryBase.h>
-#include <utils/MemoryHeapBase.h>
+#include <binder/MemoryBase.h>
+#include <binder/MemoryHeapBase.h>
 #include <ui/ICameraService.h>
 
 #include <media/mediaplayer.h>
@@ -33,7 +33,6 @@
 #include "CameraService.h"
 
 #include <cutils/atomic.h>
-#include <cutils/properties.h>
 
 namespace android {
 
@@ -199,13 +198,7 @@
 {
     sp<MediaPlayer> mp = new MediaPlayer();
     if (mp->setDataSource(file) == NO_ERROR) {
-        char value[PROPERTY_VALUE_MAX];
-        property_get("ro.camera.sound.forced", value, "0");
-        if (atoi(value)) {
-            mp->setAudioStreamType(AudioSystem::ENFORCED_AUDIBLE);
-        } else {
-            mp->setAudioStreamType(AudioSystem::SYSTEM);            
-        }
+        mp->setAudioStreamType(AudioSystem::ENFORCED_AUDIBLE);
         mp->prepare();
     } else {
         mp.clear();
@@ -227,6 +220,8 @@
 
     mMediaPlayerClick = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
     mMediaPlayerBeep = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
+    mOverlayW = 0;
+    mOverlayH = 0;
 
     // Callback is disabled by default
     mPreviewCallbackFlag = FRAME_CALLBACK_FLAG_NOOP;
@@ -399,6 +394,11 @@
     mHardware->cancelPicture(true, true, true);
     // Release the hardware resources.
     mHardware->release();
+    // Release the held overlay resources.
+    if (mUseOverlay)
+    {
+        mOverlayRef = 0;
+    }
     mHardware.clear();
 
     mCameraService->removeClient(mCameraClient);
@@ -420,11 +420,21 @@
     result = NO_ERROR;
     // asBinder() is safe on NULL (returns NULL)
     if (surface->asBinder() != mSurface->asBinder()) {
-        if (mSurface != 0 && !mUseOverlay) {
+        if (mSurface != 0) {
             LOGD("clearing old preview surface %p", mSurface.get());
-            mSurface->unregisterBuffers();
+            if ( !mUseOverlay)
+            {
+                mSurface->unregisterBuffers();
+            }
+            else
+            {
+                // Force the destruction of any previous overlay
+                sp<Overlay> dummy;
+                mHardware->setOverlay( dummy );
+            }
         }
         mSurface = surface;
+        mOverlayRef = 0;
         // If preview has been already started, set overlay or register preview
         // buffers now.
         if (mHardware->previewEnabled()) {
@@ -520,8 +530,8 @@
 
     const char *format = params.getPreviewFormat();
     int fmt;
-    if (!strcmp(format, "yuv422i"))
-        fmt = OVERLAY_FORMAT_YCbCr_422_I;
+    if (!strcmp(format, "yuv422i-yuyv"))
+        fmt = OVERLAY_FORMAT_YCbYCr_422_I;
     else if (!strcmp(format, "rgb565"))
         fmt = OVERLAY_FORMAT_RGB_565;
     else {
@@ -529,16 +539,35 @@
         return -EINVAL;
     }
 
+    if ( w != mOverlayW || h != mOverlayH )
+    {
+        // Force the destruction of any previous overlay
+        sp<Overlay> dummy;
+        mHardware->setOverlay( dummy );
+        mOverlayRef = 0;
+    }
+
     status_t ret = NO_ERROR;
     if (mSurface != 0) {
-        sp<OverlayRef> ref = mSurface->createOverlay(w, h, fmt);
-        ret = mHardware->setOverlay(new Overlay(ref));
+        if (mOverlayRef.get() == NULL) {
+            mOverlayRef = mSurface->createOverlay(w, h, fmt);
+            if ( mOverlayRef.get() == NULL )
+            {
+                LOGE("Overlay Creation Failed!");
+                return -EINVAL;
+            }
+            ret = mHardware->setOverlay(new Overlay(mOverlayRef));
+        }
     } else {
         ret = mHardware->setOverlay(NULL);
     }
     if (ret != NO_ERROR) {
         LOGE("mHardware->setOverlay() failed with status %d\n", ret);
     }
+
+    mOverlayW = w;
+    mOverlayH = h;
+
     return ret;
 }
 
@@ -1092,6 +1121,7 @@
     ssize_t offset;
     size_t size;
     sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
+    if ( !mUseOverlay )
     {
         Mutex::Autolock surfaceLock(mSurfaceLock);
         if (mSurface != NULL) {
@@ -1160,12 +1190,6 @@
 }
 
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t CameraService::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/camera/libcameraservice/CameraService.h b/camera/libcameraservice/CameraService.h
index ea93789..8a49fa6 100644
--- a/camera/libcameraservice/CameraService.h
+++ b/camera/libcameraservice/CameraService.h
@@ -189,6 +189,10 @@
                     sp<CameraHardwareInterface> mHardware;
                     pid_t                       mClientPid;
                     bool                        mUseOverlay;
+
+                    sp<OverlayRef>              mOverlayRef;
+                    int                         mOverlayW;
+                    int                         mOverlayH;
     };
 
 // ----------------------------------------------------------------------------
diff --git a/cmds/am/src/com/android/commands/am/Am.java b/cmds/am/src/com/android/commands/am/Am.java
index 3782136..0b4f25e 100644
--- a/cmds/am/src/com/android/commands/am/Am.java
+++ b/cmds/am/src/com/android/commands/am/Am.java
@@ -23,16 +23,19 @@
 import android.app.IInstrumentationWatcher;
 import android.app.Instrumentation;
 import android.content.ComponentName;
+import android.content.IIntentReceiver;
 import android.content.Intent;
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.ParcelFileDescriptor;
 import android.os.RemoteException;
 import android.os.ServiceManager;
+import android.util.AndroidException;
 import android.view.IWindowManager;
 
 import java.io.File;
 import java.io.FileNotFoundException;
+import java.net.URISyntaxException;
 import java.util.Iterator;
 import java.util.Set;
 
@@ -45,16 +48,29 @@
 
     private boolean mDebugOption = false;
 
+    // These are magic strings understood by the Eclipse plugin.
+    private static final String FATAL_ERROR_CODE = "Error type 1";
+    private static final String NO_SYSTEM_ERROR_CODE = "Error type 2";
+    private static final String NO_CLASS_ERROR_CODE = "Error type 3";
+
     /**
      * Command-line entry point.
      *
      * @param args The command-line arguments
      */
     public static void main(String[] args) {
-        (new Am()).run(args);
+        try {
+            (new Am()).run(args);
+        } catch (IllegalArgumentException e) {
+            showUsage();
+            System.err.println("Error: " + e.getMessage());
+        } catch (Exception e) {
+            System.err.println(e.toString());
+            System.exit(1);
+        }
     }
 
-    private void run(String[] args) {
+    private void run(String[] args) throws Exception {
         if (args.length < 1) {
             showUsage();
             return;
@@ -62,16 +78,14 @@
 
         mAm = ActivityManagerNative.getDefault();
         if (mAm == null) {
-            System.err.println("Error type 2");
-            System.err.println("Error: Unable to connect to activity manager; is the system running?");
-            showUsage();
-            return;
+            System.err.println(NO_SYSTEM_ERROR_CODE);
+            throw new AndroidException("Can't connect to activity manager; is the system running?");
         }
 
         mArgs = args;
-
         String op = args[0];
         mNextArg = 1;
+
         if (op.equals("start")) {
             runStart();
         } else if (op.equals("instrument")) {
@@ -81,13 +95,11 @@
         } else if (op.equals("profile")) {
             runProfile();
         } else {
-            System.err.println("Error: Unknown command: " + op);
-            showUsage();
-            return;
+            throw new IllegalArgumentException("Unknown command: " + op);
         }
     }
 
-    private Intent makeIntent() {
+    private Intent makeIntent() throws URISyntaxException {
         Intent intent = new Intent();
         boolean hasIntentInfo = false;
 
@@ -95,186 +107,146 @@
         Uri data = null;
         String type = null;
 
-        try {
-            String opt;
-            while ((opt=nextOption()) != null) {
-                if (opt.equals("-a")) {
-                    intent.setAction(nextOptionData());
-                    hasIntentInfo = true;
-                } else if (opt.equals("-d")) {
-                    data = Uri.parse(nextOptionData());
-                    hasIntentInfo = true;
-                } else if (opt.equals("-t")) {
-                    type = nextOptionData();
-                    hasIntentInfo = true;
-                } else if (opt.equals("-c")) {
-                    intent.addCategory(nextOptionData());
-                    hasIntentInfo = true;
-                } else if (opt.equals("-e") || opt.equals("--es")) {
-                    String key = nextOptionData();
-                    String value = nextOptionData();
-                    intent.putExtra(key, value);
-                    hasIntentInfo = true;
-                } else if (opt.equals("--ei")) {
-                    String key = nextOptionData();
-                    String value = nextOptionData();
-                    intent.putExtra(key, Integer.valueOf(value));
-                    hasIntentInfo = true;
-                } else if (opt.equals("--ez")) {
-                    String key = nextOptionData();
-                    String value = nextOptionData();
-                    intent.putExtra(key, Boolean.valueOf(value));
-                    hasIntentInfo = true;
-                } else if (opt.equals("-n")) {
-                    String str = nextOptionData();
-                    ComponentName cn = ComponentName.unflattenFromString(str);
-                    if (cn == null) {
-                        System.err.println("Error: Bad component name: " + str);
-                        showUsage();
-                        return null;
-                    }
-                    intent.setComponent(cn);
-                    hasIntentInfo = true;
-                } else if (opt.equals("-f")) {
-                    String str = nextOptionData();
-                    intent.setFlags(Integer.decode(str).intValue());
-                } else if (opt.equals("-D")) {
-                    mDebugOption = true;
-                } else {
-                    System.err.println("Error: Unknown option: " + opt);
-                    showUsage();
-                    return null;
-                }
+        String opt;
+        while ((opt=nextOption()) != null) {
+            if (opt.equals("-a")) {
+                intent.setAction(nextArgRequired());
+                hasIntentInfo = true;
+            } else if (opt.equals("-d")) {
+                data = Uri.parse(nextArgRequired());
+                hasIntentInfo = true;
+            } else if (opt.equals("-t")) {
+                type = nextArgRequired();
+                hasIntentInfo = true;
+            } else if (opt.equals("-c")) {
+                intent.addCategory(nextArgRequired());
+                hasIntentInfo = true;
+            } else if (opt.equals("-e") || opt.equals("--es")) {
+                String key = nextArgRequired();
+                String value = nextArgRequired();
+                intent.putExtra(key, value);
+                hasIntentInfo = true;
+            } else if (opt.equals("--ei")) {
+                String key = nextArgRequired();
+                String value = nextArgRequired();
+                intent.putExtra(key, Integer.valueOf(value));
+                hasIntentInfo = true;
+            } else if (opt.equals("--ez")) {
+                String key = nextArgRequired();
+                String value = nextArgRequired();
+                intent.putExtra(key, Boolean.valueOf(value));
+                hasIntentInfo = true;
+            } else if (opt.equals("-n")) {
+                String str = nextArgRequired();
+                ComponentName cn = ComponentName.unflattenFromString(str);
+                if (cn == null) throw new IllegalArgumentException("Bad component name: " + str);
+                intent.setComponent(cn);
+                hasIntentInfo = true;
+            } else if (opt.equals("-f")) {
+                String str = nextArgRequired();
+                intent.setFlags(Integer.decode(str).intValue());
+            } else if (opt.equals("-D")) {
+                mDebugOption = true;
+            } else {
+                System.err.println("Error: Unknown option: " + opt);
+                showUsage();
+                return null;
             }
-        } catch (RuntimeException ex) {
-            System.err.println("Error: " + ex.toString());
-            showUsage();
-            return null;
         }
         intent.setDataAndType(data, type);
 
         String uri = nextArg();
         if (uri != null) {
-            try {
-                Intent oldIntent = intent;
-                try {
-                    intent = Intent.getIntent(uri);
-                } catch (java.net.URISyntaxException ex) {
-                    System.err.println("Bad URI: " + uri);
-                    showUsage();
-                    return null;
-                }
-                if (oldIntent.getAction() != null) {
-                    intent.setAction(oldIntent.getAction());
-                }
-                if (oldIntent.getData() != null || oldIntent.getType() != null) {
-                    intent.setDataAndType(oldIntent.getData(), oldIntent.getType());
-                }
-                Set cats = oldIntent.getCategories();
-                if (cats != null) {
-                    Iterator it = cats.iterator();
-                    while (it.hasNext()) {
-                        intent.addCategory((String)it.next());
-                    }
-                }
-            } catch (RuntimeException ex) {
-                System.err.println("Error creating from URI: " + ex.toString());
-                showUsage();
-                return null;
+            Intent oldIntent = intent;
+            intent = Intent.getIntent(uri);
+            if (oldIntent.getAction() != null) {
+                intent.setAction(oldIntent.getAction());
             }
-        } else if (!hasIntentInfo) {
-            System.err.println("Error: No intent supplied");
-            showUsage();
-            return null;
+            if (oldIntent.getData() != null || oldIntent.getType() != null) {
+                intent.setDataAndType(oldIntent.getData(), oldIntent.getType());
+            }
+            Set cats = oldIntent.getCategories();
+            if (cats != null) {
+                Iterator it = cats.iterator();
+                while (it.hasNext()) {
+                    intent.addCategory((String)it.next());
+                }
+            }
+            hasIntentInfo = true;
         }
 
+        if (!hasIntentInfo) throw new IllegalArgumentException("No intent supplied");
         return intent;
     }
 
-    private void runStart() {
+    private void runStart() throws Exception {
         Intent intent = makeIntent();
-        
-        if (intent != null) {
-            System.out.println("Starting: " + intent);
-            try {
-                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-                // XXX should do something to determine the MIME type.
-                int res = mAm.startActivity(null, intent, intent.getType(),
-                        null, 0, null, null, 0, false, mDebugOption);
-                switch (res) {
-                    case IActivityManager.START_SUCCESS:
-                        break;
-                    case IActivityManager.START_SWITCHES_CANCELED:
-                        System.err.println(
-                                "Warning: Activity not started because the "
-                                + " current activity is being kept for the user.");
-                        break;
-                    case IActivityManager.START_DELIVERED_TO_TOP:
-                        System.err.println(
-                                "Warning: Activity not started, intent has "
-                                + "been delivered to currently running "
-                                + "top-most instance.");
-                        break;
-                    case IActivityManager.START_RETURN_INTENT_TO_CALLER:
-                        System.err.println(
-                                "Warning: Activity not started because intent "
-                                + "should be handled by the caller");
-                        break;
-                    case IActivityManager.START_TASK_TO_FRONT:
-                        System.err.println(
-                                "Warning: Activity not started, its current "
-                                + "task has been brought to the front");
-                        break;
-                    case IActivityManager.START_INTENT_NOT_RESOLVED:
-                        System.err.println(
-                                "Error: Activity not started, unable to "
-                                + "resolve " + intent.toString());
-                        break;
-                    case IActivityManager.START_CLASS_NOT_FOUND:
-                        System.err.println("Error type 3");
-                        System.err.println("Error: Activity class " +
-                                intent.getComponent().toShortString()
-                                + " does not exist.");
-                        break;
-                    case IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
-                        System.err.println(
-                                "Error: Activity not started, you requested to "
-                                + "both forward and receive its result");
-                        break;
-                    case IActivityManager.START_PERMISSION_DENIED:
-                        System.err.println(
-                                "Error: Activity not started, you do not "
-                                + "have permission to access it.");
-                        break;
-                    default:
-                        System.err.println(
-                                "Error: Activity not started, unknown error "
-                                + "code " + res);
-                        break;
-                }
-            } catch (RemoteException e) {
-                System.err.println("Error type 1");
+        System.out.println("Starting: " + intent);
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        // XXX should do something to determine the MIME type.
+        int res = mAm.startActivity(null, intent, intent.getType(),
+                null, 0, null, null, 0, false, mDebugOption);
+        switch (res) {
+            case IActivityManager.START_SUCCESS:
+                break;
+            case IActivityManager.START_SWITCHES_CANCELED:
+                System.err.println(
+                        "Warning: Activity not started because the "
+                        + " current activity is being kept for the user.");
+                break;
+            case IActivityManager.START_DELIVERED_TO_TOP:
+                System.err.println(
+                        "Warning: Activity not started, intent has "
+                        + "been delivered to currently running "
+                        + "top-most instance.");
+                break;
+            case IActivityManager.START_RETURN_INTENT_TO_CALLER:
+                System.err.println(
+                        "Warning: Activity not started because intent "
+                        + "should be handled by the caller");
+                break;
+            case IActivityManager.START_TASK_TO_FRONT:
+                System.err.println(
+                        "Warning: Activity not started, its current "
+                        + "task has been brought to the front");
+                break;
+            case IActivityManager.START_INTENT_NOT_RESOLVED:
                 System.err.println(
                         "Error: Activity not started, unable to "
-                        + "call on to activity manager service");
-            }
+                        + "resolve " + intent.toString());
+                break;
+            case IActivityManager.START_CLASS_NOT_FOUND:
+                System.err.println(NO_CLASS_ERROR_CODE);
+                System.err.println("Error: Activity class " +
+                        intent.getComponent().toShortString()
+                        + " does not exist.");
+                break;
+            case IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
+                System.err.println(
+                        "Error: Activity not started, you requested to "
+                        + "both forward and receive its result");
+                break;
+            case IActivityManager.START_PERMISSION_DENIED:
+                System.err.println(
+                        "Error: Activity not started, you do not "
+                        + "have permission to access it.");
+                break;
+            default:
+                System.err.println(
+                        "Error: Activity not started, unknown error code " + res);
+                break;
         }
     }
 
-    private void sendBroadcast() {
+    private void sendBroadcast() throws Exception {
         Intent intent = makeIntent();
-        
-        if (intent != null) {
-            System.out.println("Broadcasting: " + intent);
-            try {
-                mAm.broadcastIntent(null, intent, null, null, 0, null, null,
-                        null, true, false);
-            } catch (RemoteException e) {
-            }
-        }
+        IntentReceiver receiver = new IntentReceiver();
+        System.out.println("Broadcasting: " + intent);
+        mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, null, true, false);
+        receiver.waitForFinish();
     }
 
-    private void runInstrument() {
+    private void runInstrument() throws Exception {
         String profileFile = null;
         boolean wait = false;
         boolean rawMode = false;
@@ -283,46 +255,30 @@
         String argKey = null, argValue = null;
         IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
 
-        try {
-            String opt;
-            while ((opt=nextOption()) != null) {
-                if (opt.equals("-p")) {
-                    profileFile = nextOptionData();
-                } else if (opt.equals("-w")) {
-                    wait = true;
-                } else if (opt.equals("-r")) {
-                    rawMode = true;
-                } else if (opt.equals("-e")) {
-                    argKey = nextOptionData();
-                    argValue = nextOptionData();
-                    args.putString(argKey, argValue);
-                } else if (opt.equals("--no_window_animation")) {
-                    no_window_animation = true;
-                } else {
-                    System.err.println("Error: Unknown option: " + opt);
-                    showUsage();
-                    return;
-                }
+        String opt;
+        while ((opt=nextOption()) != null) {
+            if (opt.equals("-p")) {
+                profileFile = nextArgRequired();
+            } else if (opt.equals("-w")) {
+                wait = true;
+            } else if (opt.equals("-r")) {
+                rawMode = true;
+            } else if (opt.equals("-e")) {
+                argKey = nextArgRequired();
+                argValue = nextArgRequired();
+                args.putString(argKey, argValue);
+            } else if (opt.equals("--no_window_animation")) {
+                no_window_animation = true;
+            } else {
+                System.err.println("Error: Unknown option: " + opt);
+                showUsage();
+                return;
             }
-        } catch (RuntimeException ex) {
-            System.err.println("Error: " + ex.toString());
-            showUsage();
-            return;
         }
 
-        String cnArg = nextArg();
-        if (cnArg == null) {
-            System.err.println("Error: No instrumentation component supplied");
-            showUsage();
-            return;
-        }
-        
+        String cnArg = nextArgRequired();
         ComponentName cn = ComponentName.unflattenFromString(cnArg);
-        if (cn == null) {
-            System.err.println("Error: Bad component name: " + cnArg);
-            showUsage();
-            return;
-        }
+        if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg);
 
         InstrumentationWatcher watcher = null;
         if (wait) {
@@ -331,22 +287,13 @@
         }
         float[] oldAnims = null;
         if (no_window_animation) {
-            try {
-                oldAnims = wm.getAnimationScales();
-                wm.setAnimationScale(0, 0.0f);
-                wm.setAnimationScale(1, 0.0f);
-            } catch (RemoteException e) {
-            }
+            oldAnims = wm.getAnimationScales();
+            wm.setAnimationScale(0, 0.0f);
+            wm.setAnimationScale(1, 0.0f);
         }
 
-        try {
-            if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher)) {
-                System.out.println("INSTRUMENTATION_FAILED: " +
-                        cn.flattenToString());
-                showUsage();
-                return;
-            }
-        } catch (RemoteException e) {
+        if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher)) {
+            throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString());
         }
 
         if (watcher != null) {
@@ -356,9 +303,57 @@
         }
 
         if (oldAnims != null) {
+            wm.setAnimationScales(oldAnims);
+        }
+    }
+
+    private void runProfile() throws Exception {
+        String profileFile = null;
+        boolean start = false;
+        String process = nextArgRequired();
+        ParcelFileDescriptor fd = null;
+
+        String cmd = nextArgRequired();
+        if ("start".equals(cmd)) {
+            start = true;
+            profileFile = nextArgRequired();
             try {
-                wm.setAnimationScales(oldAnims);
-            } catch (RemoteException e) {
+                fd = ParcelFileDescriptor.open(
+                        new File(profileFile),
+                        ParcelFileDescriptor.MODE_CREATE |
+                        ParcelFileDescriptor.MODE_TRUNCATE |
+                        ParcelFileDescriptor.MODE_READ_WRITE);
+            } catch (FileNotFoundException e) {
+                System.err.println("Error: Unable to open file: " + profileFile);
+                return;
+            }
+        } else if (!"stop".equals(cmd)) {
+            throw new IllegalArgumentException("Profile command " + cmd + " not valid");
+        }
+
+        if (!mAm.profileControl(process, start, profileFile, fd)) {
+            throw new AndroidException("PROFILE FAILED on process " + process);
+        }
+    }
+
+    private class IntentReceiver extends IIntentReceiver.Stub {
+        private boolean mFinished = false;
+
+        public synchronized void performReceive(
+                Intent intent, int rc, String data, Bundle ext, boolean ord) {
+            String line = "Broadcast completed: result=" + rc;
+            if (data != null) line = line + ", data=\"" + data + "\"";
+            if (ext != null) line = line + ", extras: " + ext;
+            System.out.println(line);
+            mFinished = true;
+            notifyAll();
+        }
+
+        public synchronized void waitForFinish() {
+            try {
+                while (!mFinished) wait();
+            } catch (InterruptedException e) {
+                throw new IllegalStateException(e);
             }
         }
     }
@@ -366,7 +361,7 @@
     private class InstrumentationWatcher extends IInstrumentationWatcher.Stub {
         private boolean mFinished = false;
         private boolean mRawMode = false;
-        
+
         /**
          * Set or reset "raw mode".  In "raw mode", all bundles are dumped.  In "pretty mode", 
          * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that.
@@ -375,7 +370,7 @@
         public void setRawOutput(boolean rawMode) {
             mRawMode = rawMode;
         }
-        
+
         public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) {
             synchronized (this) {
                 // pretty printer mode?
@@ -431,6 +426,7 @@
                         }
                         wait(1000);
                     } catch (InterruptedException e) {
+                        throw new IllegalStateException(e);
                     }
                 }
             }
@@ -438,62 +434,11 @@
         }
     }
 
-    private void runProfile() {
-        String profileFile = null;
-        boolean start = false;
-
-        String process = nextArg();
-        if (process == null) {
-            System.err.println("Error: No profile process supplied");
-            showUsage();
-            return;
-        }
-        
-        ParcelFileDescriptor fd = null;
-        
-        String cmd = nextArg();
-        if ("start".equals(cmd)) {
-            start = true;
-            profileFile = nextArg();
-            if (profileFile == null) {
-                System.err.println("Error: No profile file path supplied");
-                showUsage();
-                return;
-            }
-            try {
-                fd = ParcelFileDescriptor.open(
-                        new File(profileFile),
-                        ParcelFileDescriptor.MODE_CREATE |
-                        ParcelFileDescriptor.MODE_TRUNCATE |
-                        ParcelFileDescriptor.MODE_READ_WRITE);
-            } catch (FileNotFoundException e) {
-                System.err.println("Error: Unable to open file: " + profileFile);
-                return;
-            }
-        } else if (!"stop".equals(cmd)) {
-            System.err.println("Error: Profile command " + cmd + " not valid");
-            showUsage();
-            return;
-        }
-        
-        try {
-            if (!mAm.profileControl(process, start, profileFile, fd)) {
-                System.err.println("PROFILE FAILED on process " + process);
-                return;
-            }
-        } catch (IllegalArgumentException e) {
-            System.out.println("PROFILE FAILED: " + e.getMessage());
-            return;
-        } catch (IllegalStateException e) {
-            System.out.println("PROFILE FAILED: " + e.getMessage());
-            return;
-        } catch (RemoteException e) {
-            System.out.println("PROFILE FAILED: activity manager gone");
-            return;
-        }
-    }
-
     private String nextOption() {
+        if (mCurArgData != null) {
+            String prev = mArgs[mNextArg - 1];
+            throw new IllegalArgumentException("No argument expected after \"" + prev + "\"");
+        }
         if (mNextArg >= mArgs.length) {
             return null;
         }
@@ -518,41 +463,52 @@
         return arg;
     }
 
-    private String nextOptionData() {
+    private String nextArg() {
         if (mCurArgData != null) {
-            return mCurArgData;
-        }
-        if (mNextArg >= mArgs.length) {
+            String arg = mCurArgData;
+            mCurArgData = null;
+            return arg;
+        } else if (mNextArg < mArgs.length) {
+            return mArgs[mNextArg++];
+        } else {
             return null;
         }
-        String data = mArgs[mNextArg];
-        mNextArg++;
-        return data;
     }
 
-    private String nextArg() {
-        if (mNextArg >= mArgs.length) {
-            return null;
+    private String nextArgRequired() {
+        String arg = nextArg();
+        if (arg == null) {
+            String prev = mArgs[mNextArg - 1];
+            throw new IllegalArgumentException("Argument expected after \"" + prev + "\"");
         }
-        String arg = mArgs[mNextArg];
-        mNextArg++;
         return arg;
     }
 
-    private void showUsage() {
-        System.err.println("usage: am [start|broadcast|instrument|profile]");
-        System.err.println("       am start [-D] INTENT");
-        System.err.println("       am broadcast INTENT");
-        System.err.println("       am instrument [-r] [-e <ARG_NAME> <ARG_VALUE>] [-p <PROF_FILE>]");
-        System.err.println("                [-w] <COMPONENT> ");
-        System.err.println("       am profile <PROCESS> [start <PROF_FILE>|stop]");
-        System.err.println("");
-        System.err.println("       INTENT is described with:");
-        System.err.println("                [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]");
-        System.err.println("                [-c <CATEGORY> [-c <CATEGORY>] ...]");
-        System.err.println("                [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]");
-        System.err.println("                [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]");
-        System.err.println("                [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]");
-        System.err.println("                [-n <COMPONENT>] [-f <FLAGS>] [<URI>]");
+    private static void showUsage() {
+        System.err.println(
+                "usage: am [subcommand] [options]\n" +
+                "\n" +
+                "    start an Activity: am start [-D] <INTENT>\n" +
+                "        -D: enable debugging\n" +
+                "\n" +
+                "    send a broadcast Intent: am broadcast <INTENT>\n" +
+                "\n" +
+                "    start an Instrumentation: am instrument [flags] <COMPONENT>\n" +
+                "        -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)\n" +
+                "        -e <NAME> <VALUE>: set argument <NAME> to <VALUE>\n" +
+                "        -p <FILE>: write profiling data to <FILE>\n" +
+                "        -w: wait for instrumentation to finish before returning\n" +
+                "\n" +
+                "    start profiling: am profile <PROCESS> start <FILE>\n" +
+                "    stop profiling: am profile <PROCESS> stop\n" +
+                "\n" +
+                "    <INTENT> specifications include these flags:\n" +
+                "        [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]\n" +
+                "        [-c <CATEGORY> [-c <CATEGORY>] ...]\n" +
+                "        [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]\n" +
+                "        [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]\n" +
+                "        [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]\n" +
+                "        [-n <COMPONENT>] [-f <FLAGS>] [<URI>]\n"
+                );
     }
 }
diff --git a/cmds/app_process/app_main.cpp b/cmds/app_process/app_main.cpp
index d825d5a..7decf9a 100644
--- a/cmds/app_process/app_main.cpp
+++ b/cmds/app_process/app_main.cpp
@@ -7,8 +7,8 @@
 
 #define LOG_TAG "appproc"
 
-#include <utils/IPCThreadState.h>
-#include <utils/ProcessState.h>
+#include <binder/IPCThreadState.h>
+#include <binder/ProcessState.h>
 #include <utils/Log.h>
 #include <cutils/process_name.h>
 #include <cutils/memory.h>
diff --git a/cmds/bootanimation/Android.mk b/cmds/bootanimation/Android.mk
index 9c94c2e..3449de1 100644
--- a/cmds/bootanimation/Android.mk
+++ b/cmds/bootanimation/Android.mk
@@ -12,12 +12,13 @@
 	endif
 endif
 
+LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+
 LOCAL_SHARED_LIBRARIES := \
 	libcutils \
 	libutils \
     libui \
-	libcorecg \
-	libsgl \
+	libskia \
     libEGL \
     libGLESv1_CM
 
diff --git a/cmds/bootanimation/BootAnimation.cpp b/cmds/bootanimation/BootAnimation.cpp
index 3b9db8d..e2d01de 100644
--- a/cmds/bootanimation/BootAnimation.cpp
+++ b/cmds/bootanimation/BootAnimation.cpp
@@ -14,15 +14,13 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "BootAnimation"
-
 #include <stdint.h>
 #include <sys/types.h>
 #include <math.h>
 #include <fcntl.h>
 #include <utils/misc.h>
 
-#include <utils/IPCThreadState.h>
+#include <binder/IPCThreadState.h>
 #include <utils/threads.h>
 #include <utils/Atomic.h>
 #include <utils/Errors.h>
@@ -35,7 +33,7 @@
 #include <ui/DisplayInfo.h>
 #include <ui/ISurfaceComposer.h>
 #include <ui/ISurfaceFlingerClient.h>
-#include <ui/EGLNativeWindowSurface.h>
+#include <ui/FramebufferNativeWindow.h>
 
 #include <core/SkBitmap.h>
 #include <images/SkImageDecoder.h>
@@ -130,12 +128,15 @@
         return -1;
 
     // create the native surface
-    sp<Surface> s = session()->createSurface(getpid(), 0, dinfo.w, dinfo.h,
-            PIXEL_FORMAT_RGB_565, ISurfaceComposer::eGPU);
+    sp<SurfaceControl> control = session()->createSurface(
+            getpid(), 0, dinfo.w, dinfo.h, PIXEL_FORMAT_RGB_565,
+            ISurfaceComposer::eGPU);
     session()->openTransaction();
-    s->setLayer(0x40000000);
+    control->setLayer(0x40000000);
     session()->closeTransaction();
 
+    sp<Surface> s = control->getSurface();
+
     // initialize opengl and egl
     const EGLint attribs[] = { EGL_RED_SIZE, 5, EGL_GREEN_SIZE, 6,
             EGL_BLUE_SIZE, 5, EGL_DEPTH_SIZE, 0, EGL_NONE };
@@ -150,9 +151,7 @@
     eglInitialize(display, 0, 0);
     eglChooseConfig(display, attribs, &config, 1, &numConfigs);
 
-    mNativeWindowSurface = new EGLNativeWindowSurface(s);
-    surface = eglCreateWindowSurface(display, config, 
-            mNativeWindowSurface.get(), NULL);
+    surface = eglCreateWindowSurface(display, config, s.get(), NULL);
 
     context = eglCreateContext(display, config, NULL, NULL);
     eglQuerySurface(display, surface, EGL_WIDTH, &w);
@@ -163,6 +162,7 @@
     mSurface = surface;
     mWidth = w;
     mHeight = h;
+    mFlingerSurfaceControl = control;
     mFlingerSurface = s;
 
     // initialize GL
@@ -178,8 +178,8 @@
     eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
     eglDestroyContext(mDisplay, mContext);
     eglDestroySurface(mDisplay, mSurface);
-    mNativeWindowSurface.clear();
     mFlingerSurface.clear();
+    mFlingerSurfaceControl.clear();
     eglTerminate(mDisplay);
     IPCThreadState::self()->stopProcess();
     return r;
@@ -200,8 +200,7 @@
     const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
 
     // draw and update only what we need
-    mNativeWindowSurface->setSwapRectangle(updateRect.left,
-            updateRect.top, updateRect.width(), updateRect.height());
+    mFlingerSurface->setSwapRectangle(updateRect);
 
     glEnable(GL_SCISSOR_TEST);
     glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
diff --git a/cmds/bootanimation/BootAnimation.h b/cmds/bootanimation/BootAnimation.h
index 42e9eed..796077d 100644
--- a/cmds/bootanimation/BootAnimation.h
+++ b/cmds/bootanimation/BootAnimation.h
@@ -34,7 +34,6 @@
 namespace android {
 
 class AssetManager;
-class EGLNativeWindowSurface;
 
 // ---------------------------------------------------------------------------
 
@@ -68,8 +67,8 @@
     EGLDisplay  mDisplay;
     EGLDisplay  mContext;
     EGLDisplay  mSurface;
+    sp<SurfaceControl> mFlingerSurfaceControl;
     sp<Surface> mFlingerSurface;
-    sp<EGLNativeWindowSurface> mNativeWindowSurface;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/cmds/bootanimation/bootanimation_main.cpp b/cmds/bootanimation/bootanimation_main.cpp
index 675ea81..346f156 100644
--- a/cmds/bootanimation/bootanimation_main.cpp
+++ b/cmds/bootanimation/bootanimation_main.cpp
@@ -16,9 +16,9 @@
 
 #define LOG_TAG "BootAnimation"
 
-#include <utils/IPCThreadState.h>
-#include <utils/ProcessState.h>
-#include <utils/IServiceManager.h>
+#include <binder/IPCThreadState.h>
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
 #include <utils/Log.h>
 #include <utils/threads.h>
 
diff --git a/cmds/dumpsys/Android.mk b/cmds/dumpsys/Android.mk
index 0c623cc..42b1b73 100644
--- a/cmds/dumpsys/Android.mk
+++ b/cmds/dumpsys/Android.mk
@@ -5,7 +5,9 @@
 	dumpsys.cpp
 
 LOCAL_SHARED_LIBRARIES := \
-	libutils
+	libutils \
+	libbinder
+	
 
 ifeq ($(TARGET_OS),linux)
 	LOCAL_CFLAGS += -DXP_UNIX
diff --git a/cmds/dumpsys/dumpsys.cpp b/cmds/dumpsys/dumpsys.cpp
index a62fe55..945a690 100644
--- a/cmds/dumpsys/dumpsys.cpp
+++ b/cmds/dumpsys/dumpsys.cpp
@@ -6,9 +6,9 @@
 #define LOG_TAG "dumpsys"
 
 #include <utils/Log.h>
-#include <utils/Parcel.h>
-#include <utils/ProcessState.h>
-#include <utils/IServiceManager.h>
+#include <binder/Parcel.h>
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
 #include <utils/TextOutput.h>
 #include <utils/Vector.h>
 
diff --git a/cmds/runtime/Android.mk b/cmds/runtime/Android.mk
index 521eb2b..6a72d10 100644
--- a/cmds/runtime/Android.mk
+++ b/cmds/runtime/Android.mk
@@ -10,6 +10,7 @@
 
 LOCAL_SHARED_LIBRARIES := \
 	libutils \
+	libbinder \
 	libandroid_runtime \
 	libcutils \
 	libui \
diff --git a/cmds/runtime/ServiceManager.cpp b/cmds/runtime/ServiceManager.cpp
index 758a95c..b2bef07 100644
--- a/cmds/runtime/ServiceManager.cpp
+++ b/cmds/runtime/ServiceManager.cpp
@@ -9,9 +9,9 @@
 
 #include <utils/Debug.h>
 #include <utils/Log.h>
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 #include <utils/String8.h>
-#include <utils/ProcessState.h>
+#include <binder/ProcessState.h>
 
 #include <private/utils/Static.h>
 
diff --git a/cmds/runtime/ServiceManager.h b/cmds/runtime/ServiceManager.h
index d09cec8..090ca6d 100644
--- a/cmds/runtime/ServiceManager.h
+++ b/cmds/runtime/ServiceManager.h
@@ -4,7 +4,7 @@
 #ifndef ANDROID_SERVICE_MANAGER_H
 #define ANDROID_SERVICE_MANAGER_H
 
-#include <utils/IServiceManager.h>
+#include <binder/IServiceManager.h>
 #include <utils/KeyedVector.h>
 #include <utils/threads.h>
 
diff --git a/cmds/runtime/main_runtime.cpp b/cmds/runtime/main_runtime.cpp
index 476f38a..21e0e4d 100644
--- a/cmds/runtime/main_runtime.cpp
+++ b/cmds/runtime/main_runtime.cpp
@@ -7,9 +7,11 @@
 #include "ServiceManager.h"
 #include "SignalHandler.h"
 
-#include <utils.h>
-#include <utils/IPCThreadState.h>
-#include <utils/ProcessState.h>
+#include <utils/threads.h>
+#include <utils/Errors.h>
+
+#include <binder/IPCThreadState.h>
+#include <binder/ProcessState.h>
 #include <utils/Log.h>  
 #include <cutils/zygote.h>
 
diff --git a/cmds/service/Android.mk b/cmds/service/Android.mk
index 8c5005c..275bbb2 100644
--- a/cmds/service/Android.mk
+++ b/cmds/service/Android.mk
@@ -4,8 +4,7 @@
 LOCAL_SRC_FILES:= \
 	service.cpp
 
-LOCAL_SHARED_LIBRARIES := \
-	libutils
+LOCAL_SHARED_LIBRARIES := libutils libbinder
 
 ifeq ($(TARGET_OS),linux)
 	LOCAL_CFLAGS += -DXP_UNIX
diff --git a/cmds/service/service.cpp b/cmds/service/service.cpp
index 859a9bf..32db83b 100644
--- a/cmds/service/service.cpp
+++ b/cmds/service/service.cpp
@@ -3,9 +3,9 @@
  *
  */
  
-#include <utils/Parcel.h>
-#include <utils/ProcessState.h>
-#include <utils/IServiceManager.h>
+#include <binder/Parcel.h>
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
 #include <utils/TextOutput.h>
 
 #include <getopt.h>
diff --git a/cmds/servicemanager/service_manager.c b/cmds/servicemanager/service_manager.c
index e4aa8b5..f3a4713 100644
--- a/cmds/servicemanager/service_manager.c
+++ b/cmds/servicemanager/service_manager.c
@@ -30,6 +30,7 @@
     { AID_MEDIA, "media.audio_flinger" },
     { AID_MEDIA, "media.player" },
     { AID_MEDIA, "media.camera" },
+    { AID_MEDIA, "media.audio_policy" },
     { AID_RADIO, "radio.phone" },
     { AID_RADIO, "radio.sms" },
     { AID_RADIO, "radio.phonesubinfo" },
diff --git a/cmds/stagefright/Android.mk b/cmds/stagefright/Android.mk
new file mode 100644
index 0000000..fd681a2
--- /dev/null
+++ b/cmds/stagefright/Android.mk
@@ -0,0 +1,66 @@
+ifeq ($(BUILD_WITH_STAGEFRIGHT),true)
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+	stagefright.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+	libstagefright
+
+LOCAL_C_INCLUDES:= \
+	frameworks/base/media/libstagefright \
+	$(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include \
+        $(TOP)/external/opencore/android
+
+LOCAL_CFLAGS += -Wno-multichar
+
+LOCAL_MODULE:= stagefright
+
+include $(BUILD_EXECUTABLE)
+
+################################################################################
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:=         \
+        record.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+	libstagefright
+
+LOCAL_C_INCLUDES:= \
+	frameworks/base/media/libstagefright \
+	$(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include \
+        $(TOP)/external/opencore/android
+
+LOCAL_CFLAGS += -Wno-multichar
+
+LOCAL_MODULE:= record
+
+include $(BUILD_EXECUTABLE)
+
+################################################################################
+
+# include $(CLEAR_VARS)
+# 
+# LOCAL_SRC_FILES:=         \
+#         play.cpp
+# 
+# LOCAL_SHARED_LIBRARIES := \
+# 	libstagefright
+# 
+# LOCAL_C_INCLUDES:= \
+# 	frameworks/base/media/libstagefright \
+# 	$(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include \
+#         $(TOP)/external/opencore/android
+# 
+# LOCAL_CFLAGS += -Wno-multichar
+# 
+# LOCAL_MODULE:= play
+# 
+# include $(BUILD_EXECUTABLE)
+
+endif
diff --git a/cmds/stagefright/WaveWriter.h b/cmds/stagefright/WaveWriter.h
new file mode 100644
index 0000000..a0eb66e
--- /dev/null
+++ b/cmds/stagefright/WaveWriter.h
@@ -0,0 +1,71 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_WAVEWRITER_H_
+
+#define ANDROID_WAVEWRITER_H_
+
+namespace android {
+
+class WaveWriter {
+public:
+    WaveWriter(const char *filename,
+               uint16_t num_channels, uint32_t sampling_rate)
+        : mFile(fopen(filename, "wb")),
+          mTotalBytes(0) {
+        fwrite("RIFFxxxxWAVEfmt \x10\x00\x00\x00\x01\x00", 1, 22, mFile); 
+        write_u16(num_channels);
+        write_u32(sampling_rate);
+        write_u32(sampling_rate * num_channels * 2);
+        write_u16(num_channels * 2);
+        write_u16(16);
+        fwrite("dataxxxx", 1, 8, mFile);
+    }
+
+    ~WaveWriter() {
+        fseek(mFile, 40, SEEK_SET);
+        write_u32(mTotalBytes);
+
+        fseek(mFile, 4, SEEK_SET);
+        write_u32(36 + mTotalBytes);
+
+        fclose(mFile);
+        mFile = NULL;
+    }
+
+    void Append(const void *data, size_t size) {
+        fwrite(data, 1, size, mFile);
+        mTotalBytes += size;
+    }
+
+private:
+    void write_u16(uint16_t x) {
+        fputc(x & 0xff, mFile);
+        fputc(x >> 8, mFile);
+    }
+
+    void write_u32(uint32_t x) {
+        write_u16(x & 0xffff);
+        write_u16(x >> 16);
+    }
+
+    FILE *mFile;
+    size_t mTotalBytes;
+};
+
+}  // namespace android
+
+#endif  // ANDROID_WAVEWRITER_H_
diff --git a/cmds/stagefright/play.cpp b/cmds/stagefright/play.cpp
new file mode 100644
index 0000000..c6e778e
--- /dev/null
+++ b/cmds/stagefright/play.cpp
@@ -0,0 +1,295 @@
+/*
+ * 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.
+ */
+
+#include <binder/ProcessState.h>
+#include <media/stagefright/OMXClient.h>
+#include <media/stagefright/TimedEventQueue.h>
+#include <media/stagefright/MPEG4Extractor.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/MmapSource.h>
+#include <media/stagefright/OMXDecoder.h>
+
+using namespace android;
+
+struct NewPlayer {
+    NewPlayer();
+    ~NewPlayer();
+
+    void setSource(const char *uri);
+    void start();
+    void pause();
+    void stop();
+
+private:
+    struct PlayerEvent : public TimedEventQueue::Event {
+        PlayerEvent(NewPlayer *player,
+                    void (NewPlayer::*method)(int64_t realtime_us))
+            : mPlayer(player),
+              mMethod(method) {
+        }
+
+        virtual void fire(TimedEventQueue *queue, int64_t realtime_us) {
+            (mPlayer->*mMethod)(realtime_us);
+        }
+
+    private:
+        NewPlayer *mPlayer;
+        void (NewPlayer::*mMethod)(int64_t realtime_us);
+
+        PlayerEvent(const PlayerEvent &);
+        PlayerEvent &operator=(const PlayerEvent &);
+    };
+
+    struct PlayVideoFrameEvent : public TimedEventQueue::Event {
+        PlayVideoFrameEvent(NewPlayer *player, MediaBuffer *buffer)
+            : mPlayer(player),
+              mBuffer(buffer) {
+        }
+
+        virtual ~PlayVideoFrameEvent() {
+            if (mBuffer != NULL) {
+                mBuffer->release();
+                mBuffer = NULL;
+            }
+        }
+
+        virtual void fire(TimedEventQueue *queue, int64_t realtime_us) {
+            mPlayer->onPlayVideoFrame(realtime_us, mBuffer);
+            mBuffer = NULL;
+        }
+
+    private:
+        NewPlayer *mPlayer;
+        MediaBuffer *mBuffer;
+
+        PlayVideoFrameEvent(const PlayVideoFrameEvent &);
+        PlayVideoFrameEvent &operator=(const PlayVideoFrameEvent &);
+    };
+
+    OMXClient mClient;
+
+    MPEG4Extractor *mExtractor;
+    MediaSource *mAudioSource;
+    OMXDecoder *mAudioDecoder;
+    MediaSource *mVideoSource;
+    OMXDecoder *mVideoDecoder;
+
+    int32_t mVideoWidth, mVideoHeight;
+
+    TimedEventQueue mQueue;
+    wp<TimedEventQueue::Event> mPlayVideoFrameEvent;
+
+    int64_t mMediaTimeUsStart;
+    int64_t mRealTimeUsStart;
+
+    void setAudioSource(MediaSource *source);
+    void setVideoSource(MediaSource *source);
+
+    int64_t approxRealTime(int64_t mediatime_us) const;
+
+    void onStart(int64_t realtime_us);
+    void onPause(int64_t realtime_us);
+    void onFetchVideoFrame(int64_t realtime_us);
+    void onPlayVideoFrame(int64_t realtime_us, MediaBuffer *buffer);
+
+    static int64_t getMediaBufferTimeUs(MediaBuffer *buffer);
+
+    NewPlayer(const NewPlayer &);
+    NewPlayer &operator=(const NewPlayer &);
+};
+
+NewPlayer::NewPlayer()
+    : mExtractor(NULL),
+      mAudioSource(NULL),
+      mAudioDecoder(NULL),
+      mVideoSource(NULL),
+      mVideoDecoder(NULL),
+      mVideoWidth(0),
+      mVideoHeight(0) {
+    status_t err = mClient.connect();
+    assert(err == OK);
+}
+
+NewPlayer::~NewPlayer() {
+    stop();
+
+    mClient.disconnect();
+}
+
+void NewPlayer::setSource(const char *uri) {
+    stop();
+
+    mExtractor = new MPEG4Extractor(new MmapSource(uri));
+
+    int num_tracks;
+    status_t err = mExtractor->countTracks(&num_tracks);
+    assert(err == OK);
+
+    for (int i = 0; i < num_tracks; ++i) {
+        const sp<MetaData> meta = mExtractor->getTrackMetaData(i);
+        assert(meta != NULL);
+
+        const char *mime;
+        if (!meta->findCString(kKeyMIMEType, &mime)) {
+            continue;
+        }
+
+        bool is_audio = false;
+        bool is_acceptable = false;
+        if (!strncasecmp(mime, "audio/", 6)) {
+            is_audio = true;
+            is_acceptable = (mAudioSource == NULL);
+        } else if (!strncasecmp(mime, "video/", 6)) {
+            is_acceptable = (mVideoSource == NULL);
+        }
+
+        if (!is_acceptable) {
+            continue;
+        }
+
+        MediaSource *source;
+        if (mExtractor->getTrack(i, &source) != OK) {
+            continue;
+        }
+
+        if (is_audio) {
+            setAudioSource(source);
+        } else {
+            setVideoSource(source);
+        }
+    }
+}
+
+void NewPlayer::setAudioSource(MediaSource *source) {
+    mAudioSource = source;
+
+    sp<MetaData> meta = source->getFormat();
+
+    mAudioDecoder = OMXDecoder::Create(&mClient, meta);
+    mAudioDecoder->setSource(source);
+}
+
+void NewPlayer::setVideoSource(MediaSource *source) {
+    mVideoSource = source;
+
+    sp<MetaData> meta = source->getFormat();
+
+    bool success = meta->findInt32(kKeyWidth, &mVideoWidth);
+    assert(success);
+
+    success = meta->findInt32(kKeyHeight, &mVideoHeight);
+    assert(success);
+
+    mVideoDecoder = OMXDecoder::Create(&mClient, meta);
+    mVideoDecoder->setSource(source);
+}
+
+void NewPlayer::start() {
+    mQueue.start();
+    mQueue.postEvent(new PlayerEvent(this, &NewPlayer::onStart));
+}
+
+void NewPlayer::pause() {
+    mQueue.postEvent(new PlayerEvent(this, &NewPlayer::onPause));
+}
+
+void NewPlayer::stop() {
+    mQueue.stop();
+
+    delete mVideoDecoder;
+    mVideoDecoder = NULL;
+    delete mVideoSource;
+    mVideoSource = NULL;
+    mVideoWidth = mVideoHeight = 0;
+
+    delete mAudioDecoder;
+    mAudioDecoder = NULL;
+    delete mAudioSource;
+    mAudioSource = NULL;
+
+    delete mExtractor;
+    mExtractor = NULL;
+}
+
+int64_t NewPlayer::approxRealTime(int64_t mediatime_us) const {
+    return mRealTimeUsStart + (mediatime_us - mMediaTimeUsStart);
+}
+
+void NewPlayer::onStart(int64_t realtime_us) {
+    mRealTimeUsStart = TimedEventQueue::getRealTimeUs();
+
+    if (mVideoDecoder != NULL) {
+        mQueue.postEvent(new PlayerEvent(this, &NewPlayer::onFetchVideoFrame));
+    }
+}
+
+void NewPlayer::onFetchVideoFrame(int64_t realtime_us) {
+    MediaBuffer *buffer;
+    status_t err = mVideoDecoder->read(&buffer);
+    assert(err == OK);
+
+    int64_t mediatime_us = getMediaBufferTimeUs(buffer);
+
+    sp<TimedEventQueue::Event> event = new PlayVideoFrameEvent(this, buffer);
+    mPlayVideoFrameEvent = event;
+
+    mQueue.postTimedEvent(event, approxRealTime(mediatime_us));
+}
+
+// static
+int64_t NewPlayer::getMediaBufferTimeUs(MediaBuffer *buffer) {
+    int32_t units, scale;
+    bool success =
+        buffer->meta_data()->findInt32(kKeyTimeUnits, &units);
+    assert(success);
+    success =
+        buffer->meta_data()->findInt32(kKeyTimeScale, &scale);
+    assert(success);
+
+    return (int64_t)units * 1000000 / scale;
+}
+
+void NewPlayer::onPlayVideoFrame(int64_t realtime_us, MediaBuffer *buffer) {
+    LOGI("playing video frame (mediatime: %.2f sec)\n",
+         getMediaBufferTimeUs(buffer) / 1E6);
+    fflush(stdout);
+
+    buffer->release();
+    buffer = NULL;
+
+    mQueue.postEvent(new PlayerEvent(this, &NewPlayer::onFetchVideoFrame));
+}
+
+void NewPlayer::onPause(int64_t realtime_us) {
+}
+
+int main(int argc, char **argv) {
+    android::ProcessState::self()->startThreadPool();
+
+    if (argc != 2) {
+        fprintf(stderr, "usage: %s filename\n", argv[0]);
+        return 1;
+    }
+
+    NewPlayer player;
+    player.setSource(argv[1]);
+    player.start();
+    sleep(10);
+    player.stop();
+
+    return 0;
+}
diff --git a/cmds/stagefright/record.cpp b/cmds/stagefright/record.cpp
new file mode 100644
index 0000000..12bdead
--- /dev/null
+++ b/cmds/stagefright/record.cpp
@@ -0,0 +1,181 @@
+/*
+ * 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.
+ */
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <binder/ProcessState.h>
+#include <media/stagefright/CameraSource.h>
+#include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/MPEG4Extractor.h>
+#include <media/stagefright/MPEG4Writer.h>
+#include <media/stagefright/MmapSource.h>
+#include <media/stagefright/OMXClient.h>
+#include <media/stagefright/OMXDecoder.h>
+
+using namespace android;
+
+class DummySource : public MediaSource {
+public:
+    DummySource(int width, int height)
+        : mSize((width * height * 3) / 2) {
+        mGroup.add_buffer(new MediaBuffer(mSize));
+    }
+
+    virtual ::status_t getMaxSampleSize(size_t *max_size) {
+        *max_size = mSize;
+        return ::OK;
+    }
+
+    virtual ::status_t read(MediaBuffer **buffer) {
+        ::status_t err = mGroup.acquire_buffer(buffer);
+        if (err != ::OK) {
+            return err;
+        }
+
+        char x = (char)((double)rand() / RAND_MAX * 255);
+        memset((*buffer)->data(), x, mSize);
+        (*buffer)->set_range(0, mSize);
+
+        return ::OK;
+    }
+
+private:
+    MediaBufferGroup mGroup;
+    size_t mSize;
+
+    DummySource(const DummySource &);
+    DummySource &operator=(const DummySource &);
+};
+
+int main(int argc, char **argv) {
+    android::ProcessState::self()->startThreadPool();
+
+#if 1
+    if (argc != 2) {
+        fprintf(stderr, "usage: %s filename\n", argv[0]);
+        return 1;
+    }
+
+    MPEG4Extractor extractor(new MmapSource(argv[1]));
+    int num_tracks;
+    assert(extractor.countTracks(&num_tracks) == ::OK);
+
+    MediaSource *source = NULL;
+    sp<MetaData> meta;
+    for (int i = 0; i < num_tracks; ++i) {
+        meta = extractor.getTrackMetaData(i);
+        assert(meta.get() != NULL);
+
+        const char *mime;
+        if (!meta->findCString(kKeyMIMEType, &mime)) {
+            continue;
+        }
+
+        if (strncasecmp(mime, "video/", 6)) {
+            continue;
+        }
+
+        if (extractor.getTrack(i, &source) != ::OK) {
+            source = NULL;
+            continue;
+        }
+        break;
+    }
+
+    if (source == NULL) {
+        fprintf(stderr, "Unable to find a suitable video track.\n");
+        return 1;
+    }
+
+    OMXClient client;
+    assert(client.connect() == android::OK);
+
+    OMXDecoder *decoder = OMXDecoder::Create(&client, meta);
+    decoder->setSource(source);
+
+    int width, height;
+    bool success = meta->findInt32(kKeyWidth, &width);
+    success = success && meta->findInt32(kKeyHeight, &height);
+    assert(success);
+
+    sp<MetaData> enc_meta = new MetaData;
+    // enc_meta->setCString(kKeyMIMEType, "video/3gpp");
+    enc_meta->setCString(kKeyMIMEType, "video/mp4v-es");
+    enc_meta->setInt32(kKeyWidth, width);
+    enc_meta->setInt32(kKeyHeight, height);
+
+    OMXDecoder *encoder = OMXDecoder::CreateEncoder(&client, enc_meta);
+
+    encoder->setSource(decoder);
+    // encoder->setSource(meta, new DummySource(width, height));
+
+#if 1
+    MPEG4Writer writer("/sdcard/output.mp4");
+    writer.addSource(enc_meta, encoder);
+    writer.start();
+    sleep(120);
+    writer.stop();
+#else
+    encoder->start();
+
+    MediaBuffer *buffer;
+    while (encoder->read(&buffer) == ::OK) {
+        printf("got an output frame of size %d\n", buffer->range_length());
+
+        buffer->release();
+        buffer = NULL;
+    }
+
+    encoder->stop();
+#endif
+
+    delete encoder;
+    encoder = NULL;
+
+    delete decoder;
+    decoder = NULL;
+
+    client.disconnect();
+
+    delete source;
+    source = NULL;
+#endif
+
+#if 0
+    CameraSource *source = CameraSource::Create();
+    printf("source = %p\n", source);
+
+    for (int i = 0; i < 100; ++i) {
+        MediaBuffer *buffer;
+        status_t err = source->read(&buffer);
+        assert(err == OK);
+
+        printf("got a frame, data=%p, size=%d\n",
+               buffer->data(), buffer->range_length());
+
+        buffer->release();
+        buffer = NULL;
+    }
+
+    delete source;
+    source = NULL;
+#endif
+
+    return 0;
+}
+
diff --git a/cmds/stagefright/stagefright.cpp b/cmds/stagefright/stagefright.cpp
new file mode 100644
index 0000000..961942a
--- /dev/null
+++ b/cmds/stagefright/stagefright.cpp
@@ -0,0 +1,200 @@
+/*
+ * 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.
+ */
+
+#include <sys/time.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <pthread.h>
+#include <stdlib.h>
+
+#include <binder/IServiceManager.h>
+#include <binder/ProcessState.h>
+#include <media/IMediaPlayerService.h>
+#include <media/stagefright/AudioPlayer.h>
+#include <media/stagefright/CachingDataSource.h>
+#include <media/stagefright/ESDS.h>
+#include <media/stagefright/FileSource.h>
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaPlayerImpl.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/MmapSource.h>
+#include <media/stagefright/OMXClient.h>
+#include <media/stagefright/OMXDecoder.h>
+
+#include "WaveWriter.h"
+
+using namespace android;
+
+////////////////////////////////////////////////////////////////////////////////
+
+static bool convertToWav(
+        OMXClient *client, const sp<MetaData> &meta, MediaSource *source) {
+    printf("convertToWav\n");
+
+    OMXDecoder *decoder = OMXDecoder::Create(client, meta);
+
+    int32_t sampleRate;
+    bool success = meta->findInt32(kKeySampleRate, &sampleRate);
+    assert(success);
+
+    int32_t numChannels;
+    success = meta->findInt32(kKeyChannelCount, &numChannels);
+    assert(success);
+
+    const char *mime;
+    success = meta->findCString(kKeyMIMEType, &mime);
+    assert(success);
+
+    if (!strcasecmp("audio/3gpp", mime)) {
+        numChannels = 1;  // XXX
+    }
+
+    WaveWriter writer("/sdcard/Music/shoutcast.wav", numChannels, sampleRate);
+
+    decoder->setSource(source);
+    for (int i = 0; i < 100; ++i) {
+        MediaBuffer *buffer;
+
+        ::status_t err = decoder->read(&buffer);
+        if (err != ::OK) {
+            break;
+        }
+
+        writer.Append((const char *)buffer->data() + buffer->range_offset(),
+                      buffer->range_length());
+
+        buffer->release();
+        buffer = NULL;
+    }
+
+    delete decoder;
+    decoder = NULL;
+
+    return true;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+static int64_t getNowUs() {
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+
+    return (int64_t)tv.tv_usec + tv.tv_sec * 1000000;
+}
+
+int main(int argc, char **argv) {
+    android::ProcessState::self()->startThreadPool();
+
+    if (argc > 1 && !strcmp(argv[1], "--list")) {
+        sp<IServiceManager> sm = defaultServiceManager();
+        sp<IBinder> binder = sm->getService(String16("media.player"));
+        sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
+
+        assert(service.get() != NULL);
+
+        sp<IOMX> omx = service->createOMX();
+        assert(omx.get() != NULL);
+
+        List<String8> list;
+        omx->list_nodes(&list);
+
+        for (List<String8>::iterator it = list.begin();
+             it != list.end(); ++it) {
+            printf("%s\n", (*it).string());
+        }
+
+        return 0;
+    }
+
+#if 0
+    MediaPlayerImpl player(argv[1]);
+    player.play();
+
+    sleep(10000);
+#else
+    DataSource::RegisterDefaultSniffers();
+
+    OMXClient client;
+    status_t err = client.connect();
+
+    MmapSource *dataSource = new MmapSource(argv[1]);
+    MediaExtractor *extractor = MediaExtractor::Create(dataSource);
+    dataSource = NULL;
+
+    int numTracks;
+    err = extractor->countTracks(&numTracks);
+
+    sp<MetaData> meta;
+    int i;
+    for (i = 0; i < numTracks; ++i) {
+        meta = extractor->getTrackMetaData(i);
+
+        const char *mime;
+        meta->findCString(kKeyMIMEType, &mime);
+
+        if (!strncasecmp(mime, "video/", 6)) {
+            break;
+        }
+    }
+
+    OMXDecoder *decoder = OMXDecoder::Create(&client, meta);
+
+    if (decoder != NULL) {
+        MediaSource *source;
+        err = extractor->getTrack(i, &source);
+
+        decoder->setSource(source);
+
+        decoder->start();
+
+        int64_t startTime = getNowUs();
+
+        int n = 0;
+        MediaBuffer *buffer;
+        while ((err = decoder->read(&buffer)) == OK) {
+            if ((++n % 16) == 0) {
+                printf(".");
+                fflush(stdout);
+            }
+
+            buffer->release();
+            buffer = NULL;
+        }
+        decoder->stop();
+        printf("\n");
+
+        int64_t delay = getNowUs() - startTime;
+        printf("avg. %.2f fps\n", n * 1E6 / delay);
+
+        delete decoder;
+        decoder = NULL;
+
+        delete source;
+        source = NULL;
+    }
+
+    delete extractor;
+    extractor = NULL;
+
+    client.disconnect();
+#endif
+
+    return 0;
+}
diff --git a/cmds/surfaceflinger/Android.mk b/cmds/surfaceflinger/Android.mk
index 37c3d94..bfa58a1 100644
--- a/cmds/surfaceflinger/Android.mk
+++ b/cmds/surfaceflinger/Android.mk
@@ -6,6 +6,7 @@
 
 LOCAL_SHARED_LIBRARIES := \
 	libsurfaceflinger \
+	libbinder \
 	libutils
 
 LOCAL_C_INCLUDES := \
diff --git a/cmds/surfaceflinger/main_surfaceflinger.cpp b/cmds/surfaceflinger/main_surfaceflinger.cpp
index 7c89578..d650721 100644
--- a/cmds/surfaceflinger/main_surfaceflinger.cpp
+++ b/cmds/surfaceflinger/main_surfaceflinger.cpp
@@ -1,6 +1,6 @@
-#include <utils/IPCThreadState.h>
-#include <utils/ProcessState.h>
-#include <utils/IServiceManager.h>
+#include <binder/IPCThreadState.h>
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
 #include <utils/Log.h>
 
 #include <SurfaceFlinger.h>
diff --git a/cmds/system_server/Android.mk b/cmds/system_server/Android.mk
index 0a684e8..ad537977 100644
--- a/cmds/system_server/Android.mk
+++ b/cmds/system_server/Android.mk
@@ -6,6 +6,7 @@
 
 LOCAL_SHARED_LIBRARIES := \
 	libutils \
+	libbinder \
 	libsystem_server 
 
 LOCAL_C_INCLUDES := \
diff --git a/cmds/system_server/library/Android.mk b/cmds/system_server/library/Android.mk
index 580331a..1813d3e 100644
--- a/cmds/system_server/library/Android.mk
+++ b/cmds/system_server/library/Android.mk
@@ -20,6 +20,7 @@
     libcameraservice \
     libmediaplayerservice \
 	libutils \
+	libbinder \
 	libcutils
 
 LOCAL_MODULE:= libsystem_server
diff --git a/cmds/system_server/library/system_init.cpp b/cmds/system_server/library/system_init.cpp
index 73b23e2..1d57fdc 100644
--- a/cmds/system_server/library/system_init.cpp
+++ b/cmds/system_server/library/system_init.cpp
@@ -8,15 +8,16 @@
 
 #define LOG_TAG "sysproc"
 
-#include <utils/IPCThreadState.h>
-#include <utils/ProcessState.h>
-#include <utils/IServiceManager.h>
+#include <binder/IPCThreadState.h>
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
 #include <utils/TextOutput.h>
 #include <utils/Log.h>
 
 #include <SurfaceFlinger.h>
 #include <AudioFlinger.h>
 #include <CameraService.h>
+#include <AudioPolicyService.h>
 #include <MediaPlayerService.h>
 
 #include <android_runtime/AndroidRuntime.h>
@@ -80,6 +81,9 @@
 
         // Start the camera service
         CameraService::instantiate();
+
+        // Start the audio policy service
+        AudioPolicyService::instantiate();
     }
 
     // And now start the Android runtime.  We have to do this bit
diff --git a/cmds/system_server/system_main.cpp b/cmds/system_server/system_main.cpp
index ca16e57..543f650 100644
--- a/cmds/system_server/system_main.cpp
+++ b/cmds/system_server/system_main.cpp
@@ -9,7 +9,7 @@
 
 #define LOG_TAG "sysproc"
 
-#include <utils/IPCThreadState.h>
+#include <binder/IPCThreadState.h>
 #include <utils/Log.h>
 
 #include <private/android_filesystem_config.h>
diff --git a/core/java/android/accounts/AbstractAccountAuthenticator.java b/core/java/android/accounts/AbstractAccountAuthenticator.java
new file mode 100644
index 0000000..3ce3ca3
--- /dev/null
+++ b/core/java/android/accounts/AbstractAccountAuthenticator.java
@@ -0,0 +1,241 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.os.Bundle;
+import android.os.RemoteException;
+import android.os.Binder;
+import android.util.Log;
+import android.content.pm.PackageManager;
+import android.content.Context;
+import android.Manifest;
+
+/**
+ * Base class for creating AccountAuthenticators. This implements the IAccountAuthenticator
+ * binder interface and also provides helper libraries to simplify the creation of
+ * AccountAuthenticators.
+ */
+public abstract class AbstractAccountAuthenticator {
+    private final Context mContext;
+
+    public AbstractAccountAuthenticator(Context context) {
+        mContext = context;
+    }
+
+    class Transport extends IAccountAuthenticator.Stub {
+        public void addAccount(IAccountAuthenticatorResponse response, String accountType,
+                String authTokenType, String[] requiredFeatures, Bundle options)
+                throws RemoteException {
+            checkBinderPermission();
+            final Bundle result;
+            try {
+                result = AbstractAccountAuthenticator.this.addAccount(
+                    new AccountAuthenticatorResponse(response),
+                        accountType, authTokenType, requiredFeatures, options);
+            } catch (NetworkErrorException e) {
+                response.onError(Constants.ERROR_CODE_NETWORK_ERROR, e.getMessage());
+                return;
+            } catch (UnsupportedOperationException e) {
+                response.onError(Constants.ERROR_CODE_UNSUPPORTED_OPERATION,
+                        "addAccount not supported");
+                return;
+            }
+            if (result != null) {
+                response.onResult(result);
+            }
+        }
+
+        public void confirmPassword(IAccountAuthenticatorResponse response,
+                Account account, String password) throws RemoteException {
+            checkBinderPermission();
+            boolean result;
+            try {
+                result = AbstractAccountAuthenticator.this.confirmPassword(
+                    new AccountAuthenticatorResponse(response),
+                        account, password);
+            } catch (UnsupportedOperationException e) {
+                response.onError(Constants.ERROR_CODE_UNSUPPORTED_OPERATION,
+                        "confirmPassword not supported");
+                return;
+            } catch (NetworkErrorException e) {
+                response.onError(Constants.ERROR_CODE_NETWORK_ERROR, e.getMessage());
+                return;
+            }
+            Bundle bundle = new Bundle();
+            bundle.putBoolean(Constants.BOOLEAN_RESULT_KEY, result);
+            response.onResult(bundle);
+        }
+
+        public void confirmCredentials(IAccountAuthenticatorResponse response,
+                Account account) throws RemoteException {
+            checkBinderPermission();
+            final Bundle result;
+            try {
+                result = AbstractAccountAuthenticator.this.confirmCredentials(
+                    new AccountAuthenticatorResponse(response), account);
+            } catch (UnsupportedOperationException e) {
+                response.onError(Constants.ERROR_CODE_UNSUPPORTED_OPERATION,
+                        "confirmCredentials not supported");
+                return;
+            }
+            if (result != null) {
+                response.onResult(result);
+            }
+        }
+
+        public void getAuthTokenLabel(IAccountAuthenticatorResponse response,
+                String authTokenType)
+                throws RemoteException {
+            checkBinderPermission();
+            try {
+                Bundle result = new Bundle();
+                result.putString(Constants.AUTH_TOKEN_LABEL_KEY,
+                        AbstractAccountAuthenticator.this.getAuthTokenLabel(authTokenType));
+                response.onResult(result);
+            } catch (IllegalArgumentException e) {
+                response.onError(Constants.ERROR_CODE_BAD_ARGUMENTS,
+                        "unknown authTokenType");
+            } catch (UnsupportedOperationException e) {
+                response.onError(Constants.ERROR_CODE_UNSUPPORTED_OPERATION,
+                        "getAuthTokenTypeLabel not supported");
+            }
+        }
+
+        public void getAuthToken(IAccountAuthenticatorResponse response,
+                Account account, String authTokenType, Bundle loginOptions)
+                throws RemoteException {
+            checkBinderPermission();
+            try {
+                final Bundle result = AbstractAccountAuthenticator.this.getAuthToken(
+                        new AccountAuthenticatorResponse(response), account,
+                        authTokenType, loginOptions);
+                if (result != null) {
+                    response.onResult(result);
+                }
+            } catch (UnsupportedOperationException e) {
+                response.onError(Constants.ERROR_CODE_UNSUPPORTED_OPERATION,
+                        "getAuthToken not supported");
+            } catch (NetworkErrorException e) {
+                response.onError(Constants.ERROR_CODE_NETWORK_ERROR, e.getMessage());
+            }
+        }
+
+        public void updateCredentials(IAccountAuthenticatorResponse response, Account account,
+                String authTokenType, Bundle loginOptions) throws RemoteException {
+            checkBinderPermission();
+            final Bundle result;
+            try {
+                result = AbstractAccountAuthenticator.this.updateCredentials(
+                    new AccountAuthenticatorResponse(response), account,
+                        authTokenType, loginOptions);
+            } catch (UnsupportedOperationException e) {
+                response.onError(Constants.ERROR_CODE_UNSUPPORTED_OPERATION,
+                        "updateCredentials not supported");
+                return;
+            }
+            if (result != null) {
+                response.onResult(result);
+            }
+        }
+
+        public void editProperties(IAccountAuthenticatorResponse response,
+                String accountType) throws RemoteException {
+            checkBinderPermission();
+            final Bundle result;
+            try {
+                result = AbstractAccountAuthenticator.this.editProperties(
+                    new AccountAuthenticatorResponse(response), accountType);
+            } catch (UnsupportedOperationException e) {
+                response.onError(Constants.ERROR_CODE_UNSUPPORTED_OPERATION,
+                        "editProperties not supported");
+                return;
+            }
+            if (result != null) {
+                response.onResult(result);
+            }
+        }
+
+        public void hasFeatures(IAccountAuthenticatorResponse response,
+                Account account, String[] features) throws RemoteException {
+            checkBinderPermission();
+            final Bundle result;
+            try {
+                result = AbstractAccountAuthenticator.this.hasFeatures(
+                    new AccountAuthenticatorResponse(response), account, features);
+            } catch (UnsupportedOperationException e) {
+                response.onError(Constants.ERROR_CODE_UNSUPPORTED_OPERATION,
+                        "hasFeatures not supported");
+                return;
+            } catch (NetworkErrorException e) {
+                response.onError(Constants.ERROR_CODE_NETWORK_ERROR, e.getMessage());
+                return;
+            }
+            if (result != null) {
+                response.onResult(result);
+            }
+        }
+    }
+
+    private void checkBinderPermission() {
+        final int uid = Binder.getCallingUid();
+        final String perm = Manifest.permission.ACCOUNT_MANAGER_SERVICE;
+        if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
+            throw new SecurityException("caller uid " + uid + " lacks " + perm);
+        }
+    }
+
+    Transport mTransport = new Transport();
+
+    /**
+     * @return the IAccountAuthenticator binder transport object
+     */
+    public final IAccountAuthenticator getIAccountAuthenticator()
+    {
+        return mTransport;
+    }
+
+    /**
+     * Returns a Bundle that contains the Intent of the activity that can be used to edit the
+     * properties. In order to indicate success the activity should call response.setResult()
+     * with a non-null Bundle.
+     * @param response used to set the result for the request. If the Constants.INTENT_KEY
+     *   is set in the bundle then this response field is to be used for sending future
+     *   results if and when the Intent is started.
+     * @param accountType the AccountType whose properties are to be edited.
+     * @return a Bundle containing the result or the Intent to start to continue the request.
+     *   If this is null then the request is considered to still be active and the result should
+     *   sent later using response.
+     */
+    public abstract Bundle editProperties(AccountAuthenticatorResponse response,
+            String accountType);
+    public abstract Bundle addAccount(AccountAuthenticatorResponse response, String accountType,
+            String authTokenType, String[] requiredFeatures, Bundle options)
+            throws NetworkErrorException;
+    /* @deprecated */
+    public abstract boolean confirmPassword(AccountAuthenticatorResponse response,
+            Account account, String password) throws NetworkErrorException;
+    public abstract Bundle confirmCredentials(AccountAuthenticatorResponse response,
+            Account account);
+    public abstract Bundle getAuthToken(AccountAuthenticatorResponse response,
+            Account account, String authTokenType, Bundle loginOptions)
+            throws NetworkErrorException;
+    public abstract String getAuthTokenLabel(String authTokenType);
+    public abstract Bundle updateCredentials(AccountAuthenticatorResponse response,
+            Account account, String authTokenType, Bundle loginOptions);
+    public abstract Bundle hasFeatures(AccountAuthenticatorResponse response,
+            Account account, String[] features) throws NetworkErrorException;
+}
diff --git a/include/utils/executablepath.h b/core/java/android/accounts/Account.aidl
similarity index 65%
copy from include/utils/executablepath.h
copy to core/java/android/accounts/Account.aidl
index c979432..8752d99 100644
--- a/include/utils/executablepath.h
+++ b/core/java/android/accounts/Account.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,15 +14,6 @@
  * limitations under the License.
  */
 
-#ifndef _UTILS_EXECUTABLEPATH_H
-#define _UTILS_EXECUTABLEPATH_H
+package android.accounts;
 
-#include <limits.h>
-
-// returns the path to this executable
-#if __cplusplus
-extern "C"
-#endif
-void executablepath(char s[PATH_MAX]);
-
-#endif // _UTILS_EXECUTABLEPATH_H
+parcelable Account;
diff --git a/core/java/android/accounts/Account.java b/core/java/android/accounts/Account.java
new file mode 100644
index 0000000..30c91b0
--- /dev/null
+++ b/core/java/android/accounts/Account.java
@@ -0,0 +1,84 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.os.Parcelable;
+import android.os.Parcel;
+import android.text.TextUtils;
+
+/**
+ * Value type that represents an Account in the {@link AccountManager}. This object is
+ * {@link Parcelable} and also overrides {@link #equals} and {@link #hashCode}, making it
+ * suitable for use as the key of a {@link java.util.Map}
+ */
+public class Account implements Parcelable {
+    public final String mName;
+    public final String mType;
+
+    public boolean equals(Object o) {
+        if (o == this) return true;
+        if (!(o instanceof Account)) return false;
+        final Account other = (Account)o;
+        return mName.equals(other.mName) && mType.equals(other.mType);
+    }
+
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + mName.hashCode();
+        result = 31 * result + mType.hashCode();
+        return result;
+    }
+
+    public Account(String name, String type) {
+        if (TextUtils.isEmpty(name)) {
+            throw new IllegalArgumentException("the name must not be empty: " + name);
+        }
+        if (TextUtils.isEmpty(type)) {
+            throw new IllegalArgumentException("the type must not be empty: " + type);
+        }
+        mName = name;
+        mType = type;
+    }
+
+    public Account(Parcel in) {
+        mName = in.readString();
+        mType = in.readString();
+    }
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeString(mName);
+        dest.writeString(mType);
+    }
+
+    public static final Creator<Account> CREATOR = new Creator<Account>() {
+        public Account createFromParcel(Parcel source) {
+            return new Account(source);
+        }
+
+        public Account[] newArray(int size) {
+            return new Account[size];
+        }
+    };
+
+    public String toString() {
+        return "Account {name=" + mName + ", type=" + mType + "}";
+    }
+}
diff --git a/core/java/android/accounts/AccountAuthenticatorActivity.java b/core/java/android/accounts/AccountAuthenticatorActivity.java
new file mode 100644
index 0000000..0319ab9
--- /dev/null
+++ b/core/java/android/accounts/AccountAuthenticatorActivity.java
@@ -0,0 +1,102 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+
+/**
+ * Base class for implementing an Activity that is used to help implement an
+ * AbstractAccountAuthenticator. If the AbstractAccountAuthenticator needs to return an Intent
+ * that is to be used to launch an Activity that needs to return results to satisfy an
+ * AbstractAccountAuthenticator request, it should store the AccountAuthenticatorResponse
+ * inside of the Intent as follows:
+ * <p>
+ *      intent.putExtra(Constants.ACCOUNT_AUTHENTICATOR_RESPONSE_KEY, response);
+ * <p>
+ * The activity that it launches should extend the AccountAuthenticatorActivity. If this
+ * activity has a result that satisfies the original request it sets it via:
+ * <p>
+ *       setAccountAuthenticatorResult(result)
+ * <p>
+ * This result will be sent as the result of the request when the activity finishes. If this
+ * is never set or if it is set to null then the request will be canceled when the activity
+ * finishes.
+ */
+public class AccountAuthenticatorActivity extends Activity {
+    private AccountAuthenticatorResponse mAccountAuthenticatorResponse = null;
+    private Bundle mResultBundle = null;
+
+    /**
+     * Set the result that is to be sent as the result of the request that caused this
+     * Activity to be launched. If result is null or this method is never called then
+     * the request will be canceled.
+     * @param result this is returned as the result of the AbstractAccountAuthenticator request
+     */
+    public final void setAccountAuthenticatorResult(Bundle result) {
+        mResultBundle = result;
+    }
+
+    /**
+     * Retreives the AccountAuthenticatorResponse from either the intent of the icicle, if the
+     * icicle is non-zero.
+     * @param icicle the save instance data of this Activity, may be null
+     */
+    protected void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        if (icicle == null) {
+            Intent intent = getIntent();
+            mAccountAuthenticatorResponse =
+                    intent.getParcelableExtra(Constants.ACCOUNT_AUTHENTICATOR_RESPONSE_KEY);
+        } else {
+            mAccountAuthenticatorResponse =
+                    icicle.getParcelable(Constants.ACCOUNT_AUTHENTICATOR_RESPONSE_KEY);
+        }
+
+        if (mAccountAuthenticatorResponse != null) {
+            mAccountAuthenticatorResponse.onRequestContinued();
+        }
+    }
+
+    /**
+     * Saves the AccountAuthenticatorResponse in the instance state.
+     * @param outState where to store any instance data
+     */
+    protected void onSaveInstanceState(Bundle outState) {
+        outState.putParcelable(Constants.ACCOUNT_AUTHENTICATOR_RESPONSE_KEY,
+                mAccountAuthenticatorResponse);
+        super.onSaveInstanceState(outState);
+    }
+
+    /**
+     * Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present.
+     */
+    public void finish() {
+        if (mAccountAuthenticatorResponse != null) {
+            // send the result bundle back if set, otherwise send an error.
+            if (mResultBundle != null) {
+                mAccountAuthenticatorResponse.onResult(mResultBundle);
+            } else {
+                mAccountAuthenticatorResponse.onError(Constants.ERROR_CODE_CANCELED, "canceled");
+            }
+            mAccountAuthenticatorResponse = null;
+        }
+        super.finish();
+    }
+}
diff --git a/core/java/android/accounts/AccountAuthenticatorCache.java b/core/java/android/accounts/AccountAuthenticatorCache.java
new file mode 100644
index 0000000..2f52f40
--- /dev/null
+++ b/core/java/android/accounts/AccountAuthenticatorCache.java
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.content.pm.PackageManager;
+import android.content.pm.RegisteredServicesCache;
+import android.content.res.TypedArray;
+import android.content.Context;
+import android.util.AttributeSet;
+
+/**
+ * A cache of services that export the {@link IAccountAuthenticator} interface. This cache
+ * is built by interrogating the {@link PackageManager} and is updated as packages are added,
+ * removed and changed. The authenticators are referred to by their account type and
+ * are made available via the {@link RegisteredServicesCache#getServiceInfo} method.
+ * @hide
+ */
+/* package private */ class AccountAuthenticatorCache
+        extends RegisteredServicesCache<AuthenticatorDescription> {
+    private static final String TAG = "Account";
+
+    public AccountAuthenticatorCache(Context context) {
+        super(context, Constants.AUTHENTICATOR_INTENT_ACTION,
+                Constants.AUTHENTICATOR_META_DATA_NAME, Constants.AUTHENTICATOR_ATTRIBUTES_NAME);
+    }
+
+    public AuthenticatorDescription parseServiceAttributes(String packageName, AttributeSet attrs) {
+        TypedArray sa = mContext.getResources().obtainAttributes(attrs,
+                com.android.internal.R.styleable.AccountAuthenticator);
+        try {
+            final String accountType =
+                    sa.getString(com.android.internal.R.styleable.AccountAuthenticator_accountType);
+            final int labelId = sa.getResourceId(
+                    com.android.internal.R.styleable.AccountAuthenticator_label, 0);
+            final int iconId = sa.getResourceId(
+                    com.android.internal.R.styleable.AccountAuthenticator_icon, 0);
+            return new AuthenticatorDescription(accountType, packageName, labelId, iconId);
+        } finally {
+            sa.recycle();
+        }
+    }
+}
diff --git a/core/java/android/accounts/AccountAuthenticatorResponse.java b/core/java/android/accounts/AccountAuthenticatorResponse.java
new file mode 100644
index 0000000..7198046
--- /dev/null
+++ b/core/java/android/accounts/AccountAuthenticatorResponse.java
@@ -0,0 +1,82 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.os.Parcel;
+import android.os.RemoteException;
+
+/**
+ * Object that wraps calls to an {@link IAccountAuthenticatorResponse} object.
+ * TODO: this interface is still in flux
+ */
+public class AccountAuthenticatorResponse implements Parcelable {
+    private IAccountAuthenticatorResponse mAccountAuthenticatorResponse;
+
+    public AccountAuthenticatorResponse(IAccountAuthenticatorResponse response) {
+        mAccountAuthenticatorResponse = response;
+    }
+
+    public AccountAuthenticatorResponse(Parcel parcel) {
+        mAccountAuthenticatorResponse =
+                IAccountAuthenticatorResponse.Stub.asInterface(parcel.readStrongBinder());
+    }
+
+    public void onResult(Bundle result) {
+        try {
+            mAccountAuthenticatorResponse.onResult(result);
+        } catch (RemoteException e) {
+            // this should never happen
+        }
+    }
+
+    public void onRequestContinued() {
+        try {
+            mAccountAuthenticatorResponse.onRequestContinued();
+        } catch (RemoteException e) {
+            // this should never happen
+        }
+    }
+
+    public void onError(int errorCode, String errorMessage) {
+        try {
+            mAccountAuthenticatorResponse.onError(errorCode, errorMessage);
+        } catch (RemoteException e) {
+            // this should never happen
+        }
+    }
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeStrongBinder(mAccountAuthenticatorResponse.asBinder());
+    }
+
+    public static final Creator<AccountAuthenticatorResponse> CREATOR =
+            new Creator<AccountAuthenticatorResponse>() {
+        public AccountAuthenticatorResponse createFromParcel(Parcel source) {
+            return new AccountAuthenticatorResponse(source);
+        }
+
+        public AccountAuthenticatorResponse[] newArray(int size) {
+            return new AccountAuthenticatorResponse[size];
+        }
+    };
+}
diff --git a/core/java/android/accounts/AccountManager.java b/core/java/android/accounts/AccountManager.java
new file mode 100644
index 0000000..502abbb
--- /dev/null
+++ b/core/java/android/accounts/AccountManager.java
@@ -0,0 +1,1080 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.content.Context;
+import android.content.IntentFilter;
+import android.content.BroadcastReceiver;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.RemoteException;
+import android.os.Parcelable;
+import android.util.Config;
+import android.util.Log;
+
+import java.io.IOException;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.TimeUnit;
+import java.util.HashMap;
+import java.util.Map;
+
+import com.google.android.collect.Maps;
+
+/**
+ * A class that helps with interactions with the AccountManagerService. It provides
+ * methods to allow for account, password, and authtoken management for all accounts on the
+ * device. Some of these calls are implemented with the help of the corresponding
+ * {@link IAccountAuthenticator} services. One accesses the {@link AccountManager} by calling:
+ *    AccountManager accountManager = AccountManager.get(context);
+ *
+ * <p>
+ * TODO(fredq) this interface is still in flux
+ */
+public class AccountManager {
+    private static final String TAG = "AccountManager";
+
+    private final Context mContext;
+    private final IAccountManager mService;
+    private final Handler mMainHandler;
+
+    /**
+     * @hide
+     */
+    public AccountManager(Context context, IAccountManager service) {
+        mContext = context;
+        mService = service;
+        mMainHandler = new Handler(mContext.getMainLooper());
+    }
+
+    /**
+     * @hide used for testing only
+     */
+    public AccountManager(Context context, IAccountManager service, Handler handler) {
+        mContext = context;
+        mService = service;
+        mMainHandler = handler;
+    }
+
+    public static AccountManager get(Context context) {
+        return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
+    }
+
+    public String blockingGetPassword(Account account) {
+        ensureNotOnMainThread();
+        try {
+            return mService.getPassword(account);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+            throw new RuntimeException(e);
+        }
+    }
+
+    public Future1<String> getPassword(final Future1Callback<String> callback,
+            final Account account, final Handler handler) {
+        return startAsFuture(callback, handler, new Callable<String>() {
+            public String call() throws Exception {
+                return blockingGetPassword(account);
+            }
+        });
+    }
+
+    public String blockingGetUserData(Account account, String key) {
+        ensureNotOnMainThread();
+        try {
+            return mService.getUserData(account, key);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+            throw new RuntimeException(e);
+        }
+    }
+
+    public Future1<String> getUserData(Future1Callback<String> callback,
+            final Account account, final String key, Handler handler) {
+        return startAsFuture(callback, handler, new Callable<String>() {
+            public String call() throws Exception {
+                return blockingGetUserData(account, key);
+            }
+        });
+    }
+
+    public AuthenticatorDescription[] blockingGetAuthenticatorTypes() {
+        ensureNotOnMainThread();
+        try {
+            return mService.getAuthenticatorTypes();
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+            throw new RuntimeException(e);
+        }
+    }
+
+    public Future1<AuthenticatorDescription[]> getAuthenticatorTypes(
+            Future1Callback<AuthenticatorDescription[]> callback, Handler handler) {
+        return startAsFuture(callback, handler, new Callable<AuthenticatorDescription[]>() {
+            public AuthenticatorDescription[] call() throws Exception {
+                return blockingGetAuthenticatorTypes();
+            }
+        });
+    }
+
+    public Account[] blockingGetAccounts() {
+        ensureNotOnMainThread();
+        try {
+            return mService.getAccounts();
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+            throw new RuntimeException(e);
+        }
+    }
+
+    public Account[] blockingGetAccountsByType(String accountType) {
+        ensureNotOnMainThread();
+        try {
+            return mService.getAccountsByType(accountType);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+            throw new RuntimeException(e);
+        }
+    }
+
+    public Future1<Account[]> getAccounts(Future1Callback<Account[]> callback, Handler handler) {
+        return startAsFuture(callback, handler, new Callable<Account[]>() {
+            public Account[] call() throws Exception {
+                return blockingGetAccounts();
+            }
+        });
+    }
+
+    public Future1<Account[]> getAccountsByType(Future1Callback<Account[]> callback,
+            final String type, Handler handler) {
+        return startAsFuture(callback, handler, new Callable<Account[]>() {
+            public Account[] call() throws Exception {
+                return blockingGetAccountsByType(type);
+            }
+        });
+    }
+
+    public boolean blockingAddAccountExplicitly(Account account, String password, Bundle extras) {
+        ensureNotOnMainThread();
+        try {
+            return mService.addAccount(account, password, extras);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+            throw new RuntimeException(e);
+        }
+    }
+
+    public Future1<Boolean> addAccountExplicitly(final Future1Callback<Boolean> callback,
+            final Account account, final String password, final Bundle extras,
+            final Handler handler) {
+        return startAsFuture(callback, handler, new Callable<Boolean>() {
+            public Boolean call() throws Exception {
+                return blockingAddAccountExplicitly(account, password, extras);
+            }
+        });
+    }
+
+    public void blockingRemoveAccount(Account account) {
+        ensureNotOnMainThread();
+        try {
+            mService.removeAccount(account);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+        }
+    }
+
+    public Future1<Void> removeAccount(Future1Callback<Void> callback, final Account account,
+            final Handler handler) {
+        return startAsFuture(callback, handler, new Callable<Void>() {
+            public Void call() throws Exception {
+                blockingRemoveAccount(account);
+                return null;
+            }
+        });
+    }
+
+    public void blockingInvalidateAuthToken(String accountType, String authToken) {
+        ensureNotOnMainThread();
+        try {
+            mService.invalidateAuthToken(accountType, authToken);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+        }
+    }
+
+    public Future1<Void> invalidateAuthToken(Future1Callback<Void> callback,
+            final String accountType, final String authToken, final Handler handler) {
+        return startAsFuture(callback, handler, new Callable<Void>() {
+            public Void call() throws Exception {
+                blockingInvalidateAuthToken(accountType, authToken);
+                return null;
+            }
+        });
+    }
+
+    public String blockingPeekAuthToken(Account account, String authTokenType) {
+        ensureNotOnMainThread();
+        try {
+            return mService.peekAuthToken(account, authTokenType);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+            throw new RuntimeException(e);
+        }
+    }
+
+    public Future1<String> peekAuthToken(Future1Callback<String> callback,
+            final Account account, final String authTokenType, final Handler handler) {
+        return startAsFuture(callback, handler, new Callable<String>() {
+            public String call() throws Exception {
+                return blockingPeekAuthToken(account, authTokenType);
+            }
+        });
+    }
+
+    public void blockingSetPassword(Account account, String password) {
+        ensureNotOnMainThread();
+        try {
+            mService.setPassword(account, password);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+        }
+    }
+
+    public Future1<Void> setPassword(Future1Callback<Void> callback,
+            final Account account, final String password, final Handler handler) {
+        return startAsFuture(callback, handler, new Callable<Void>() {
+            public Void call() throws Exception {
+                blockingSetPassword(account, password);
+                return null;
+            }
+        });
+    }
+
+    public void blockingClearPassword(Account account) {
+        ensureNotOnMainThread();
+        try {
+            mService.clearPassword(account);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+        }
+    }
+
+    public Future1<Void> clearPassword(final Future1Callback<Void> callback, final Account account,
+            final Handler handler) {
+        return startAsFuture(callback, handler, new Callable<Void>() {
+            public Void call() throws Exception {
+                blockingClearPassword(account);
+                return null;
+            }
+        });
+    }
+
+    public void blockingSetUserData(Account account, String key, String value) {
+        ensureNotOnMainThread();
+        try {
+            mService.setUserData(account, key, value);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+        }
+    }
+
+    public Future1<Void> setUserData(Future1Callback<Void> callback,
+            final Account account, final String key, final String value, final Handler handler) {
+        return startAsFuture(callback, handler, new Callable<Void>() {
+            public Void call() throws Exception {
+                blockingSetUserData(account, key, value);
+                return null;
+            }
+        });
+    }
+
+    public void blockingSetAuthToken(Account account, String authTokenType, String authToken) {
+        ensureNotOnMainThread();
+        try {
+            mService.setAuthToken(account, authTokenType, authToken);
+        } catch (RemoteException e) {
+            // if this happens the entire runtime will restart
+        }
+    }
+
+    public Future1<Void> setAuthToken(Future1Callback<Void> callback,
+            final Account account, final String authTokenType, final String authToken,
+            final Handler handler) {
+        return startAsFuture(callback, handler, new Callable<Void>() {
+            public Void call() throws Exception {
+                blockingSetAuthToken(account, authTokenType, authToken);
+                return null;
+            }
+        });
+    }
+
+    public String blockingGetAuthToken(Account account, String authTokenType,
+            boolean notifyAuthFailure)
+            throws OperationCanceledException, IOException, AuthenticatorException {
+        ensureNotOnMainThread();
+        Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
+                null /* handler */).getResult();
+        return bundle.getString(Constants.AUTHTOKEN_KEY);
+    }
+
+    /**
+     * Request the auth token for this account/authTokenType. If this succeeds then the
+     * auth token will then be passed to the activity. If this results in an authentication
+     * failure then a login intent will be returned that can be invoked to prompt the user to
+     * update their credentials. This login activity will return the auth token to the calling
+     * activity. If activity is null then the login intent will not be invoked.
+     *
+     * @param account the account whose auth token should be retrieved
+     * @param authTokenType the auth token type that should be retrieved
+     * @param loginOptions
+     * @param activity the activity to launch the login intent, if necessary, and to which
+     */
+    public Future2 getAuthToken(
+            final Account account, final String authTokenType, final Bundle loginOptions,
+            final Activity activity, Future2Callback callback, Handler handler) {
+        if (activity == null) throw new IllegalArgumentException("activity is null");
+        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
+        return new AmsTask(activity, handler, callback) {
+            public void doWork() throws RemoteException {
+                mService.getAuthToken(mResponse, account, authTokenType,
+                        false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
+                        loginOptions);
+            }
+        }.start();
+    }
+
+    public Future2 getAuthToken(
+            final Account account, final String authTokenType, final boolean notifyAuthFailure,
+            Future2Callback callback, Handler handler) {
+        if (account == null) throw new IllegalArgumentException("account is null");
+        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
+        return new AmsTask(null, handler, callback) {
+            public void doWork() throws RemoteException {
+                mService.getAuthToken(mResponse, account, authTokenType,
+                        notifyAuthFailure, false /* expectActivityLaunch */, null /* options */);
+            }
+        }.start();
+    }
+
+    public Future2 addAccount(final String accountType,
+            final String authTokenType, final String[] requiredFeatures,
+            final Bundle addAccountOptions,
+            final Activity activity, Future2Callback callback, Handler handler) {
+        return new AmsTask(activity, handler, callback) {
+            public void doWork() throws RemoteException {
+                mService.addAcount(mResponse, accountType, authTokenType,
+                        requiredFeatures, activity != null, addAccountOptions);
+            }
+        }.start();
+    }
+
+    /** @deprecated use {@link #confirmCredentials} instead */
+    public Future1<Boolean> confirmPassword(final Account account, final String password,
+            Future1Callback<Boolean> callback, Handler handler) {
+        return new AMSTaskBoolean(handler, callback) {
+            public void doWork() throws RemoteException {
+                mService.confirmPassword(response, account, password);
+            }
+        };
+    }
+
+    public Account[] blockingGetAccountsWithTypeAndFeatures(String type, String[] features)
+            throws AuthenticatorException, IOException, OperationCanceledException {
+        Future2 future = getAccountsWithTypeAndFeatures(type, features,
+                null /* callback */, null /* handler */);
+        Bundle result = future.getResult();
+        Parcelable[] accountsTemp = result.getParcelableArray(Constants.ACCOUNTS_KEY);
+        if (accountsTemp == null) {
+            throw new AuthenticatorException("accounts should not be null");
+        }
+        Account[] accounts = new Account[accountsTemp.length];
+        for (int i = 0; i < accountsTemp.length; i++) {
+            accounts[i] = (Account) accountsTemp[i];
+        }
+        return accounts;
+    }
+
+    public Future2 getAccountsWithTypeAndFeatures(
+            final String type, final String[] features,
+            Future2Callback callback, Handler handler) {
+        if (type == null) throw new IllegalArgumentException("type is null");
+        return new AmsTask(null /* activity */, handler, callback) {
+            public void doWork() throws RemoteException {
+                mService.getAccountsByTypeAndFeatures(mResponse, type, features);
+            }
+        }.start();
+    }
+
+    public Future2 confirmCredentials(final Account account, final Activity activity,
+            final Future2Callback callback,
+            final Handler handler) {
+        return new AmsTask(activity, handler, callback) {
+            public void doWork() throws RemoteException {
+                mService.confirmCredentials(mResponse, account, activity != null);
+            }
+        }.start();
+    }
+
+    public Future2 updateCredentials(final Account account, final String authTokenType,
+            final Bundle loginOptions, final Activity activity,
+            final Future2Callback callback,
+            final Handler handler) {
+        return new AmsTask(activity, handler, callback) {
+            public void doWork() throws RemoteException {
+                mService.updateCredentials(mResponse, account, authTokenType, activity != null,
+                        loginOptions);
+            }
+        }.start();
+    }
+
+    public Future2 editProperties(final String accountType, final Activity activity,
+            final Future2Callback callback,
+            final Handler handler) {
+        return new AmsTask(activity, handler, callback) {
+            public void doWork() throws RemoteException {
+                mService.editProperties(mResponse, accountType, activity != null);
+            }
+        }.start();
+    }
+
+    private void ensureNotOnMainThread() {
+        final Looper looper = Looper.myLooper();
+        if (looper != null && looper == mContext.getMainLooper()) {
+            // We really want to throw an exception here, but GTalkService exercises this
+            // path quite a bit and needs some serious rewrite in order to work properly.
+            //noinspection ThrowableInstanceNeverThrow
+//            Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
+//                    new Exception());
+            // TODO(fredq) remove the log and throw this exception when the callers are fixed
+//            throw new IllegalStateException(
+//                    "calling this from your main thread can lead to deadlock");
+        }
+    }
+
+    private void postToHandler(Handler handler, final Future2Callback callback,
+            final Future2 future) {
+        handler = handler == null ? mMainHandler : handler;
+        handler.post(new Runnable() {
+            public void run() {
+                callback.run(future);
+            }
+        });
+    }
+
+    private void postToHandler(Handler handler, final OnAccountsUpdatedListener listener,
+            final Account[] accounts) {
+        handler = handler == null ? mMainHandler : handler;
+        handler.post(new Runnable() {
+            public void run() {
+                listener.onAccountsUpdated(accounts);
+            }
+        });
+    }
+
+    private <V> void postToHandler(Handler handler, final Future1Callback<V> callback,
+            final Future1<V> future) {
+        handler = handler == null ? mMainHandler : handler;
+        handler.post(new Runnable() {
+            public void run() {
+                callback.run(future);
+            }
+        });
+    }
+
+    private <V> Future1<V> startAsFuture(Future1Callback<V> callback, Handler handler,
+            Callable<V> callable) {
+        final FutureTaskWithCallback<V> task =
+                new FutureTaskWithCallback<V>(callback, callable, handler);
+        new Thread(task).start();
+        return task;
+    }
+
+    private class FutureTaskWithCallback<V> extends FutureTask<V> implements Future1<V> {
+        final Future1Callback<V> mCallback;
+        final Handler mHandler;
+
+        public FutureTaskWithCallback(Future1Callback<V> callback, Callable<V> callable,
+                Handler handler) {
+            super(callable);
+            mCallback = callback;
+            mHandler = handler;
+        }
+
+        protected void done() {
+            if (mCallback != null) {
+                postToHandler(mHandler, mCallback, this);
+            }
+        }
+
+        public V internalGetResult(Long timeout, TimeUnit unit) throws OperationCanceledException {
+            try {
+                if (timeout == null) {
+                    return get();
+                } else {
+                    return get(timeout, unit);
+                }
+            } catch (InterruptedException e) {
+                // we will cancel the task below
+            } catch (CancellationException e) {
+                // we will cancel the task below
+            } catch (TimeoutException e) {
+                // we will cancel the task below
+            } catch (ExecutionException e) {
+                // this should never happen
+                throw new IllegalStateException(e.getCause());
+            } finally {
+                cancel(true /* interruptIfRunning */);
+            }
+            throw new OperationCanceledException();
+        }
+
+        public V getResult() throws OperationCanceledException {
+            return internalGetResult(null, null);
+        }
+
+        public V getResult(long timeout, TimeUnit unit) throws OperationCanceledException {
+            return internalGetResult(null, null);
+        }
+    }
+
+    private abstract class AmsTask extends FutureTask<Bundle> implements Future2 {
+        final IAccountManagerResponse mResponse;
+        final Handler mHandler;
+        final Future2Callback mCallback;
+        final Activity mActivity;
+        final Thread mThread;
+        public AmsTask(Activity activity, Handler handler, Future2Callback callback) {
+            super(new Callable<Bundle>() {
+                public Bundle call() throws Exception {
+                    throw new IllegalStateException("this should never be called");
+                }
+            });
+
+            mHandler = handler;
+            mCallback = callback;
+            mActivity = activity;
+            mResponse = new Response();
+            mThread = new Thread(new Runnable() {
+                public void run() {
+                    try {
+                        doWork();
+                    } catch (RemoteException e) {
+                        // never happens
+                    }
+                }
+            }, "AmsTask");
+        }
+
+        public final Future2 start() {
+            mThread.start();
+            return this;
+        }
+
+        public abstract void doWork() throws RemoteException;
+
+        private Bundle internalGetResult(Long timeout, TimeUnit unit)
+                throws OperationCanceledException, IOException, AuthenticatorException {
+            try {
+                if (timeout == null) {
+                    return get();
+                } else {
+                    return get(timeout, unit);
+                }
+            } catch (CancellationException e) {
+                throw new OperationCanceledException();
+            } catch (TimeoutException e) {
+                // fall through and cancel
+            } catch (InterruptedException e) {
+                // fall through and cancel
+            } catch (ExecutionException e) {
+                final Throwable cause = e.getCause();
+                if (cause instanceof IOException) {
+                    throw (IOException) cause;
+                } else if (cause instanceof UnsupportedOperationException) {
+                    throw new AuthenticatorException(cause);
+                } else if (cause instanceof AuthenticatorException) {
+                    throw (AuthenticatorException) cause;
+                } else if (cause instanceof RuntimeException) {
+                    throw (RuntimeException) cause;
+                } else if (cause instanceof Error) {
+                    throw (Error) cause;
+                } else {
+                    throw new IllegalStateException(cause);
+                }
+            } finally {
+                cancel(true /* interrupt if running */);
+            }
+            throw new OperationCanceledException();
+        }
+
+        public Bundle getResult()
+                throws OperationCanceledException, IOException, AuthenticatorException {
+            return internalGetResult(null, null);
+        }
+
+        public Bundle getResult(long timeout, TimeUnit unit)
+                throws OperationCanceledException, IOException, AuthenticatorException {
+            return internalGetResult(timeout, unit);
+        }
+
+        protected void done() {
+            if (mCallback != null) {
+                postToHandler(mHandler, mCallback, this);
+            }
+        }
+
+        /** Handles the responses from the AccountManager */
+        private class Response extends IAccountManagerResponse.Stub {
+            public void onResult(Bundle bundle) {
+                Intent intent = bundle.getParcelable("intent");
+                if (intent != null && mActivity != null) {
+                    // since the user provided an Activity we will silently start intents
+                    // that we see
+                    mActivity.startActivity(intent);
+                    // leave the Future running to wait for the real response to this request
+                } else if (bundle.getBoolean("retry")) {
+                    try {
+                        doWork();
+                    } catch (RemoteException e) {
+                        // this will only happen if the system process is dead, which means
+                        // we will be dying ourselves
+                    }
+                } else {
+                    set(bundle);
+                }
+            }
+
+            public void onError(int code, String message) {
+                if (code == Constants.ERROR_CODE_CANCELED) {
+                    // the authenticator indicated that this request was canceled, do so now
+                    cancel(true /* mayInterruptIfRunning */);
+                    return;
+                }
+                setException(convertErrorToException(code, message));
+            }
+        }
+
+    }
+
+    private abstract class AMSTaskBoolean extends FutureTask<Boolean> implements Future1<Boolean> {
+        final IAccountManagerResponse response;
+        final Handler mHandler;
+        final Future1Callback<Boolean> mCallback;
+        public AMSTaskBoolean(Handler handler, Future1Callback<Boolean> callback) {
+            super(new Callable<Boolean>() {
+                public Boolean call() throws Exception {
+                    throw new IllegalStateException("this should never be called");
+                }
+            });
+
+            mHandler = handler;
+            mCallback = callback;
+            response = new Response();
+
+            new Thread(new Runnable() {
+                public void run() {
+                    try {
+                        doWork();
+                    } catch (RemoteException e) {
+                        // never happens
+                    }
+                }
+            }).start();
+        }
+
+        public abstract void doWork() throws RemoteException;
+
+
+        protected void done() {
+            if (mCallback != null) {
+                postToHandler(mHandler, mCallback, this);
+            }
+        }
+
+        private Boolean internalGetResult(Long timeout, TimeUnit unit) {
+            try {
+                if (timeout == null) {
+                    return get();
+                } else {
+                    return get(timeout, unit);
+                }
+            } catch (InterruptedException e) {
+                // fall through and cancel
+            } catch (TimeoutException e) {
+                // fall through and cancel
+            } catch (CancellationException e) {
+                return false;
+            } catch (ExecutionException e) {
+                final Throwable cause = e.getCause();
+                if (cause instanceof IOException) {
+                    return false;
+                } else if (cause instanceof UnsupportedOperationException) {
+                    return false;
+                } else if (cause instanceof AuthenticatorException) {
+                    return false;
+                } else if (cause instanceof RuntimeException) {
+                    throw (RuntimeException) cause;
+                } else if (cause instanceof Error) {
+                    throw (Error) cause;
+                } else {
+                    throw new IllegalStateException(cause);
+                }
+            } finally {
+                cancel(true /* interrupt if running */);
+            }
+            return false;
+        }
+
+        public Boolean getResult() throws OperationCanceledException {
+            return internalGetResult(null, null);
+        }
+
+        public Boolean getResult(long timeout, TimeUnit unit) throws OperationCanceledException {
+            return internalGetResult(timeout, unit);
+        }
+
+        private class Response extends IAccountManagerResponse.Stub {
+            public void onResult(Bundle bundle) {
+                try {
+                    if (bundle.containsKey(Constants.BOOLEAN_RESULT_KEY)) {
+                        set(bundle.getBoolean(Constants.BOOLEAN_RESULT_KEY));
+                        return;
+                    }
+                } catch (ClassCastException e) {
+                    // we will set the exception below
+                }
+                onError(Constants.ERROR_CODE_INVALID_RESPONSE, "no result in response");
+            }
+
+            public void onError(int code, String message) {
+                if (code == Constants.ERROR_CODE_CANCELED) {
+                    cancel(true /* mayInterruptIfRunning */);
+                    return;
+                }
+                setException(convertErrorToException(code, message));
+            }
+        }
+
+    }
+
+    private Exception convertErrorToException(int code, String message) {
+        if (code == Constants.ERROR_CODE_NETWORK_ERROR) {
+            return new IOException(message);
+        }
+
+        if (code == Constants.ERROR_CODE_UNSUPPORTED_OPERATION) {
+            return new UnsupportedOperationException(message);
+        }
+
+        if (code == Constants.ERROR_CODE_INVALID_RESPONSE) {
+            return new AuthenticatorException(message);
+        }
+
+        if (code == Constants.ERROR_CODE_BAD_ARGUMENTS) {
+            return new IllegalArgumentException(message);
+        }
+
+        return new AuthenticatorException(message);
+    }
+
+    private class GetAuthTokenByTypeAndFeaturesTask extends AmsTask implements Future2Callback {
+        GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
+                final String[] features, Activity activityForPrompting,
+                final Bundle addAccountOptions, final Bundle loginOptions,
+                Future2Callback callback, Handler handler) {
+            super(activityForPrompting, handler, callback);
+            if (accountType == null) throw new IllegalArgumentException("account type is null");
+            mAccountType = accountType;
+            mAuthTokenType = authTokenType;
+            mFeatures = features;
+            mAddAccountOptions = addAccountOptions;
+            mLoginOptions = loginOptions;
+            mMyCallback = this;
+        }
+        volatile Future2 mFuture = null;
+        final String mAccountType;
+        final String mAuthTokenType;
+        final String[] mFeatures;
+        final Bundle mAddAccountOptions;
+        final Bundle mLoginOptions;
+        final Future2Callback mMyCallback;
+
+        public void doWork() throws RemoteException {
+            getAccountsWithTypeAndFeatures(mAccountType, mFeatures, new Future2Callback() {
+                public void run(Future2 future) {
+                    Bundle getAccountsResult;
+                    try {
+                        getAccountsResult = future.getResult();
+                    } catch (OperationCanceledException e) {
+                        setException(e);
+                        return;
+                    } catch (IOException e) {
+                        setException(e);
+                        return;
+                    } catch (AuthenticatorException e) {
+                        setException(e);
+                        return;
+                    }
+
+                    Parcelable[] accounts =
+                            getAccountsResult.getParcelableArray(Constants.ACCOUNTS_KEY);
+                    if (accounts.length == 0) {
+                        if (mActivity != null) {
+                            // no accounts, add one now. pretend that the user directly
+                            // made this request
+                            mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
+                                    mAddAccountOptions, mActivity, mMyCallback, mHandler);
+                        } else {
+                            // send result since we can't prompt to add an account
+                            Bundle result = new Bundle();
+                            result.putString(Constants.ACCOUNT_NAME_KEY, null);
+                            result.putString(Constants.ACCOUNT_TYPE_KEY, null);
+                            result.putString(Constants.AUTHTOKEN_KEY, null);
+                            try {
+                                mResponse.onResult(result);
+                            } catch (RemoteException e) {
+                                // this will never happen
+                            }
+                            // we are done
+                        }
+                    } else if (accounts.length == 1) {
+                        // have a single account, return an authtoken for it
+                        if (mActivity == null) {
+                            mFuture = getAuthToken((Account) accounts[0], mAuthTokenType,
+                                    false /* notifyAuthFailure */, mMyCallback, mHandler);
+                        } else {
+                            mFuture = getAuthToken((Account) accounts[0],
+                                    mAuthTokenType, mLoginOptions,
+                                    mActivity, mMyCallback, mHandler);
+                        }
+                    } else {
+                        if (mActivity != null) {
+                            IAccountManagerResponse chooseResponse =
+                                    new IAccountManagerResponse.Stub() {
+                                public void onResult(Bundle value) throws RemoteException {
+                                    Account account = new Account(
+                                            value.getString(Constants.ACCOUNT_NAME_KEY),
+                                            value.getString(Constants.ACCOUNT_TYPE_KEY));
+                                    mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
+                                            mActivity, mMyCallback, mHandler);
+                                }
+
+                                public void onError(int errorCode, String errorMessage)
+                                        throws RemoteException {
+                                    mResponse.onError(errorCode, errorMessage);
+                                }
+                            };
+                            // have many accounts, launch the chooser
+                            Intent intent = new Intent();
+                            intent.setClassName("android",
+                                    "android.accounts.ChooseAccountActivity");
+                            intent.putExtra(Constants.ACCOUNTS_KEY, accounts);
+                            intent.putExtra(Constants.ACCOUNT_MANAGER_RESPONSE_KEY,
+                                    new AccountManagerResponse(chooseResponse));
+                            mActivity.startActivity(intent);
+                            // the result will arrive via the IAccountManagerResponse
+                        } else {
+                            // send result since we can't prompt to select an account
+                            Bundle result = new Bundle();
+                            result.putString(Constants.ACCOUNTS_KEY, null);
+                            try {
+                                mResponse.onResult(result);
+                            } catch (RemoteException e) {
+                                // this will never happen
+                            }
+                            // we are done
+                        }
+                    }
+                }}, mHandler);
+        }
+
+
+
+        // TODO(fredq) pass through the calls to our implemention of Future2 to the underlying
+        // future that we create. We need to do things like have cancel cancel the mFuture, if set
+        // or to cause this to be canceled if mFuture isn't set.
+        // Once this is done then getAuthTokenByFeatures can be changed to return a Future2.
+
+        public void run(Future2 future) {
+            try {
+                set(future.get());
+            } catch (InterruptedException e) {
+                cancel(true);
+            } catch (CancellationException e) {
+                cancel(true);
+            } catch (ExecutionException e) {
+                setException(e.getCause());
+            }
+        }
+    }
+
+    public void getAuthTokenByFeatures(
+            final String accountType, final String authTokenType, final String[] features,
+            final Activity activityForPrompting, final Bundle addAccountOptions,
+            final Bundle loginOptions,
+            final Future2Callback callback, final Handler handler) {
+        if (accountType == null) throw new IllegalArgumentException("account type is null");
+        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
+        new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType,  features,
+                activityForPrompting, addAccountOptions, loginOptions, callback, handler).start();
+    }
+
+    private final HashMap<OnAccountsUpdatedListener, Handler> mAccountsUpdatedListeners =
+            Maps.newHashMap();
+
+    // These variable are only used from the LOGIN_ACCOUNTS_CHANGED_ACTION BroadcastReceiver
+    // and its getAccounts() callback which are both invoked only on the main thread. As a
+    // result we don't need to protect against concurrent accesses and any changes are guaranteed
+    // to be visible when used. Basically, these two variables are thread-confined.
+    private Future1<Account[]> mAccountsLookupFuture = null;
+    private boolean mAccountLookupPending = false;
+
+    /**
+     * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
+     * so that it can read the updated list of accounts and send them to the listener
+     * in mAccountsUpdatedListeners.
+     */
+    private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
+        public void onReceive(final Context context, final Intent intent) {
+            if (mAccountsLookupFuture != null) {
+                // an accounts lookup is already in progress,
+                // don't bother starting another request
+                mAccountLookupPending = true;
+                return;
+            }
+            // initiate a read of the accounts
+            mAccountsLookupFuture = getAccounts(new Future1Callback<Account[]>() {
+                public void run(Future1<Account[]> future) {
+                    // clear the future so that future receives will try the lookup again
+                    mAccountsLookupFuture = null;
+
+                    // get the accounts array
+                    Account[] accounts;
+                    try {
+                        accounts = future.getResult();
+                    } catch (OperationCanceledException e) {
+                        // this should never happen, but if it does pretend we got another
+                        // accounts changed broadcast
+                        if (Config.LOGD) {
+                            Log.d(TAG, "the accounts lookup for listener notifications was "
+                                    + "canceled, try again by simulating the receipt of "
+                                    + "a LOGIN_ACCOUNTS_CHANGED_ACTION broadcast");
+                        }
+                        onReceive(context, intent);
+                        return;
+                    }
+
+                    // send the result to the listeners
+                    synchronized (mAccountsUpdatedListeners) {
+                        for (Map.Entry<OnAccountsUpdatedListener, Handler> entry :
+                                mAccountsUpdatedListeners.entrySet()) {
+                            Account[] accountsCopy = new Account[accounts.length];
+                            // send the listeners a copy to make sure that one doesn't
+                            // change what another sees
+                            System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
+                            postToHandler(entry.getValue(), entry.getKey(), accountsCopy);
+                        }
+                    }
+
+                    // If mAccountLookupPending was set when the account lookup finished it
+                    // means that we had previously ignored a LOGIN_ACCOUNTS_CHANGED_ACTION
+                    // intent because a lookup was already in progress. Now that we are done
+                    // with this lookup and notification pretend that another intent
+                    // was received by calling onReceive() directly.
+                    if (mAccountLookupPending) {
+                        mAccountLookupPending = false;
+                        onReceive(context, intent);
+                        return;
+                    }
+                }
+            }, mMainHandler);
+        }
+    };
+
+    /**
+     * Add a {@link OnAccountsUpdatedListener} to this instance of the {@link AccountManager}.
+     * The listener is guaranteed to be invoked on the thread of the Handler that is passed
+     * in or the main thread's Handler if handler is null.
+     * @param listener the listener to add
+     * @param handler the Handler whose thread will be used to invoke the listener. If null
+     * the AccountManager context's main thread will be used.
+     * @param updateImmediately if true then the listener will be invoked as a result of this
+     * call.
+     * @throws IllegalArgumentException if listener is null
+     * @throws IllegalStateException if listener was already added
+     */
+    public void addOnAccountsUpdatedListener(final OnAccountsUpdatedListener listener,
+            Handler handler, boolean updateImmediately) {
+        if (listener == null) {
+            throw new IllegalArgumentException("the listener is null");
+        }
+        synchronized (mAccountsUpdatedListeners) {
+            if (mAccountsUpdatedListeners.containsKey(listener)) {
+                throw new IllegalStateException("this listener is already added");
+            }
+            final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
+
+            mAccountsUpdatedListeners.put(listener, handler);
+
+            if (wasEmpty) {
+                // Register a broadcast receiver to monitor account changes
+                IntentFilter intentFilter = new IntentFilter();
+                intentFilter.addAction(Constants.LOGIN_ACCOUNTS_CHANGED_ACTION);
+                mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
+            }
+        }
+
+        if (updateImmediately) {
+            getAccounts(new Future1Callback<Account[]>() {
+                public void run(Future1<Account[]> future) {
+                    try {
+                        listener.onAccountsUpdated(future.getResult());
+                    } catch (OperationCanceledException e) {
+                        // ignore
+                    }
+                }
+            }, handler);
+        }
+    }
+
+    /**
+     * Remove an {@link OnAccountsUpdatedListener} that was previously registered with
+     * {@link #addOnAccountsUpdatedListener}.
+     * @param listener the listener to remove
+     * @throws IllegalArgumentException if listener is null
+     * @throws IllegalStateException if listener was not already added
+     */
+    public void removeOnAccountsUpdatedListener(OnAccountsUpdatedListener listener) {
+        if (listener == null) {
+            throw new IllegalArgumentException("the listener is null");
+        }
+        synchronized (mAccountsUpdatedListeners) {
+            if (mAccountsUpdatedListeners.remove(listener) == null) {
+                throw new IllegalStateException("this listener was not previously added");
+            }
+            if (mAccountsUpdatedListeners.isEmpty()) {
+                mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
+            }
+        }
+    }
+}
diff --git a/core/java/android/accounts/AccountManagerResponse.java b/core/java/android/accounts/AccountManagerResponse.java
new file mode 100644
index 0000000..25371fd
--- /dev/null
+++ b/core/java/android/accounts/AccountManagerResponse.java
@@ -0,0 +1,74 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.os.Bundle;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.os.RemoteException;
+
+/**
+ * Object that wraps calls to an {@link android.accounts.IAccountManagerResponse} object.
+ * @hide
+ */
+public class AccountManagerResponse implements Parcelable {
+    private IAccountManagerResponse mResponse;
+
+    public AccountManagerResponse(IAccountManagerResponse response) {
+        mResponse = response;
+    }
+
+    public AccountManagerResponse(Parcel parcel) {
+        mResponse =
+                IAccountManagerResponse.Stub.asInterface(parcel.readStrongBinder());
+    }
+
+    public void onResult(Bundle result) {
+        try {
+            mResponse.onResult(result);
+        } catch (RemoteException e) {
+            // this should never happen
+        }
+    }
+
+    public void onError(int errorCode, String errorMessage) {
+        try {
+            mResponse.onError(errorCode, errorMessage);
+        } catch (RemoteException e) {
+            // this should never happen
+        }
+    }
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeStrongBinder(mResponse.asBinder());
+    }
+
+    public static final Creator<AccountManagerResponse> CREATOR =
+            new Creator<AccountManagerResponse>() {
+        public AccountManagerResponse createFromParcel(Parcel source) {
+            return new AccountManagerResponse(source);
+        }
+
+        public AccountManagerResponse[] newArray(int size) {
+            return new AccountManagerResponse[size];
+        }
+    };
+}
\ No newline at end of file
diff --git a/core/java/android/accounts/AccountManagerService.java b/core/java/android/accounts/AccountManagerService.java
new file mode 100644
index 0000000..0c941be
--- /dev/null
+++ b/core/java/android/accounts/AccountManagerService.java
@@ -0,0 +1,1522 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.content.BroadcastReceiver;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageManager;
+import android.content.pm.RegisteredServicesCache;
+import android.database.Cursor;
+import android.database.DatabaseUtils;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteOpenHelper;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.Message;
+import android.os.RemoteException;
+import android.os.SystemClock;
+import android.os.Binder;
+import android.os.SystemProperties;
+import android.telephony.TelephonyManager;
+import android.text.TextUtils;
+import android.util.Log;
+import android.util.Pair;
+import android.app.PendingIntent;
+import android.app.NotificationManager;
+import android.app.Notification;
+import android.Manifest;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.HashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.android.internal.telephony.TelephonyIntents;
+import com.android.internal.R;
+
+/**
+ * A system service that provides  account, password, and authtoken management for all
+ * accounts on the device. Some of these calls are implemented with the help of the corresponding
+ * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
+ * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
+ *    AccountManager accountManager =
+ *      (AccountManager)context.getSystemService(Context.ACCOUNT_SERVICE)
+ * @hide
+ */
+public class AccountManagerService extends IAccountManager.Stub {
+    private static final String TAG = "AccountManagerService";
+
+    private static final int TIMEOUT_DELAY_MS = 1000 * 60;
+    private static final String DATABASE_NAME = "accounts.db";
+    private static final int DATABASE_VERSION = 3;
+
+    private final Context mContext;
+
+    private HandlerThread mMessageThread;
+    private final MessageHandler mMessageHandler;
+
+    // Messages that can be sent on mHandler
+    private static final int MESSAGE_TIMED_OUT = 3;
+    private static final int MESSAGE_CONNECTED = 7;
+    private static final int MESSAGE_DISCONNECTED = 8;
+
+    private final AccountAuthenticatorCache mAuthenticatorCache;
+    private final AuthenticatorBindHelper mBindHelper;
+    private final DatabaseHelper mOpenHelper;
+    private final SimWatcher mSimWatcher;
+
+    private static final String TABLE_ACCOUNTS = "accounts";
+    private static final String ACCOUNTS_ID = "_id";
+    private static final String ACCOUNTS_NAME = "name";
+    private static final String ACCOUNTS_TYPE = "type";
+    private static final String ACCOUNTS_PASSWORD = "password";
+
+    private static final String TABLE_AUTHTOKENS = "authtokens";
+    private static final String AUTHTOKENS_ID = "_id";
+    private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
+    private static final String AUTHTOKENS_TYPE = "type";
+    private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
+
+    private static final String TABLE_GRANTS = "grants";
+    private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
+    private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
+    private static final String GRANTS_GRANTEE_UID = "uid";
+
+    private static final String TABLE_EXTRAS = "extras";
+    private static final String EXTRAS_ID = "_id";
+    private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
+    private static final String EXTRAS_KEY = "key";
+    private static final String EXTRAS_VALUE = "value";
+
+    private static final String TABLE_META = "meta";
+    private static final String META_KEY = "key";
+    private static final String META_VALUE = "value";
+
+    private static final String[] ACCOUNT_NAME_TYPE_PROJECTION =
+            new String[]{ACCOUNTS_ID, ACCOUNTS_NAME, ACCOUNTS_TYPE};
+    private static final Intent ACCOUNTS_CHANGED_INTENT =
+            new Intent(Constants.LOGIN_ACCOUNTS_CHANGED_ACTION);
+
+    private static final String COUNT_OF_MATCHING_GRANTS = ""
+            + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
+            + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
+            + " AND " + GRANTS_GRANTEE_UID + "=?"
+            + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
+            + " AND " + ACCOUNTS_NAME + "=?"
+            + " AND " + ACCOUNTS_TYPE + "=?";
+
+    private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
+    private final AtomicInteger mNotificationIds = new AtomicInteger(1);
+
+    private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
+            mCredentialsPermissionNotificationIds =
+            new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
+    private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
+            new HashMap<Account, Integer>();
+    private static AtomicReference<AccountManagerService> sThis =
+            new AtomicReference<AccountManagerService>();
+
+    private static final boolean isDebuggableMonkeyBuild =
+            SystemProperties.getBoolean("ro.monkey", false)
+                    && SystemProperties.getBoolean("ro.debuggable", false);
+    /**
+     * This should only be called by system code. One should only call this after the service
+     * has started.
+     * @return a reference to the AccountManagerService instance
+     * @hide
+     */
+    public static AccountManagerService getSingleton() {
+        return sThis.get();
+    }
+
+    public class AuthTokenKey {
+        public final Account mAccount;
+        public final String mAuthTokenType;
+        private final int mHashCode;
+
+        public AuthTokenKey(Account account, String authTokenType) {
+            mAccount = account;
+            mAuthTokenType = authTokenType;
+            mHashCode = computeHashCode();
+        }
+
+        public boolean equals(Object o) {
+            if (o == this) {
+                return true;
+            }
+            if (!(o instanceof AuthTokenKey)) {
+                return false;
+            }
+            AuthTokenKey other = (AuthTokenKey)o;
+            if (!mAccount.equals(other.mAccount)) {
+                return false;
+            }
+            return (mAuthTokenType == null)
+                    ? other.mAuthTokenType == null
+                    : mAuthTokenType.equals(other.mAuthTokenType);
+        }
+
+        private int computeHashCode() {
+            int result = 17;
+            result = 31 * result + mAccount.hashCode();
+            result = 31 * result + ((mAuthTokenType == null) ? 0 : mAuthTokenType.hashCode());
+            return result;
+        }
+
+        public int hashCode() {
+            return mHashCode;
+        }
+    }
+
+    public AccountManagerService(Context context) {
+        mContext = context;
+
+        mOpenHelper = new DatabaseHelper(mContext);
+
+        mMessageThread = new HandlerThread("AccountManagerService");
+        mMessageThread.start();
+        mMessageHandler = new MessageHandler(mMessageThread.getLooper());
+
+        mAuthenticatorCache = new AccountAuthenticatorCache(mContext);
+        mBindHelper = new AuthenticatorBindHelper(mContext, mAuthenticatorCache, mMessageHandler,
+                MESSAGE_CONNECTED, MESSAGE_DISCONNECTED);
+
+        mSimWatcher = new SimWatcher(mContext);
+        sThis.set(this);
+    }
+
+    public String getPassword(Account account) {
+        checkAuthenticateAccountsPermission(account);
+
+        long identityToken = clearCallingIdentity();
+        try {
+            SQLiteDatabase db = mOpenHelper.getReadableDatabase();
+            Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
+                    ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
+                    new String[]{account.mName, account.mType}, null, null, null);
+            try {
+                if (cursor.moveToNext()) {
+                    return cursor.getString(0);
+                }
+                return null;
+            } finally {
+                cursor.close();
+            }
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public String getUserData(Account account, String key) {
+        checkAuthenticateAccountsPermission(account);
+        long identityToken = clearCallingIdentity();
+        try {
+            SQLiteDatabase db = mOpenHelper.getReadableDatabase();
+            db.beginTransaction();
+            try {
+                long accountId = getAccountId(db, account);
+                if (accountId < 0) {
+                    return null;
+                }
+                Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_VALUE},
+                        EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
+                        new String[]{key}, null, null, null);
+                try {
+                    if (cursor.moveToNext()) {
+                        return cursor.getString(0);
+                    }
+                    return null;
+                } finally {
+                    cursor.close();
+                }
+            } finally {
+                db.endTransaction();
+            }
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public AuthenticatorDescription[] getAuthenticatorTypes() {
+        long identityToken = clearCallingIdentity();
+        try {
+            Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
+                    authenticatorCollection = mAuthenticatorCache.getAllServices();
+            AuthenticatorDescription[] types =
+                    new AuthenticatorDescription[authenticatorCollection.size()];
+            int i = 0;
+            for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
+                    : authenticatorCollection) {
+                types[i] = authenticator.type;
+                i++;
+            }
+            return types;
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public Account[] getAccounts() {
+        checkReadAccountsPermission();
+        long identityToken = clearCallingIdentity();
+        try {
+            return getAccountsByType(null);
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public Account[] getAccountsByType(String accountType) {
+        checkReadAccountsPermission();
+        long identityToken = clearCallingIdentity();
+        try {
+            SQLiteDatabase db = mOpenHelper.getReadableDatabase();
+
+            final String selection = accountType == null ? null : (ACCOUNTS_TYPE + "=?");
+            final String[] selectionArgs = accountType == null ? null : new String[]{accountType};
+            Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_NAME_TYPE_PROJECTION,
+                    selection, selectionArgs, null, null, null);
+            try {
+                int i = 0;
+                Account[] accounts = new Account[cursor.getCount()];
+                while (cursor.moveToNext()) {
+                    accounts[i] = new Account(cursor.getString(1), cursor.getString(2));
+                    i++;
+                }
+                return accounts;
+            } finally {
+                cursor.close();
+            }
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public boolean addAccount(Account account, String password, Bundle extras) {
+        checkAuthenticateAccountsPermission(account);
+
+        // fails if the account already exists
+        long identityToken = clearCallingIdentity();
+        try {
+            SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+            db.beginTransaction();
+            try {
+                long numMatches = DatabaseUtils.longForQuery(db,
+                        "select count(*) from " + TABLE_ACCOUNTS
+                                + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
+                        new String[]{account.mName, account.mType});
+                if (numMatches > 0) {
+                    return false;
+                }
+                ContentValues values = new ContentValues();
+                values.put(ACCOUNTS_NAME, account.mName);
+                values.put(ACCOUNTS_TYPE, account.mType);
+                values.put(ACCOUNTS_PASSWORD, password);
+                long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
+                if (accountId < 0) {
+                    return false;
+                }
+                if (extras != null) {
+                    for (String key : extras.keySet()) {
+                        final String value = extras.getString(key);
+                        if (insertExtra(db, accountId, key, value) < 0) {
+                            return false;
+                        }
+                    }
+                }
+                db.setTransactionSuccessful();
+                sendAccountsChangedBroadcast();
+                return true;
+            } finally {
+                db.endTransaction();
+            }
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
+        ContentValues values = new ContentValues();
+        values.put(EXTRAS_KEY, key);
+        values.put(EXTRAS_ACCOUNTS_ID, accountId);
+        values.put(EXTRAS_VALUE, value);
+        return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
+    }
+
+    public void removeAccount(Account account) {
+        checkManageAccountsPermission();
+        long identityToken = clearCallingIdentity();
+        try {
+            final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+            db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
+                    new String[]{account.mName, account.mType});
+            sendAccountsChangedBroadcast();
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public void invalidateAuthToken(String accountType, String authToken) {
+        checkManageAccountsPermission();
+        long identityToken = clearCallingIdentity();
+        try {
+            SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+            db.beginTransaction();
+            try {
+                invalidateAuthToken(db, accountType, authToken);
+                db.setTransactionSuccessful();
+            } finally {
+                db.endTransaction();
+            }
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
+        Cursor cursor = db.rawQuery(
+                "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
+                        + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
+                        + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
+                        + " FROM " + TABLE_ACCOUNTS
+                        + " JOIN " + TABLE_AUTHTOKENS
+                        + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
+                        + " = " + AUTHTOKENS_ACCOUNTS_ID
+                        + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
+                        + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
+                new String[]{authToken, accountType});
+        try {
+            while (cursor.moveToNext()) {
+                long authTokenId = cursor.getLong(0);
+                String accountName = cursor.getString(1);
+                String authTokenType = cursor.getString(2);
+                db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
+            }
+        } finally {
+            cursor.close();
+        }
+    }
+
+    private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
+        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+        db.beginTransaction();
+        try {
+            long accountId = getAccountId(db, account);
+            if (accountId < 0) {
+                return false;
+            }
+            db.delete(TABLE_AUTHTOKENS,
+                    AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
+                    new String[]{type});
+            ContentValues values = new ContentValues();
+            values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
+            values.put(AUTHTOKENS_TYPE, type);
+            values.put(AUTHTOKENS_AUTHTOKEN, authToken);
+            if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
+                db.setTransactionSuccessful();
+                return true;
+            }
+            return false;
+        } finally {
+            db.endTransaction();
+        }
+    }
+
+    public String readAuthTokenFromDatabase(Account account, String authTokenType) {
+        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
+        db.beginTransaction();
+        try {
+            long accountId = getAccountId(db, account);
+            if (accountId < 0) {
+                return null;
+            }
+            return getAuthToken(db, accountId, authTokenType);
+        } finally {
+            db.endTransaction();
+        }
+    }
+
+    public String peekAuthToken(Account account, String authTokenType) {
+        checkAuthenticateAccountsPermission(account);
+        long identityToken = clearCallingIdentity();
+        try {
+            return readAuthTokenFromDatabase(account, authTokenType);
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public void setAuthToken(Account account, String authTokenType, String authToken) {
+        checkAuthenticateAccountsPermission(account);
+        long identityToken = clearCallingIdentity();
+        try {
+            cacheAuthToken(account, authTokenType, authToken);
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public void setPassword(Account account, String password) {
+        checkAuthenticateAccountsPermission(account);
+        long identityToken = clearCallingIdentity();
+        try {
+            ContentValues values = new ContentValues();
+            values.put(ACCOUNTS_PASSWORD, password);
+            mOpenHelper.getWritableDatabase().update(TABLE_ACCOUNTS, values,
+                    ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
+                    new String[]{account.mName, account.mType});
+            sendAccountsChangedBroadcast();
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    private void sendAccountsChangedBroadcast() {
+        mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
+    }
+
+    public void clearPassword(Account account) {
+        checkManageAccountsPermission();
+        long identityToken = clearCallingIdentity();
+        try {
+            setPassword(account, null);
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public void setUserData(Account account, String key, String value) {
+        checkAuthenticateAccountsPermission(account);
+        long identityToken = clearCallingIdentity();
+        try {
+            SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+            db.beginTransaction();
+            try {
+                long accountId = getAccountId(db, account);
+                if (accountId < 0) {
+                    return;
+                }
+                long extrasId = getExtrasId(db, accountId, key);
+                if (extrasId < 0 ) {
+                    extrasId = insertExtra(db, accountId, key, value);
+                    if (extrasId < 0) {
+                        return;
+                    }
+                } else {
+                    ContentValues values = new ContentValues();
+                    values.put(EXTRAS_VALUE, value);
+                    if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
+                        return;
+                    }
+
+                }
+                db.setTransactionSuccessful();
+            } finally {
+                db.endTransaction();
+            }
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    private void onResult(IAccountManagerResponse response, Bundle result) {
+        try {
+            response.onResult(result);
+        } catch (RemoteException e) {
+            // if the caller is dead then there is no one to care about remote
+            // exceptions
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "failure while notifying response", e);
+            }
+        }
+    }
+
+    public void getAuthToken(IAccountManagerResponse response, final Account account,
+            final String authTokenType, final boolean notifyOnAuthFailure,
+            final boolean expectActivityLaunch, final Bundle loginOptions) {
+        checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
+        final int callerUid = Binder.getCallingUid();
+        final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
+
+        long identityToken = clearCallingIdentity();
+        try {
+            // if the caller has permission, do the peek. otherwise go the more expensive
+            // route of starting a Session
+            if (permissionGranted) {
+                String authToken = readAuthTokenFromDatabase(account, authTokenType);
+                if (authToken != null) {
+                    Bundle result = new Bundle();
+                    result.putString(Constants.AUTHTOKEN_KEY, authToken);
+                    result.putString(Constants.ACCOUNT_NAME_KEY, account.mName);
+                    result.putString(Constants.ACCOUNT_TYPE_KEY, account.mType);
+                    onResult(response, result);
+                    return;
+                }
+            }
+
+            new Session(response, account.mType, expectActivityLaunch) {
+                protected String toDebugString(long now) {
+                    if (loginOptions != null) loginOptions.keySet();
+                    return super.toDebugString(now) + ", getAuthToken"
+                            + ", " + account
+                            + ", authTokenType " + authTokenType
+                            + ", loginOptions " + loginOptions
+                            + ", notifyOnAuthFailure " + notifyOnAuthFailure;
+                }
+
+                public void run() throws RemoteException {
+                    // If the caller doesn't have permission then create and return the
+                    // "grant permission" intent instead of the "getAuthToken" intent.
+                    if (!permissionGranted) {
+                        mAuthenticator.getAuthTokenLabel(this, authTokenType);
+                    } else {
+                        mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
+                    }
+                }
+
+                public void onResult(Bundle result) {
+                    if (result != null) {
+                        if (result.containsKey(Constants.AUTH_TOKEN_LABEL_KEY)) {
+                            Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
+                                    new AccountAuthenticatorResponse(this),
+                                    authTokenType,
+                                    result.getString(Constants.AUTH_TOKEN_LABEL_KEY));
+                            Bundle bundle = new Bundle();
+                            bundle.putParcelable(Constants.INTENT_KEY, intent);
+                            onResult(bundle);
+                            return;
+                        }
+                        String authToken = result.getString(Constants.AUTHTOKEN_KEY);
+                        if (authToken != null) {
+                            String name = result.getString(Constants.ACCOUNT_NAME_KEY);
+                            String type = result.getString(Constants.ACCOUNT_TYPE_KEY);
+                            if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
+                                onError(Constants.ERROR_CODE_INVALID_RESPONSE,
+                                        "the type and name should not be empty");
+                                return;
+                            }
+                            cacheAuthToken(new Account(name, type), authTokenType, authToken);
+                        }
+
+                        Intent intent = result.getParcelable(Constants.INTENT_KEY);
+                        if (intent != null && notifyOnAuthFailure) {
+                            doNotification(
+                                    account, result.getString(Constants.AUTH_FAILED_MESSAGE_KEY),
+                                    intent);
+                        }
+                    }
+                    super.onResult(result);
+                }
+            }.bind();
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
+        int uid = intent.getIntExtra(
+                GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
+        String authTokenType = intent.getStringExtra(
+                GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
+        String authTokenLabel = intent.getStringExtra(
+                GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
+
+        Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
+                0 /* when */);
+        final CharSequence subtitleFormatString =
+                mContext.getText(R.string.permission_request_notification_subtitle);
+        n.setLatestEventInfo(mContext,
+                mContext.getText(R.string.permission_request_notification_title),
+                String.format(subtitleFormatString.toString(), account.mName),
+                PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
+        ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
+                .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
+    }
+
+    private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
+            AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
+        RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
+                mAuthenticatorCache.getServiceInfo(
+                        AuthenticatorDescription.newKey(account.mType));
+        if (serviceInfo == null) {
+            throw new IllegalArgumentException("unknown account type: " + account.mType);
+        }
+
+        final Context authContext;
+        try {
+            authContext = mContext.createPackageContext(
+                serviceInfo.type.packageName, 0);
+        } catch (PackageManager.NameNotFoundException e) {
+            throw new IllegalArgumentException("unknown account type: " + account.mType);
+        }
+
+        Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        intent.addCategory(
+                String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
+        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
+        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
+        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
+        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
+        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
+                        authContext.getString(serviceInfo.type.labelId));
+        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
+                        mContext.getPackageManager().getPackagesForUid(uid));
+        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
+        return intent;
+    }
+
+    private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
+            int uid) {
+        Integer id;
+        synchronized(mCredentialsPermissionNotificationIds) {
+            final Pair<Pair<Account, String>, Integer> key =
+                    new Pair<Pair<Account, String>, Integer>(
+                            new Pair<Account, String>(account, authTokenType), uid);
+            id = mCredentialsPermissionNotificationIds.get(key);
+            if (id == null) {
+                id = mNotificationIds.incrementAndGet();
+                mCredentialsPermissionNotificationIds.put(key, id);
+            }
+        }
+        return id;
+    }
+
+    private Integer getSigninRequiredNotificationId(Account account) {
+        Integer id;
+        synchronized(mSigninRequiredNotificationIds) {
+            id = mSigninRequiredNotificationIds.get(account);
+            if (id == null) {
+                id = mNotificationIds.incrementAndGet();
+                mSigninRequiredNotificationIds.put(account, id);
+            }
+        }
+        return id;
+    }
+
+
+    public void addAcount(final IAccountManagerResponse response, final String accountType,
+            final String authTokenType, final String[] requiredFeatures,
+            final boolean expectActivityLaunch, final Bundle options) {
+        checkManageAccountsPermission();
+        long identityToken = clearCallingIdentity();
+        try {
+            new Session(response, accountType, expectActivityLaunch) {
+                public void run() throws RemoteException {
+                    mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures, 
+                            options);
+                }
+
+                protected String toDebugString(long now) {
+                    return super.toDebugString(now) + ", addAccount"
+                            + ", accountType " + accountType
+                            + ", requiredFeatures "
+                            + (requiredFeatures != null
+                              ? TextUtils.join(",", requiredFeatures)
+                              : null);
+                }
+            }.bind();
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public void confirmCredentials(IAccountManagerResponse response,
+            final Account account, final boolean expectActivityLaunch) {
+        checkManageAccountsPermission();
+        long identityToken = clearCallingIdentity();
+        try {
+            new Session(response, account.mType, expectActivityLaunch) {
+                public void run() throws RemoteException {
+                    mAuthenticator.confirmCredentials(this, account);
+                }
+                protected String toDebugString(long now) {
+                    return super.toDebugString(now) + ", confirmCredentials"
+                            + ", " + account;
+                }
+            }.bind();
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public void confirmPassword(IAccountManagerResponse response, final Account account,
+            final String password) {
+        checkManageAccountsPermission();
+        long identityToken = clearCallingIdentity();
+        try {
+            new Session(response, account.mType, false /* expectActivityLaunch */) {
+                public void run() throws RemoteException {
+                    mAuthenticator.confirmPassword(this, account, password);
+                }
+                protected String toDebugString(long now) {
+                    return super.toDebugString(now) + ", confirmPassword"
+                            + ", " + account;
+                }
+            }.bind();
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public void updateCredentials(IAccountManagerResponse response, final Account account,
+            final String authTokenType, final boolean expectActivityLaunch,
+            final Bundle loginOptions) {
+        checkManageAccountsPermission();
+        long identityToken = clearCallingIdentity();
+        try {
+            new Session(response, account.mType, expectActivityLaunch) {
+                public void run() throws RemoteException {
+                    mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
+                }
+                protected String toDebugString(long now) {
+                    if (loginOptions != null) loginOptions.keySet();
+                    return super.toDebugString(now) + ", updateCredentials"
+                            + ", " + account
+                            + ", authTokenType " + authTokenType
+                            + ", loginOptions " + loginOptions;
+                }
+            }.bind();
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    public void editProperties(IAccountManagerResponse response, final String accountType,
+            final boolean expectActivityLaunch) {
+        checkManageAccountsPermission();
+        long identityToken = clearCallingIdentity();
+        try {
+            new Session(response, accountType, expectActivityLaunch) {
+                public void run() throws RemoteException {
+                    mAuthenticator.editProperties(this, mAccountType);
+                }
+                protected String toDebugString(long now) {
+                    return super.toDebugString(now) + ", editProperties"
+                            + ", accountType " + accountType;
+                }
+            }.bind();
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    private class GetAccountsByTypeAndFeatureSession extends Session {
+        private final String[] mFeatures;
+        private volatile Account[] mAccountsOfType = null;
+        private volatile ArrayList<Account> mAccountsWithFeatures = null;
+        private volatile int mCurrentAccount = 0;
+
+        public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
+            String type, String[] features) {
+            super(response, type, false /* expectActivityLaunch */);
+            mFeatures = features;
+        }
+
+        public void run() throws RemoteException {
+            mAccountsOfType = getAccountsByType(mAccountType);
+            // check whether each account matches the requested features
+            mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
+            mCurrentAccount = 0;
+
+            checkAccount();
+        }
+
+        public void checkAccount() {
+            if (mCurrentAccount >= mAccountsOfType.length) {
+                sendResult();
+                return;
+            }
+
+            try {
+                mAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
+            } catch (RemoteException e) {
+                onError(Constants.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
+            }
+        }
+
+        public void onResult(Bundle result) {
+            mNumResults++;
+            if (result == null) {
+                onError(Constants.ERROR_CODE_INVALID_RESPONSE, "null bundle");
+                return;
+            }
+            if (result.getBoolean(Constants.BOOLEAN_RESULT_KEY, false)) {
+                mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
+            }
+            mCurrentAccount++;
+            checkAccount();
+        }
+
+        public void sendResult() {
+            IAccountManagerResponse response = getResponseAndClose();
+            if (response != null) {
+                try {
+                    Account[] accounts = new Account[mAccountsWithFeatures.size()];
+                    for (int i = 0; i < accounts.length; i++) {
+                        accounts[i] = mAccountsWithFeatures.get(i);
+                    }
+                    Bundle result = new Bundle();
+                    result.putParcelableArray(Constants.ACCOUNTS_KEY, accounts);
+                    response.onResult(result);
+                } catch (RemoteException e) {
+                    // if the caller is dead then there is no one to care about remote exceptions
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "failure while notifying response", e);
+                    }
+                }
+            }
+        }
+
+
+        protected String toDebugString(long now) {
+            return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
+                    + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
+        }
+    }
+    public void getAccountsByTypeAndFeatures(IAccountManagerResponse response,
+            String type, String[] features) {
+        checkReadAccountsPermission();
+        if (type == null) {
+            if (response != null) {
+                try {
+                    response.onError(Constants.ERROR_CODE_BAD_ARGUMENTS, "type is null");
+                } catch (RemoteException e) {
+                    // ignore this
+                }
+            }
+            return;
+        }
+        long identityToken = clearCallingIdentity();
+        try {
+            new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    private boolean cacheAuthToken(Account account, String authTokenType, String authToken) {
+        return saveAuthTokenToDatabase(account, authTokenType, authToken);
+    }
+
+    private long getAccountId(SQLiteDatabase db, Account account) {
+        Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
+                "name=? AND type=?", new String[]{account.mName, account.mType}, null, null, null);
+        try {
+            if (cursor.moveToNext()) {
+                return cursor.getLong(0);
+            }
+            return -1;
+        } finally {
+            cursor.close();
+        }
+    }
+
+    private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
+        Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
+                EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
+                new String[]{key}, null, null, null);
+        try {
+            if (cursor.moveToNext()) {
+                return cursor.getLong(0);
+            }
+            return -1;
+        } finally {
+            cursor.close();
+        }
+    }
+
+    private String getAuthToken(SQLiteDatabase db, long accountId, String authTokenType) {
+        Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
+                AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
+                new String[]{authTokenType},
+                null, null, null);
+        try {
+            if (cursor.moveToNext()) {
+                return cursor.getString(0);
+            }
+            return null;
+        } finally {
+            cursor.close();
+        }
+    }
+
+    private abstract class Session extends IAccountAuthenticatorResponse.Stub
+            implements AuthenticatorBindHelper.Callback, IBinder.DeathRecipient {
+        IAccountManagerResponse mResponse;
+        final String mAccountType;
+        final boolean mExpectActivityLaunch;
+        final long mCreationTime;
+
+        public int mNumResults = 0;
+        private int mNumRequestContinued = 0;
+        private int mNumErrors = 0;
+
+
+        IAccountAuthenticator mAuthenticator = null;
+
+        public Session(IAccountManagerResponse response, String accountType,
+                boolean expectActivityLaunch) {
+            super();
+            if (response == null) throw new IllegalArgumentException("response is null");
+            if (accountType == null) throw new IllegalArgumentException("accountType is null");
+            mResponse = response;
+            mAccountType = accountType;
+            mExpectActivityLaunch = expectActivityLaunch;
+            mCreationTime = SystemClock.elapsedRealtime();
+            synchronized (mSessions) {
+                mSessions.put(toString(), this);
+            }
+            try {
+                response.asBinder().linkToDeath(this, 0 /* flags */);
+            } catch (RemoteException e) {
+                mResponse = null;
+                binderDied();
+            }
+        }
+
+        IAccountManagerResponse getResponseAndClose() {
+            if (mResponse == null) {
+                // this session has already been closed
+                return null;
+            }
+            IAccountManagerResponse response = mResponse;
+            close(); // this clears mResponse so we need to save the response before this call
+            return response;
+        }
+
+        private void close() {
+            synchronized (mSessions) {
+                if (mSessions.remove(toString()) == null) {
+                    // the session was already closed, so bail out now
+                    return;
+                }
+            }
+            if (mResponse != null) {
+                // stop listening for response deaths
+                mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
+
+                // clear this so that we don't accidentally send any further results
+                mResponse = null;
+            }
+            cancelTimeout();
+            unbind();
+        }
+
+        public void binderDied() {
+            mResponse = null;
+            close();
+        }
+
+        protected String toDebugString() {
+            return toDebugString(SystemClock.elapsedRealtime());
+        }
+
+        protected String toDebugString(long now) {
+            return "Session: expectLaunch " + mExpectActivityLaunch
+                    + ", connected " + (mAuthenticator != null)
+                    + ", stats (" + mNumResults + "/" + mNumRequestContinued
+                    + "/" + mNumErrors + ")"
+                    + ", lifetime " + ((now - mCreationTime) / 1000.0);
+        }
+
+        void bind() {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
+            }
+            if (!mBindHelper.bind(mAccountType, this)) {
+                Log.d(TAG, "bind attempt failed for " + toDebugString());
+                onError(Constants.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
+            }
+        }
+
+        private void unbind() {
+            if (mAuthenticator != null) {
+                mAuthenticator = null;
+                mBindHelper.unbind(this);
+            }
+        }
+
+        public void scheduleTimeout() {
+            mMessageHandler.sendMessageDelayed(
+                    mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
+        }
+
+        public void cancelTimeout() {
+            mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
+        }
+
+        public void onConnected(IBinder service) {
+            mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
+            try {
+                run();
+            } catch (RemoteException e) {
+                onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
+                        "remote exception");
+            }
+        }
+
+        public abstract void run() throws RemoteException;
+
+        public void onDisconnected() {
+            mAuthenticator = null;
+            IAccountManagerResponse response = getResponseAndClose();
+            if (response != null) {
+                onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
+                        "disconnected");
+            }
+        }
+
+        public void onTimedOut() {
+            IAccountManagerResponse response = getResponseAndClose();
+            if (response != null) {
+                onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
+                        "timeout");
+            }
+        }
+
+        public void onResult(Bundle result) {
+            mNumResults++;
+            if (result != null && !TextUtils.isEmpty(result.getString(Constants.AUTHTOKEN_KEY))) {
+                String accountName = result.getString(Constants.ACCOUNT_NAME_KEY);
+                String accountType = result.getString(Constants.ACCOUNT_TYPE_KEY);
+                if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
+                    Account account = new Account(accountName, accountType);
+                    cancelNotification(getSigninRequiredNotificationId(account));
+                }
+            }
+            IAccountManagerResponse response;
+            if (mExpectActivityLaunch && result != null
+                    && result.containsKey(Constants.INTENT_KEY)) {
+                response = mResponse;
+            } else {
+                response = getResponseAndClose();
+            }
+            if (response != null) {
+                try {
+                    if (result == null) {
+                        response.onError(Constants.ERROR_CODE_INVALID_RESPONSE,
+                                "null bundle returned");
+                    } else {
+                        response.onResult(result);
+                    }
+                } catch (RemoteException e) {
+                    // if the caller is dead then there is no one to care about remote exceptions
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "failure while notifying response", e);
+                    }
+                }
+            }
+        }
+
+        public void onRequestContinued() {
+            mNumRequestContinued++;
+        }
+
+        public void onError(int errorCode, String errorMessage) {
+            mNumErrors++;
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
+            }
+            IAccountManagerResponse response = getResponseAndClose();
+            if (response != null) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "Session.onError: responding");
+                }
+                try {
+                    response.onError(errorCode, errorMessage);
+                } catch (RemoteException e) {
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
+                    }
+                }
+            } else {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "Session.onError: already closed");
+                }
+            }
+        }
+    }
+
+    private class MessageHandler extends Handler {
+        MessageHandler(Looper looper) {
+            super(looper);
+        }
+        
+        public void handleMessage(Message msg) {
+            if (mBindHelper.handleMessage(msg)) {
+                return;
+            }
+            switch (msg.what) {
+                case MESSAGE_TIMED_OUT:
+                    Session session = (Session)msg.obj;
+                    session.onTimedOut();
+                    break;
+
+                default:
+                    throw new IllegalStateException("unhandled message: " + msg.what);
+            }
+        }
+    }
+
+    private class DatabaseHelper extends SQLiteOpenHelper {
+        public DatabaseHelper(Context context) {
+            super(context, DATABASE_NAME, null, DATABASE_VERSION);
+        }
+
+        @Override
+        public void onCreate(SQLiteDatabase db) {
+            db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
+                    + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+                    + ACCOUNTS_NAME + " TEXT NOT NULL, "
+                    + ACCOUNTS_TYPE + " TEXT NOT NULL, "
+                    + ACCOUNTS_PASSWORD + " TEXT, "
+                    + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
+
+            db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " (  "
+                    + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,  "
+                    + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
+                    + AUTHTOKENS_TYPE + " TEXT NOT NULL,  "
+                    + AUTHTOKENS_AUTHTOKEN + " TEXT,  "
+                    + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
+
+            createGrantsTable(db);
+
+            db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
+                    + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+                    + EXTRAS_ACCOUNTS_ID + " INTEGER, "
+                    + EXTRAS_KEY + " TEXT NOT NULL, "
+                    + EXTRAS_VALUE + " TEXT, "
+                    + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
+
+            db.execSQL("CREATE TABLE " + TABLE_META + " ( "
+                    + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
+                    + META_VALUE + " TEXT)");
+
+            createAccountsDeletionTrigger(db);
+        }
+
+        private void createAccountsDeletionTrigger(SQLiteDatabase db) {
+            db.execSQL(""
+                    + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
+                    + " BEGIN"
+                    + "   DELETE FROM " + TABLE_AUTHTOKENS
+                    + "     WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
+                    + "   DELETE FROM " + TABLE_EXTRAS
+                    + "     WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
+                    + "   DELETE FROM " + TABLE_GRANTS
+                    + "     WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
+                    + " END");
+        }
+
+        private void createGrantsTable(SQLiteDatabase db) {
+            db.execSQL("CREATE TABLE " + TABLE_GRANTS + " (  "
+                    + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
+                    + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL,  "
+                    + GRANTS_GRANTEE_UID + " INTEGER NOT NULL,  "
+                    + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
+                    +   "," + GRANTS_GRANTEE_UID + "))");
+        }
+
+        @Override
+        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+            Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
+
+            if (oldVersion == 1) {
+                // no longer need to do anything since the work is done
+                // when upgrading from version 2
+                oldVersion++;
+            }
+
+            if (oldVersion == 2) {
+                createGrantsTable(db);
+                db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
+                createAccountsDeletionTrigger(db);
+                oldVersion++;
+            }
+        }
+
+        @Override
+        public void onOpen(SQLiteDatabase db) {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
+        }
+    }
+
+    private void setMetaValue(String key, String value) {
+        ContentValues values = new ContentValues();
+        values.put(META_KEY, key);
+        values.put(META_VALUE, value);
+        mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
+    }
+
+    private String getMetaValue(String key) {
+        Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
+                new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
+        try {
+            if (c.moveToNext()) {
+                return c.getString(0);
+            }
+            return null;
+        } finally {
+            c.close();
+        }
+    }
+
+    private class SimWatcher extends BroadcastReceiver {
+        public SimWatcher(Context context) {
+            // Re-scan the SIM card when the SIM state changes, and also if
+            // the disk recovers from a full state (we may have failed to handle
+            // things properly while the disk was full).
+            final IntentFilter filter = new IntentFilter();
+            filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
+            filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
+            context.registerReceiver(this, filter);
+        }
+        
+        /**
+         * Compare the IMSI to the one stored in the login service's
+         * database.  If they differ, erase all passwords and
+         * authtokens (and store the new IMSI).
+         */
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            // Check IMSI on every update; nothing happens if the IMSI is missing or unchanged.
+            String imsi = ((TelephonyManager) context.getSystemService(
+                    Context.TELEPHONY_SERVICE)).getSubscriberId();
+            if (TextUtils.isEmpty(imsi)) return;
+
+            String storedImsi = getMetaValue("imsi");
+
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
+            }
+
+            if (!imsi.equals(storedImsi) && !"initial".equals(storedImsi)) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "wiping all passwords and authtokens");
+                }
+                SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+                db.beginTransaction();
+                try {
+                    db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
+                    db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
+                    sendAccountsChangedBroadcast();
+                    db.setTransactionSuccessful();
+                } finally {
+                    db.endTransaction();
+                }
+            }
+            setMetaValue("imsi", imsi);
+        }
+    }
+
+    public IBinder onBind(Intent intent) {
+        return asBinder();
+    }
+
+    protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
+        synchronized (mSessions) {
+            final long now = SystemClock.elapsedRealtime();
+            fout.println("AccountManagerService: " + mSessions.size() + " sessions");
+            for (Session session : mSessions.values()) {
+                fout.println("  " + session.toDebugString(now));
+            }
+        }
+
+        fout.println();
+
+        mAuthenticatorCache.dump(fd, fout, args);
+    }
+
+    private void doNotification(Account account, CharSequence message, Intent intent) {
+        long identityToken = clearCallingIdentity();
+        try {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "doNotification: " + message + " intent:" + intent);
+            }
+
+            if (intent.getComponent() != null &&
+                    GrantCredentialsPermissionActivity.class.getName().equals(
+                            intent.getComponent().getClassName())) {
+                createNoCredentialsPermissionNotification(account, intent);
+            } else {
+                Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
+                        0 /* when */);
+                n.setLatestEventInfo(mContext, mContext.getText(R.string.notification_title),
+                        message, PendingIntent.getActivity(
+                        mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
+                ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
+                        .notify(getSigninRequiredNotificationId(account), n);
+            }
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    private void cancelNotification(int id) {
+        long identityToken = clearCallingIdentity();
+        try {
+            ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
+                .cancel(id);
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+
+    private void checkBinderPermission(String permission) {
+        final int uid = Binder.getCallingUid();
+        if (mContext.checkCallingOrSelfPermission(permission) !=
+                PackageManager.PERMISSION_GRANTED) {
+            String msg = "caller uid " + uid + " lacks " + permission;
+            Log.w(TAG, msg);
+            throw new SecurityException(msg);
+        }
+        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+            Log.v(TAG, "caller uid " + uid + " has " + permission);
+        }
+    }
+
+    private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
+        final boolean fromAuthenticator = hasAuthenticatorUid(account.mType, callerUid);
+        final boolean hasExplicitGrants = hasExplicitlyGrantedPermission(account, authTokenType);
+        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+            Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
+                    + callerUid + ", account " + account
+                    + ": is authenticator? " + fromAuthenticator
+                    + ", has explicit permission? " + hasExplicitGrants);
+        }
+        return fromAuthenticator || hasExplicitGrants;
+    }
+
+    private boolean hasAuthenticatorUid(String accountType, int callingUid) {
+        for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
+                mAuthenticatorCache.getAllServices()) {
+            if (serviceInfo.type.type.equals(accountType)) {
+                return serviceInfo.uid == callingUid;
+            }
+        }
+        return false;
+    }
+
+    private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
+        if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
+            return true;
+        }
+        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
+        String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
+                account.mName, account.mType};
+        final boolean permissionGranted =
+                DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
+        if (!permissionGranted && isDebuggableMonkeyBuild) {
+            // TODO: Skip this check when running automated tests. Replace this
+            // with a more general solution.
+            Log.w(TAG, "no credentials permission for usage of " + account + ", "
+                    + authTokenType + " by uid " + Binder.getCallingUid()
+                    + " but ignoring since this is a monkey build");
+            return true;
+        }
+        return permissionGranted;
+    }
+
+    private void checkCallingUidAgainstAuthenticator(Account account) {
+        final int uid = Binder.getCallingUid();
+        if (!hasAuthenticatorUid(account.mType, uid)) {
+            String msg = "caller uid " + uid + " is different than the authenticator's uid";
+            Log.w(TAG, msg);
+            throw new SecurityException(msg);
+        }
+        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+            Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
+        }
+    }
+
+    private void checkAuthenticateAccountsPermission(Account account) {
+        checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
+        checkCallingUidAgainstAuthenticator(account);
+    }
+
+    private void checkReadAccountsPermission() {
+        checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
+    }
+
+    private void checkManageAccountsPermission() {
+        checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
+    }
+
+    /**
+     * Allow callers with the given uid permission to get credentials for account/authTokenType.
+     * <p>
+     * Although this is public it can only be accessed via the AccountManagerService object
+     * which is in the system. This means we don't need to protect it with permissions.
+     * @hide
+     */
+    public void grantAppPermission(Account account, String authTokenType, int uid) {
+        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+        db.beginTransaction();
+        try {
+            long accountId = getAccountId(db, account);
+            if (accountId >= 0) {
+                ContentValues values = new ContentValues();
+                values.put(GRANTS_ACCOUNTS_ID, accountId);
+                values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
+                values.put(GRANTS_GRANTEE_UID, uid);
+                db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
+                db.setTransactionSuccessful();
+            }
+        } finally {
+            db.endTransaction();
+        }
+        cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
+    }
+
+    /**
+     * Don't allow callers with the given uid permission to get credentials for
+     * account/authTokenType.
+     * <p>
+     * Although this is public it can only be accessed via the AccountManagerService object
+     * which is in the system. This means we don't need to protect it with permissions.
+     * @hide
+     */
+    public void revokeAppPermission(Account account, String authTokenType, int uid) {
+        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+        db.beginTransaction();
+        try {
+            long accountId = getAccountId(db, account);
+            if (accountId >= 0) {
+                db.delete(TABLE_GRANTS,
+                        GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
+                                + GRANTS_GRANTEE_UID + "=?",
+                        new String[]{String.valueOf(accountId), authTokenType,
+                                String.valueOf(uid)});
+                db.setTransactionSuccessful();
+            }
+        } finally {
+            db.endTransaction();
+        }
+        cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
+    }
+}
diff --git a/core/java/android/accounts/AccountMonitor.java b/core/java/android/accounts/AccountMonitor.java
deleted file mode 100644
index f21385e..0000000
--- a/core/java/android/accounts/AccountMonitor.java
+++ /dev/null
@@ -1,174 +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.accounts;
-
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.ServiceConnection;
-import android.database.SQLException;
-import android.os.IBinder;
-import android.os.Process;
-import android.os.RemoteException;
-import android.util.Log;
-
-/**
- * A helper class that calls back on the provided
- * AccountMonitorListener with the set of current accounts both when
- * it gets created and whenever the set changes. It does this by
- * binding to the AccountsService and registering to receive the
- * intent broadcast when the set of accounts is changed.  The
- * connection to the accounts service is only made when it needs to
- * fetch the current list of accounts (that is, when the
- * AccountMonitor is first created, and when the intent is received).
- */
-public class AccountMonitor extends BroadcastReceiver implements ServiceConnection {
-    private final Context mContext;
-    private final AccountMonitorListener mListener;
-    private boolean mClosed = false;
-    private int pending = 0;
-
-    // This thread runs in the background and runs the code to update accounts
-    // in the listener.
-    private class AccountUpdater extends Thread {
-        private IBinder mService;
-
-        public AccountUpdater(IBinder service) {
-            mService = service;
-        }
-
-        @Override
-        public void run() {
-            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
-            IAccountsService accountsService = IAccountsService.Stub.asInterface(mService);
-            String[] accounts = null;
-            do {
-                try {
-                    accounts = accountsService.getAccounts();
-                } catch (RemoteException e) {
-                    // if the service was killed then the system will restart it and when it does we
-                    // will get another onServiceConnected, at which point we will do a notify.
-                    Log.w("AccountMonitor", "Remote exception when getting accounts", e);
-                    return;
-                }
-
-                synchronized (AccountMonitor.this) {
-                    --pending;
-                    if (pending == 0) {
-                        break;
-                    }
-                }
-            } while (true);
-
-            mContext.unbindService(AccountMonitor.this);
-
-            try {
-                mListener.onAccountsUpdated(accounts);
-            } catch (SQLException e) {
-                // Better luck next time.  If the problem was disk-full,
-                // the STORAGE_OK intent will re-trigger the update.
-                Log.e("AccountMonitor", "Can't update accounts", e);
-            }
-        }
-    }
-
-    /**
-     * Initializes the AccountMonitor and initiates a bind to the
-     * AccountsService to get the initial account list.  For 1.0,
-     * the "list" is always a single account.
-     *
-     * @param context the context we are running in
-     * @param listener the user to notify when the account set changes
-     */
-    public AccountMonitor(Context context, AccountMonitorListener listener) {
-        if (listener == null) {
-            throw new IllegalArgumentException("listener is null");
-        }
-
-        mContext = context;
-        mListener = listener;
-
-        // Register a broadcast receiver to monitor account changes
-        IntentFilter intentFilter = new IntentFilter();
-        intentFilter.addAction(AccountsServiceConstants.LOGIN_ACCOUNTS_CHANGED_ACTION);
-        intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);  // To recover from disk-full.
-        mContext.registerReceiver(this, intentFilter);
-
-        // Send the listener the initial state now.
-        notifyListener();
-    }
-
-    @Override
-    public void onReceive(Context context, Intent intent) {
-        notifyListener();
-    }
-
-    public void onServiceConnected(ComponentName className, IBinder service) {
-        // Create a background thread to update the accounts.
-        new AccountUpdater(service).start();
-    }
-
-    public void onServiceDisconnected(ComponentName className) {
-    }
-
-    private synchronized void notifyListener() {
-        if (pending == 0) {
-            // initiate the bind
-            if (!mContext.bindService(AccountsServiceConstants.SERVICE_INTENT,
-                                      this, Context.BIND_AUTO_CREATE)) {
-                // This is normal if GLS isn't part of this build.
-                Log.w("AccountMonitor",
-                      "Couldn't connect to "  +
-                      AccountsServiceConstants.SERVICE_INTENT +
-                      " (Missing service?)");
-            }
-        } else {
-            // already bound.  bindService will not trigger another
-            // call to onServiceConnected, so instead we make sure
-            // that the existing background thread will call
-            // getAccounts() after this function returns, by
-            // incrementing pending.
-            //
-            // Yes, this else clause contains only a comment.
-        }
-        ++pending;
-    }
-
-    /**
-     * calls close()
-     * @throws Throwable
-     */
-    @Override
-    protected void finalize() throws Throwable {
-        close();
-        super.finalize();
-    }
-
-    /**
-     * Unregisters the account receiver.  Consecutive calls to this
-     * method are harmless, but also do nothing.  Once this call is
-     * made no more notifications will occur.
-     */
-    public synchronized void close() {
-        if (!mClosed) {
-            mContext.unregisterReceiver(this);
-            mClosed = true;
-        }
-    }
-}
diff --git a/core/java/android/accounts/AccountsServiceConstants.java b/core/java/android/accounts/AccountsServiceConstants.java
deleted file mode 100644
index b882e7b..0000000
--- a/core/java/android/accounts/AccountsServiceConstants.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2008 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.accounts;
-
-import android.content.Intent;
-
-/**
- * Miscellaneous constants used by the AccountsService and its
- * clients.
- */
-// TODO: These constants *could* come directly from the
-// IAccountsService interface, but that's not possible since the
-// aidl compiler doesn't let you define constants (yet.)
-public class AccountsServiceConstants {
-    /** This class is never instantiated. */
-    private AccountsServiceConstants() {
-    }
-
-    /**
-     * Action sent as a broadcast Intent by the AccountsService
-     * when accounts are added to and/or removed from the device's
-     * database, or when the primary account is changed.
-     */
-    public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
-        "android.accounts.LOGIN_ACCOUNTS_CHANGED";
-
-    /**
-     * Action sent as a broadcast Intent by the AccountsService
-     * when it starts up and no accounts are available (so some should be added).
-     */
-    public static final String LOGIN_ACCOUNTS_MISSING_ACTION =
-        "android.accounts.LOGIN_ACCOUNTS_MISSING";
-
-    /**
-     * Action on the intent used to bind to the IAccountsService interface. This
-     * is used for services that have multiple interfaces (allowing
-     * them to differentiate the interface intended, and return the proper
-     * Binder.)
-     */
-    private static final String ACCOUNTS_SERVICE_ACTION = "android.accounts.IAccountsService";
-
-    /*
-     * The intent uses a component in addition to the action to ensure the actual
-     * accounts service is bound to (a malicious third-party app could
-     * theoretically have a service with the same action).
-     */
-    /** The intent used to bind to the accounts service. */
-    public static final Intent SERVICE_INTENT =
-        new Intent()
-            .setClassName("com.google.android.googleapps",
-                    "com.google.android.googleapps.GoogleLoginService")
-            .setAction(ACCOUNTS_SERVICE_ACTION);
-
-    /**
-     * Checks whether the intent is to bind to the accounts service.
-     * 
-     * @param bindIntent The Intent used to bind to the service. 
-     * @return Whether the intent is to bind to the accounts service.
-     */
-    public static final boolean isForAccountsService(Intent bindIntent) {
-        String otherAction = bindIntent.getAction();
-        return otherAction != null && otherAction.equals(ACCOUNTS_SERVICE_ACTION);
-    }
-}
diff --git a/core/java/android/accounts/AuthenticatorBindHelper.java b/core/java/android/accounts/AuthenticatorBindHelper.java
new file mode 100644
index 0000000..91e23ab
--- /dev/null
+++ b/core/java/android/accounts/AuthenticatorBindHelper.java
@@ -0,0 +1,252 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Message;
+import android.util.Log;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import com.google.android.collect.Lists;
+import com.google.android.collect.Maps;
+
+/**
+ * A helper object that simplifies binding to Account Authenticators. It uses the
+ * {@link AccountAuthenticatorCache} to find the component name of the authenticators,
+ * allowing the user to bind by account name. It also allows multiple, simultaneous binds
+ * to the same authenticator, with each bind call guaranteed to return either
+ * {@link Callback#onConnected} or {@link Callback#onDisconnected} if the bind() call
+ * itself succeeds, even if the authenticator is already bound internally.
+ * @hide
+ */
+public class AuthenticatorBindHelper {
+    private static final String TAG = "Accounts";
+    private final Handler mHandler;
+    private final Context mContext;
+    private final int mMessageWhatConnected;
+    private final int mMessageWhatDisconnected;
+    private final Map<String, MyServiceConnection> mServiceConnections = Maps.newHashMap();
+    private final Map<String, ArrayList<Callback>> mServiceUsers = Maps.newHashMap();
+    private final AccountAuthenticatorCache mAuthenticatorCache;
+
+    public AuthenticatorBindHelper(Context context,
+            AccountAuthenticatorCache authenticatorCache, Handler handler,
+            int messageWhatConnected, int messageWhatDisconnected) {
+        mContext = context;
+        mHandler = handler;
+        mAuthenticatorCache = authenticatorCache;
+        mMessageWhatConnected = messageWhatConnected;
+        mMessageWhatDisconnected = messageWhatDisconnected;
+    }
+
+    public interface Callback {
+        void onConnected(IBinder service);
+        void onDisconnected();
+    }
+
+    public boolean bind(String authenticatorType, Callback callback) {
+        // if the authenticator is connecting or connected then return true
+        synchronized (mServiceConnections) {
+            if (mServiceConnections.containsKey(authenticatorType)) {
+                MyServiceConnection connection = mServiceConnections.get(authenticatorType);
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "service connection already exists for " + authenticatorType);
+                }
+                mServiceUsers.get(authenticatorType).add(callback);
+                if (connection.mService != null) {
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "the service is connected, scheduling a connected message for "
+                                + authenticatorType);
+                    }
+                    connection.scheduleCallbackConnectedMessage(callback);
+                } else {
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "the service is *not* connected, waiting for for "
+                                + authenticatorType);
+                    }
+                }
+                return true;
+            }
+
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "there is no service connection for " + authenticatorType);
+            }
+
+            // otherwise find the component name for the authenticator and initiate a bind
+            // if no authenticator or the bind fails then return false, otherwise return true
+            AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
+                    mAuthenticatorCache.getServiceInfo(
+                            AuthenticatorDescription.newKey(authenticatorType));
+            if (authenticatorInfo == null) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "there is no authenticator for " + authenticatorType
+                            + ", bailing out");
+                }
+                return false;
+            }
+
+            MyServiceConnection connection = new MyServiceConnection(authenticatorType);
+
+            Intent intent = new Intent();
+            intent.setAction("android.accounts.AccountAuthenticator");
+            intent.setComponent(authenticatorInfo.componentName);
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
+            }
+            if (!mContext.bindService(intent, connection, Context.BIND_AUTO_CREATE)) {
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
+                }
+                return false;
+            }
+
+            mServiceConnections.put(authenticatorType, connection);
+            mServiceUsers.put(authenticatorType, Lists.newArrayList(callback));
+            return true;
+        }
+    }
+
+    public void unbind(Callback callbackToUnbind) {
+        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+            Log.v(TAG, "unbinding callback " + callbackToUnbind);
+        }
+        synchronized (mServiceConnections) {
+            for (Map.Entry<String, ArrayList<Callback>> entry : mServiceUsers.entrySet()) {
+                final String authenticatorType = entry.getKey();
+                final ArrayList<Callback> serviceUsers = entry.getValue();
+                for (Callback callback : serviceUsers) {
+                    if (callback == callbackToUnbind) {
+                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                            Log.v(TAG, "found callback in service" + authenticatorType);
+                        }
+                        serviceUsers.remove(callbackToUnbind);
+                        if (serviceUsers.isEmpty()) {
+                            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                                Log.v(TAG, "there are no more callbacks for service "
+                                        + authenticatorType + ", unbinding service");
+                            }
+                            unbindFromService(authenticatorType);
+                        } else {
+                            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                                Log.v(TAG, "leaving service " + authenticatorType
+                                        + " around since there are still callbacks using it");
+                            }
+                        }
+                        return;
+                    }
+                }
+            }
+            Log.e(TAG, "did not find callback " + callbackToUnbind + " in any of the services");
+        }
+    }
+
+    private void unbindFromService(String authenticatorType) {
+        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+            Log.v(TAG, "unbindService from " + authenticatorType);
+        }
+        mContext.unbindService(mServiceConnections.get(authenticatorType));
+        mServiceUsers.remove(authenticatorType);
+        mServiceConnections.remove(authenticatorType);
+    }
+
+    private class ConnectedMessagePayload {
+        public final IBinder mService;
+        public final Callback mCallback;
+        public ConnectedMessagePayload(IBinder service, Callback callback) {
+            mService = service;
+            mCallback = callback;
+        }
+    }
+
+    private class MyServiceConnection implements ServiceConnection {
+        private final String mAuthenticatorType;
+        private IBinder mService = null;
+
+        public MyServiceConnection(String authenticatorType) {
+            mAuthenticatorType = authenticatorType;
+        }
+
+        public void onServiceConnected(ComponentName name, IBinder service) {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "onServiceConnected for account type " + mAuthenticatorType);
+            }
+            // post a message for each service user to tell them that the service is connected
+            synchronized (mServiceConnections) {
+                mService = service;
+                for (Callback callback : mServiceUsers.get(mAuthenticatorType)) {
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "the service became connected, scheduling a connected "
+                                + "message for " + mAuthenticatorType);
+                    }
+                    scheduleCallbackConnectedMessage(callback);
+                }
+            }
+        }
+
+        private void scheduleCallbackConnectedMessage(Callback callback) {
+            final ConnectedMessagePayload payload =
+                    new ConnectedMessagePayload(mService, callback);
+            mHandler.obtainMessage(mMessageWhatConnected, payload).sendToTarget();
+        }
+
+        public void onServiceDisconnected(ComponentName name) {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "onServiceDisconnected for account type " + mAuthenticatorType);
+            }
+            // post a message for each service user to tell them that the service is disconnected,
+            // and unbind from the service.
+            synchronized (mServiceConnections) {
+                for (Callback callback : mServiceUsers.get(mAuthenticatorType)) {
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "the service became disconnected, scheduling a "
+                                + "disconnected message for "
+                                + mAuthenticatorType);
+                    }
+                    mHandler.obtainMessage(mMessageWhatDisconnected, callback).sendToTarget();
+                }
+                unbindFromService(mAuthenticatorType);
+            }
+        }
+    }
+
+    boolean handleMessage(Message message) {
+        if (message.what == mMessageWhatConnected) {
+            ConnectedMessagePayload payload = (ConnectedMessagePayload)message.obj;
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "notifying callback " + payload.mCallback + " that it is connected");
+            }
+            payload.mCallback.onConnected(payload.mService);
+            return true;
+        } else if (message.what == mMessageWhatDisconnected) {
+            Callback callback = (Callback)message.obj;
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "notifying callback " + callback + " that it is disconnected");
+            }
+            callback.onDisconnected();
+            return true;
+        } else {
+            return false;
+        }
+    }
+}
diff --git a/include/utils/executablepath.h b/core/java/android/accounts/AuthenticatorDescription.aidl
similarity index 65%
copy from include/utils/executablepath.h
copy to core/java/android/accounts/AuthenticatorDescription.aidl
index c979432..136361c 100644
--- a/include/utils/executablepath.h
+++ b/core/java/android/accounts/AuthenticatorDescription.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,15 +14,6 @@
  * limitations under the License.
  */
 
-#ifndef _UTILS_EXECUTABLEPATH_H
-#define _UTILS_EXECUTABLEPATH_H
+package android.accounts;
 
-#include <limits.h>
-
-// returns the path to this executable
-#if __cplusplus
-extern "C"
-#endif
-void executablepath(char s[PATH_MAX]);
-
-#endif // _UTILS_EXECUTABLEPATH_H
+parcelable AuthenticatorDescription;
diff --git a/core/java/android/accounts/AuthenticatorDescription.java b/core/java/android/accounts/AuthenticatorDescription.java
new file mode 100644
index 0000000..f896bf8
--- /dev/null
+++ b/core/java/android/accounts/AuthenticatorDescription.java
@@ -0,0 +1,69 @@
+package android.accounts;
+
+import android.os.Parcelable;
+import android.os.Parcel;
+
+public class AuthenticatorDescription implements Parcelable {
+    final public String type;
+    final public int labelId;
+    final public int iconId;
+    final public String packageName;
+
+    public AuthenticatorDescription(String type, String packageName, int labelId, int iconId) {
+        this.type = type;
+        this.packageName = packageName;
+        this.labelId = labelId;
+        this.iconId = iconId;
+    }
+
+    public static AuthenticatorDescription newKey(String type) {
+        return new AuthenticatorDescription(type);
+    }
+
+    private AuthenticatorDescription(String type) {
+        this.type = type;
+        this.packageName = null;
+        this.labelId = 0;
+        this.iconId = 0;
+    }
+
+    private AuthenticatorDescription(Parcel source) {
+        this.type = source.readString();
+        this.packageName = source.readString();
+        this.labelId = source.readInt();
+        this.iconId = source.readInt();
+    }
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public int hashCode() {
+        return type.hashCode();
+    }
+
+    public boolean equals(Object o) {
+        if (o == this) return true;
+        if (!(o instanceof AuthenticatorDescription)) return false;
+        final AuthenticatorDescription other = (AuthenticatorDescription) o;
+        return type.equals(other.type);
+    }
+
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeString(type);
+        dest.writeString(packageName);
+        dest.writeInt(labelId);
+        dest.writeInt(iconId);
+    }
+
+    public static final Creator<AuthenticatorDescription> CREATOR =
+            new Creator<AuthenticatorDescription>() {
+        public AuthenticatorDescription createFromParcel(Parcel source) {
+            return new AuthenticatorDescription(source);
+        }
+
+        public AuthenticatorDescription[] newArray(int size) {
+            return new AuthenticatorDescription[size];
+        }
+    };
+}
diff --git a/core/java/android/accounts/AuthenticatorException.java b/core/java/android/accounts/AuthenticatorException.java
new file mode 100644
index 0000000..4023494
--- /dev/null
+++ b/core/java/android/accounts/AuthenticatorException.java
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+public class AuthenticatorException extends Exception {
+    public AuthenticatorException() {
+        super();
+    }
+    public AuthenticatorException(String message) {
+        super(message);
+    }
+    public AuthenticatorException(String message, Throwable cause) {
+        super(message, cause);
+    }
+    public AuthenticatorException(Throwable cause) {
+        super(cause);
+    }
+}
diff --git a/core/java/android/accounts/ChooseAccountActivity.java b/core/java/android/accounts/ChooseAccountActivity.java
new file mode 100644
index 0000000..83377f3
--- /dev/null
+++ b/core/java/android/accounts/ChooseAccountActivity.java
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+package android.accounts;
+
+import android.app.ListActivity;
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+import android.view.View;
+import android.util.Log;
+
+public class ChooseAccountActivity extends ListActivity {
+    private static final String TAG = "AccountManager";
+    private Parcelable[] mAccounts = null;
+    private AccountManagerResponse mAccountManagerResponse = null;
+    private Bundle mResult;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        if (savedInstanceState == null) {
+            mAccounts = getIntent().getParcelableArrayExtra(Constants.ACCOUNTS_KEY);
+            mAccountManagerResponse =
+                    getIntent().getParcelableExtra(Constants.ACCOUNT_MANAGER_RESPONSE_KEY);
+        } else {
+            mAccounts = savedInstanceState.getParcelableArray(Constants.ACCOUNTS_KEY);
+            mAccountManagerResponse =
+                    savedInstanceState.getParcelable(Constants.ACCOUNT_MANAGER_RESPONSE_KEY);
+        }
+
+        String[] mAccountNames = new String[mAccounts.length];
+        for (int i = 0; i < mAccounts.length; i++) {
+            mAccountNames[i] = ((Account) mAccounts[i]).mName;
+        }
+
+        // Use an existing ListAdapter that will map an array
+        // of strings to TextViews
+        setListAdapter(new ArrayAdapter<String>(this,
+                android.R.layout.simple_list_item_1, mAccountNames));
+        getListView().setTextFilterEnabled(true);
+    }
+
+    protected void onListItemClick(ListView l, View v, int position, long id) {
+        Account account = (Account) mAccounts[position];
+        Log.d(TAG, "selected account " + account);
+        Bundle bundle = new Bundle();
+        bundle.putString(Constants.ACCOUNT_NAME_KEY, account.mName);
+        bundle.putString(Constants.ACCOUNT_TYPE_KEY, account.mType);
+        mResult = bundle;
+        finish();
+    }
+
+    public void finish() {
+        if (mAccountManagerResponse != null) {
+            if (mResult != null) {
+                mAccountManagerResponse.onResult(mResult);
+            } else {
+                mAccountManagerResponse.onError(Constants.ERROR_CODE_CANCELED, "canceled");
+            }
+        }
+        super.finish();
+    }
+}
diff --git a/core/java/android/accounts/Constants.java b/core/java/android/accounts/Constants.java
new file mode 100644
index 0000000..da8173f
--- /dev/null
+++ b/core/java/android/accounts/Constants.java
@@ -0,0 +1,58 @@
+/*
+ * 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.
+ */
+package android.accounts;
+
+public class Constants {
+    // this should never be instantiated
+    private Constants() {}
+
+    public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
+    public static final int ERROR_CODE_NETWORK_ERROR = 3;
+    public static final int ERROR_CODE_CANCELED = 4;
+    public static final int ERROR_CODE_INVALID_RESPONSE = 5;
+    public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
+    public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
+    public static final int ERROR_CODE_BAD_REQUEST = 8;
+
+    public static final String ACCOUNTS_KEY = "accounts";
+    public static final String AUTHENTICATOR_TYPES_KEY = "authenticator_types";
+    public static final String USERDATA_KEY = "userdata";
+    public static final String AUTHTOKEN_KEY = "authtoken";
+    public static final String ACCOUNT_NAME_KEY = "authAccount";
+    public static final String ACCOUNT_TYPE_KEY = "accountType";
+    public static final String ERROR_CODE_KEY = "errorCode";
+    public static final String ERROR_MESSAGE_KEY = "errorMessage";
+    public static final String INTENT_KEY = "intent";
+    public static final String BOOLEAN_RESULT_KEY = "booleanResult";
+    public static final String ACCOUNT_AUTHENTICATOR_RESPONSE_KEY = "accountAuthenticatorResponse";
+    public static final String ACCOUNT_MANAGER_RESPONSE_KEY = "accountManagerResponse";
+    public static final String AUTH_FAILED_MESSAGE_KEY = "authFailedMessage";
+    public static final String AUTH_TOKEN_LABEL_KEY = "authTokenLabelKey";
+
+    public static final String AUTHENTICATOR_INTENT_ACTION =
+            "android.accounts.AccountAuthenticator";
+    public static final String AUTHENTICATOR_META_DATA_NAME =
+            "android.accounts.AccountAuthenticator";
+    public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
+
+    /**
+     * Action sent as a broadcast Intent by the AccountsService
+     * when accounts are added to and/or removed from the device's
+     * database, or when the primary account is changed.
+     */
+    public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
+        "android.accounts.LOGIN_ACCOUNTS_CHANGED";
+}
diff --git a/core/java/android/accounts/Future1.java b/core/java/android/accounts/Future1.java
new file mode 100644
index 0000000..386cb6e
--- /dev/null
+++ b/core/java/android/accounts/Future1.java
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+package android.accounts;
+
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * An extension of {@link Future} that provides wrappers for {@link #get()} that handle the various
+ * exceptions that  {@link #get()} may return and rethrows them as exceptions specific to
+ * {@link AccountManager}.
+ */
+public interface Future1<V> extends Future<V> {
+    /**
+     * Wrapper for {@link Future#get()}. If the get() throws {@link InterruptedException} then the
+     * {@link Future1} is canceled and {@link OperationCanceledException} is thrown.
+     * @return the {@link android.os.Bundle} that is returned by get()
+     * @throws OperationCanceledException if get() throws the unchecked CancellationException
+     * or if the Future was interrupted.
+     */
+    V getResult() throws OperationCanceledException;
+
+    /**
+     * Wrapper for {@link Future#get()}. If the get() throws {@link InterruptedException} then the
+     * {@link Future1} is canceled and {@link OperationCanceledException} is thrown.
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the timeout argument
+     * @return the {@link android.os.Bundle} that is returned by {@link Future#get()}
+     * @throws OperationCanceledException if get() throws the unchecked
+     * {@link java.util.concurrent.CancellationException} or if the {@link Future1} was interrupted.
+     */
+    V getResult(long timeout, TimeUnit unit) throws OperationCanceledException;
+}
\ No newline at end of file
diff --git a/include/utils/executablepath.h b/core/java/android/accounts/Future1Callback.java
similarity index 65%
copy from include/utils/executablepath.h
copy to core/java/android/accounts/Future1Callback.java
index c979432..886671b 100644
--- a/include/utils/executablepath.h
+++ b/core/java/android/accounts/Future1Callback.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -13,16 +13,8 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+package android.accounts;
 
-#ifndef _UTILS_EXECUTABLEPATH_H
-#define _UTILS_EXECUTABLEPATH_H
-
-#include <limits.h>
-
-// returns the path to this executable
-#if __cplusplus
-extern "C"
-#endif
-void executablepath(char s[PATH_MAX]);
-
-#endif // _UTILS_EXECUTABLEPATH_H
+public interface Future1Callback<V> {
+    void run(Future1<V> future);
+}
diff --git a/core/java/android/accounts/Future2.java b/core/java/android/accounts/Future2.java
new file mode 100644
index 0000000..b2ea84f
--- /dev/null
+++ b/core/java/android/accounts/Future2.java
@@ -0,0 +1,57 @@
+/*
+ * 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.
+ */
+package android.accounts;
+
+import android.os.Bundle;
+
+import java.io.IOException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * An extension of {@link Future} that provides wrappers for {@link #get()} that handle the various
+ * exceptions that  {@link #get()} may return and rethrows them as exceptions specific to
+ * {@link AccountManager}.
+ */
+public interface Future2 extends Future<Bundle> {
+    /**
+     * Wrapper for {@link Future#get()}. If the get() throws {@link InterruptedException} then the
+     * {@link Future2} is canceled and {@link OperationCanceledException} is thrown.
+     * @return the {@link android.os.Bundle} that is returned by {@link Future#get()}
+     * @throws OperationCanceledException if get() throws the unchecked
+     * {@link java.util.concurrent.CancellationException} or if the {@link Future2} was interrupted.
+     * @throws IOException if the request was unable to complete due to a network error
+     * @throws AuthenticatorException if there was an error communicating with the
+     * {@link AbstractAccountAuthenticator}.
+     */
+    Bundle getResult()
+            throws OperationCanceledException, IOException, AuthenticatorException;
+
+    /**
+     * Wrapper for {@link Future#get()}. If the get() throws {@link InterruptedException} then the
+     * {@link Future2} is canceled and {@link OperationCanceledException} is thrown.
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the timeout argument
+     * @return the {@link android.os.Bundle} that is returned by {@link Future#get()}
+     * @throws OperationCanceledException if get() throws the unchecked
+     * {@link java.util.concurrent.CancellationException} or if the {@link Future2} was interrupted.
+     * @throws IOException if the request was unable to complete due to a network error
+     * @throws AuthenticatorException if there was an error communicating with the
+     * {@link AbstractAccountAuthenticator}.
+     */
+    Bundle getResult(long timeout, TimeUnit unit)
+            throws OperationCanceledException, IOException, AuthenticatorException;
+}
diff --git a/include/utils/executablepath.h b/core/java/android/accounts/Future2Callback.java
similarity index 65%
copy from include/utils/executablepath.h
copy to core/java/android/accounts/Future2Callback.java
index c979432..7ef0c94 100644
--- a/include/utils/executablepath.h
+++ b/core/java/android/accounts/Future2Callback.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -13,16 +13,8 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+package android.accounts;
 
-#ifndef _UTILS_EXECUTABLEPATH_H
-#define _UTILS_EXECUTABLEPATH_H
-
-#include <limits.h>
-
-// returns the path to this executable
-#if __cplusplus
-extern "C"
-#endif
-void executablepath(char s[PATH_MAX]);
-
-#endif // _UTILS_EXECUTABLEPATH_H
+public interface Future2Callback {
+    void run(Future2 future);
+}
\ No newline at end of file
diff --git a/core/java/android/accounts/GrantCredentialsPermissionActivity.java b/core/java/android/accounts/GrantCredentialsPermissionActivity.java
new file mode 100644
index 0000000..f92d43f
--- /dev/null
+++ b/core/java/android/accounts/GrantCredentialsPermissionActivity.java
@@ -0,0 +1,172 @@
+/*
+ * 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.
+ */
+package android.accounts;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.widget.TextView;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+import android.view.View;
+import android.view.LayoutInflater;
+import android.view.ViewGroup;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import com.android.internal.R;
+
+/**
+ * @hide
+ */
+public class GrantCredentialsPermissionActivity extends Activity implements View.OnClickListener {
+    public static final String EXTRAS_ACCOUNT = "account";
+    public static final String EXTRAS_AUTH_TOKEN_LABEL = "authTokenLabel";
+    public static final String EXTRAS_AUTH_TOKEN_TYPE = "authTokenType";
+    public static final String EXTRAS_RESPONSE = "response";
+    public static final String EXTRAS_ACCOUNT_TYPE_LABEL = "accountTypeLabel";
+    public static final String EXTRAS_PACKAGES = "application";
+    public static final String EXTRAS_REQUESTING_UID = "uid";
+    private Account mAccount;
+    private String mAuthTokenType;
+    private int mUid;
+    private Bundle mResultBundle = null;
+
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        getWindow().setContentView(R.layout.grant_credentials_permission);
+        mAccount = getIntent().getExtras().getParcelable(EXTRAS_ACCOUNT);
+        mAuthTokenType = getIntent().getExtras().getString(EXTRAS_AUTH_TOKEN_TYPE);
+        mUid = getIntent().getExtras().getInt(EXTRAS_REQUESTING_UID);
+        final String accountTypeLabel =
+                getIntent().getExtras().getString(EXTRAS_ACCOUNT_TYPE_LABEL);
+        final String[] packages = getIntent().getExtras().getStringArray(EXTRAS_PACKAGES);
+
+        findViewById(R.id.allow).setOnClickListener(this);
+        findViewById(R.id.deny).setOnClickListener(this);
+
+        TextView messageView = (TextView) getWindow().findViewById(R.id.message);
+        String authTokenLabel = getIntent().getExtras().getString(EXTRAS_AUTH_TOKEN_LABEL);
+        if (authTokenLabel.length() == 0) {
+            CharSequence grantCredentialsPermissionFormat = getResources().getText(
+                    R.string.grant_credentials_permission_message_desc);
+            messageView.setText(String.format(grantCredentialsPermissionFormat.toString(),
+                    mAccount.mName, accountTypeLabel));
+        } else {
+            CharSequence grantCredentialsPermissionFormat = getResources().getText(
+                    R.string.grant_credentials_permission_message_with_authtokenlabel_desc);
+            messageView.setText(String.format(grantCredentialsPermissionFormat.toString(),
+                    authTokenLabel, mAccount.mName, accountTypeLabel));
+        }
+
+        String[] packageLabels = new String[packages.length];
+        final PackageManager pm = getPackageManager();
+        for (int i = 0; i < packages.length; i++) {
+            try {
+                packageLabels[i] =
+                        pm.getApplicationLabel(pm.getApplicationInfo(packages[i], 0)).toString();
+            } catch (PackageManager.NameNotFoundException e) {
+                packageLabels[i] = packages[i];
+            }
+        }
+        ((ListView) findViewById(R.id.packages_list)).setAdapter(
+                new PackagesArrayAdapter(this, packageLabels));
+    }
+
+    public void onClick(View v) {
+        switch (v.getId()) {
+            case R.id.allow:
+                AccountManagerService.getSingleton().grantAppPermission(mAccount, mAuthTokenType,
+                        mUid);
+                Intent result = new Intent();
+                result.putExtra("retry", true);
+                setResult(RESULT_OK, result);
+                setAccountAuthenticatorResult(result.getExtras());
+                break;
+
+            case R.id.deny:
+                AccountManagerService.getSingleton().revokeAppPermission(mAccount, mAuthTokenType,
+                        mUid);
+                setResult(RESULT_CANCELED);
+                break;
+        }
+        finish();
+    }
+
+    public final void setAccountAuthenticatorResult(Bundle result) {
+        mResultBundle = result;
+    }
+
+    /**
+     * Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present.
+     */
+    public void finish() {
+        Intent intent = getIntent();
+        AccountAuthenticatorResponse accountAuthenticatorResponse =
+                intent.getParcelableExtra(EXTRAS_RESPONSE);
+        if (accountAuthenticatorResponse != null) {
+            // send the result bundle back if set, otherwise send an error.
+            if (mResultBundle != null) {
+                accountAuthenticatorResponse.onResult(mResultBundle);
+            } else {
+                accountAuthenticatorResponse.onError(Constants.ERROR_CODE_CANCELED, "canceled");
+            }
+        }
+        super.finish();
+    }
+
+    private static class PackagesArrayAdapter extends ArrayAdapter<String> {
+        protected LayoutInflater mInflater;
+        private static final int mResource = R.layout.simple_list_item_1;
+
+        public PackagesArrayAdapter(Context context, String[] items) {
+            super(context, mResource, items);
+            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+        }
+
+        static class ViewHolder {
+            TextView label;
+        }
+
+        @Override
+        public View getView(int position, View convertView, ViewGroup parent) {
+            // A ViewHolder keeps references to children views to avoid unneccessary calls
+            // to findViewById() on each row.
+            ViewHolder holder;
+
+            // When convertView is not null, we can reuse it directly, there is no need
+            // to reinflate it. We only inflate a new View when the convertView supplied
+            // by ListView is null.
+            if (convertView == null) {
+                convertView = mInflater.inflate(mResource, null);
+
+                // Creates a ViewHolder and store references to the two children views
+                // we want to bind data to.
+                holder = new ViewHolder();
+                holder.label = (TextView) convertView.findViewById(R.id.text1);
+
+                convertView.setTag(holder);
+            } else {
+                // Get the ViewHolder back to get fast access to the TextView
+                // and the ImageView.
+                holder = (ViewHolder) convertView.getTag();
+            }
+
+            holder.label.setText(getItem(position));
+
+            return convertView;
+        }
+    }
+}
diff --git a/core/java/android/accounts/IAccountAuthenticator.aidl b/core/java/android/accounts/IAccountAuthenticator.aidl
new file mode 100644
index 0000000..7d4de39
--- /dev/null
+++ b/core/java/android/accounts/IAccountAuthenticator.aidl
@@ -0,0 +1,73 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.accounts.IAccountAuthenticatorResponse;
+import android.accounts.Account;
+import android.os.Bundle;
+
+/**
+ * Service that allows the interaction with an authentication server.
+ */
+oneway interface IAccountAuthenticator {
+    /**
+     * prompts the user for account information and adds the result to the IAccountManager
+     */
+    void addAccount(in IAccountAuthenticatorResponse response, String accountType,
+        String authTokenType, in String[] requiredFeatures, in Bundle options);
+
+    /**
+     * Checks that the account/password combination is valid.
+     * @deprecated
+     */
+    void confirmPassword(in IAccountAuthenticatorResponse response,
+        in Account account, String password);
+
+    /**
+     * prompts the user for the credentials of the account
+     */
+    void confirmCredentials(in IAccountAuthenticatorResponse response, in Account account);
+
+    /**
+     * gets the password by either prompting the user or querying the IAccountManager
+     */
+    void getAuthToken(in IAccountAuthenticatorResponse response, in Account account,
+        String authTokenType, in Bundle options);
+
+    /**
+     * Gets the user-visible label of the given authtoken type.
+     */
+    void getAuthTokenLabel(in IAccountAuthenticatorResponse response, String authTokenType);
+
+    /**
+     * prompts the user for a new password and writes it to the IAccountManager
+     */
+    void updateCredentials(in IAccountAuthenticatorResponse response, in Account account,
+        String authTokenType, in Bundle options);
+
+    /**
+     * launches an activity that lets the user edit and set the properties for an authenticator
+     */
+    void editProperties(in IAccountAuthenticatorResponse response, String accountType);
+
+    /**
+     * returns a Bundle where the boolean value BOOLEAN_RESULT_KEY is set if the account has the
+     * specified features
+     */
+    void hasFeatures(in IAccountAuthenticatorResponse response, in Account account, 
+        in String[] features);
+}
diff --git a/libs/utils/executablepath_linux.cpp b/core/java/android/accounts/IAccountAuthenticatorResponse.aidl
similarity index 60%
copy from libs/utils/executablepath_linux.cpp
copy to core/java/android/accounts/IAccountAuthenticatorResponse.aidl
index b8d2a3d..a9ac2f1 100644
--- a/libs/utils/executablepath_linux.cpp
+++ b/core/java/android/accounts/IAccountAuthenticatorResponse.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,17 +14,14 @@
  * limitations under the License.
  */
 
-#include <utils/executablepath.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <limits.h>
-#include <stdio.h>
+package android.accounts;
+import android.os.Bundle;
 
-void executablepath(char exe[PATH_MAX])
-{
-    char proc[100];
-    sprintf(proc, "/proc/%d/exe", getpid());
-    
-    int err = readlink(proc, exe, PATH_MAX);
+/**
+ * The interface used to return responses from an {@link IAccountAuthenticator}
+ */
+oneway interface IAccountAuthenticatorResponse {
+    void onResult(in Bundle value);
+    void onRequestContinued();
+    void onError(int errorCode, String errorMessage);
 }
-
diff --git a/core/java/android/accounts/IAccountManager.aidl b/core/java/android/accounts/IAccountManager.aidl
new file mode 100644
index 0000000..15ab4e8
--- /dev/null
+++ b/core/java/android/accounts/IAccountManager.aidl
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+package android.accounts;
+
+import android.accounts.IAccountManagerResponse;
+import android.accounts.Account;
+import android.accounts.AuthenticatorDescription;
+import android.os.Bundle;
+
+/**
+ * Central application service that provides account management.
+ * @hide
+ */
+interface IAccountManager {
+    String getPassword(in Account account);
+    String getUserData(in Account account, String key);
+    AuthenticatorDescription[] getAuthenticatorTypes();
+    Account[] getAccounts();
+    Account[] getAccountsByType(String accountType);
+    boolean addAccount(in Account account, String password, in Bundle extras);
+    void removeAccount(in Account account);
+    void invalidateAuthToken(String accountType, String authToken);
+    String peekAuthToken(in Account account, String authTokenType);
+    void setAuthToken(in Account account, String authTokenType, String authToken);
+    void setPassword(in Account account, String password);
+    void clearPassword(in Account account);
+    void setUserData(in Account account, String key, String value);
+
+    void getAuthToken(in IAccountManagerResponse response, in Account account,
+        String authTokenType, boolean notifyOnAuthFailure, boolean expectActivityLaunch,
+        in Bundle options);
+    void addAcount(in IAccountManagerResponse response, String accountType,
+        String authTokenType, in String[] requiredFeatures, boolean expectActivityLaunch, 
+        in Bundle options);
+    void updateCredentials(in IAccountManagerResponse response, in Account account,
+        String authTokenType, boolean expectActivityLaunch, in Bundle options);
+    void editProperties(in IAccountManagerResponse response, String accountType,
+        boolean expectActivityLaunch);
+    void confirmCredentials(in IAccountManagerResponse response, in Account account,
+        boolean expectActivityLaunch);
+    void getAccountsByTypeAndFeatures(in IAccountManagerResponse response, String accountType,
+        in String[] features);
+
+    /*
+     * @deprecated
+     */
+    void confirmPassword(in IAccountManagerResponse response, in Account account,
+        String password);
+}
diff --git a/libs/utils/executablepath_linux.cpp b/core/java/android/accounts/IAccountManagerResponse.aidl
similarity index 61%
rename from libs/utils/executablepath_linux.cpp
rename to core/java/android/accounts/IAccountManagerResponse.aidl
index b8d2a3d..ca1203d 100644
--- a/libs/utils/executablepath_linux.cpp
+++ b/core/java/android/accounts/IAccountManagerResponse.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,17 +14,14 @@
  * limitations under the License.
  */
 
-#include <utils/executablepath.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <limits.h>
-#include <stdio.h>
+package android.accounts;
+import android.os.Bundle;
 
-void executablepath(char exe[PATH_MAX])
-{
-    char proc[100];
-    sprintf(proc, "/proc/%d/exe", getpid());
-    
-    int err = readlink(proc, exe, PATH_MAX);
+/**
+ * The interface used to return responses for asynchronous calls to the {@link IAccountManager}
+ * @hide
+ */
+oneway interface IAccountManagerResponse {
+    void onResult(in Bundle value);
+    void onError(int errorCode, String errorMessage);
 }
-
diff --git a/core/java/android/accounts/IAccountsService.aidl b/core/java/android/accounts/IAccountsService.aidl
deleted file mode 100644
index dda513c..0000000
--- a/core/java/android/accounts/IAccountsService.aidl
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2008 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.accounts;
-
-/**
- * Central application service that allows querying the list of accounts.
- */
-interface IAccountsService {
-    /**
-     * Gets the list of Accounts the user has previously logged
-     * in to.  Accounts are of the form "username@domain".
-     * <p>
-     * This method will return an empty array if the device doesn't
-     * know about any accounts (yet).
-     *
-     * @return The accounts.  The array will be zero-length if the
-     *         AccountsService doesn't know about any accounts yet.
-     */
-    String[] getAccounts();
-
-    /**
-     * This is an interim solution for bypassing a forgotten gesture on the
-     * unlock screen (it is hidden, please make sure it stays this way!). This
-     * will be *removed* when the unlock screen design supports additional
-     * authenticators.
-     * <p>
-     * The user will be presented with username and password fields that are
-     * called as parameters to this method. If true is returned, the user is
-     * able to define a new gesture and get back into the system. If false, the
-     * user can try again.
-     * 
-     * @param username The username entered.
-     * @param password The password entered.
-     * @return Whether to allow the user to bypass the lock screen and define a
-     *         new gesture.
-     * @hide (The package is already hidden, but just in case someone
-     *       unhides that, this should not be revealed.)
-     */
-    boolean shouldUnlock(String username, String password);
-}
diff --git a/core/java/android/accounts/NetworkErrorException.java b/core/java/android/accounts/NetworkErrorException.java
new file mode 100644
index 0000000..f855cc8
--- /dev/null
+++ b/core/java/android/accounts/NetworkErrorException.java
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+package android.accounts;
+
+public class NetworkErrorException extends Exception {
+    public NetworkErrorException() {
+        super();
+    }
+    public NetworkErrorException(String message) {
+        super(message);
+    }
+    public NetworkErrorException(String message, Throwable cause) {
+        super(message, cause);
+    }
+    public NetworkErrorException(Throwable cause) {
+        super(cause);
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/accounts/AccountMonitorListener.java b/core/java/android/accounts/OnAccountsUpdatedListener.java
similarity index 85%
rename from core/java/android/accounts/AccountMonitorListener.java
rename to core/java/android/accounts/OnAccountsUpdatedListener.java
index d0bd9a9..bd249d0 100644
--- a/core/java/android/accounts/AccountMonitorListener.java
+++ b/core/java/android/accounts/OnAccountsUpdatedListener.java
@@ -19,11 +19,11 @@
 /**
  * An interface that contains the callback used by the AccountMonitor
  */
-public interface AccountMonitorListener {
+public interface OnAccountsUpdatedListener {
     /**
      * This invoked when the AccountMonitor starts up and whenever the account
      * set changes.
-     * @param currentAccounts the current accounts
+     * @param accounts the current accounts
      */
-    void onAccountsUpdated(String[] currentAccounts);
+    void onAccountsUpdated(Account[] accounts);
 }
diff --git a/core/java/android/accounts/OperationCanceledException.java b/core/java/android/accounts/OperationCanceledException.java
new file mode 100644
index 0000000..2f2c164
--- /dev/null
+++ b/core/java/android/accounts/OperationCanceledException.java
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+package android.accounts;
+
+public class OperationCanceledException extends Exception {
+    public OperationCanceledException() {
+        super();
+    }
+    public OperationCanceledException(String message) {
+        super(message);
+    }
+    public OperationCanceledException(String message, Throwable cause) {
+        super(message, cause);
+    }
+    public OperationCanceledException(Throwable cause) {
+        super(cause);
+    }
+}
diff --git a/core/java/android/accounts/package.html b/core/java/android/accounts/package.html
deleted file mode 100755
index c9f96a6..0000000
--- a/core/java/android/accounts/package.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<body>
-
-{@hide}
-
-</body>
diff --git a/core/java/android/app/ApplicationContext.java b/core/java/android/app/ApplicationContext.java
index 92929ea..1e4ab68 100644
--- a/core/java/android/app/ApplicationContext.java
+++ b/core/java/android/app/ApplicationContext.java
@@ -96,6 +96,8 @@
 import android.view.WindowManagerImpl;
 import android.view.accessibility.AccessibilityManager;
 import android.view.inputmethod.InputMethodManager;
+import android.accounts.AccountManager;
+import android.accounts.IAccountManager;
 
 import java.io.File;
 import java.io.FileInputStream;
@@ -155,6 +157,7 @@
     private final static boolean DEBUG_ICONS = false;
 
     private static final Object sSync = new Object();
+    private static AccountManager sAccountManager;
     private static AlarmManager sAlarmManager;
     private static PowerManager sPowerManager;
     private static ConnectivityManager sConnectivityManager;
@@ -903,6 +906,8 @@
             return getActivityManager();
         } else if (ALARM_SERVICE.equals(name)) {
             return getAlarmManager();
+        } else if (ACCOUNT_SERVICE.equals(name)) {
+            return getAccountManager();
         } else if (POWER_SERVICE.equals(name)) {
             return getPowerManager();
         } else if (CONNECTIVITY_SERVICE.equals(name)) {
@@ -945,6 +950,17 @@
         return null;
     }
 
+    private AccountManager getAccountManager() {
+        synchronized (sSync) {
+            if (sAccountManager == null) {
+                IBinder b = ServiceManager.getService(ACCOUNT_SERVICE);
+                IAccountManager service = IAccountManager.Stub.asInterface(b);
+                sAccountManager = new AccountManager(this, service);
+            }
+        }
+        return sAccountManager;
+    }
+
     private ActivityManager getActivityManager() {
         synchronized (mSync) {
             if (mActivityManager == null) {
diff --git a/core/java/android/app/ApplicationErrorReport.java b/core/java/android/app/ApplicationErrorReport.java
index 6b17236..aeae5f9 100644
--- a/core/java/android/app/ApplicationErrorReport.java
+++ b/core/java/android/app/ApplicationErrorReport.java
@@ -171,6 +171,11 @@
         public String throwMethodName;
 
         /**
+         * Line number the exception was thrown from.
+         */
+        public int throwLineNumber;
+
+        /**
          * Stack trace.
          */
         public String stackTrace;
@@ -190,6 +195,7 @@
             throwFileName = in.readString();
             throwClassName = in.readString();
             throwMethodName = in.readString();
+            throwLineNumber = in.readInt();
             stackTrace = in.readString();
         }
 
@@ -202,6 +208,7 @@
             dest.writeString(throwFileName);
             dest.writeString(throwClassName);
             dest.writeString(throwMethodName);
+            dest.writeInt(throwLineNumber);
             dest.writeString(stackTrace);
         }
 
@@ -214,6 +221,7 @@
             pw.println(prefix + "throwFileName: " + throwFileName);
             pw.println(prefix + "throwClassName: " + throwClassName);
             pw.println(prefix + "throwMethodName: " + throwMethodName);
+            pw.println(prefix + "throwLineNumber: " + throwLineNumber);
             pw.println(prefix + "stackTrace: " + stackTrace);
         }
     }
diff --git a/core/java/android/app/ApplicationThreadNative.java b/core/java/android/app/ApplicationThreadNative.java
index a3c6325..5335239 100644
--- a/core/java/android/app/ApplicationThreadNative.java
+++ b/core/java/android/app/ApplicationThreadNative.java
@@ -524,7 +524,8 @@
         data.writeInterfaceToken(IApplicationThread.descriptor);
         app.writeToParcel(data, 0);
         data.writeInt(backupMode);
-        mRemote.transact(SCHEDULE_CREATE_BACKUP_AGENT_TRANSACTION, data, null, 0);
+        mRemote.transact(SCHEDULE_CREATE_BACKUP_AGENT_TRANSACTION, data, null,
+                IBinder.FLAG_ONEWAY);
         data.recycle();
     }
 
@@ -532,7 +533,8 @@
         Parcel data = Parcel.obtain();
         data.writeInterfaceToken(IApplicationThread.descriptor);
         app.writeToParcel(data, 0);
-        mRemote.transact(SCHEDULE_DESTROY_BACKUP_AGENT_TRANSACTION, data, null, 0);
+        mRemote.transact(SCHEDULE_DESTROY_BACKUP_AGENT_TRANSACTION, data, null,
+                IBinder.FLAG_ONEWAY);
         data.recycle();
     }
     
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 9834c75..a67e60b 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -458,7 +458,9 @@
                 sb.append(this.vibrate[i]);
                 sb.append(',');
             }
-            sb.append(this.vibrate[N]);
+            if (N != -1) {
+                sb.append(this.vibrate[N]);
+            }
             sb.append("]");
         } else if ((this.defaults & DEFAULT_VIBRATE) != 0) {
             sb.append("default");
diff --git a/core/java/android/backup/BackupManager.java b/core/java/android/backup/BackupManager.java
index c52fcd2d..da1647a 100644
--- a/core/java/android/backup/BackupManager.java
+++ b/core/java/android/backup/BackupManager.java
@@ -43,7 +43,7 @@
     private static final String TAG = "BackupManager";
 
     /** @hide TODO: REMOVE THIS */
-    public static final boolean EVEN_THINK_ABOUT_DOING_RESTORE = false;
+    public static final boolean EVEN_THINK_ABOUT_DOING_RESTORE = true;
 
     private Context mContext;
     private static IBackupManager sService;
diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java
index 951b4b0..a64c6d7 100644
--- a/core/java/android/bluetooth/BluetoothDevice.java
+++ b/core/java/android/bluetooth/BluetoothDevice.java
@@ -74,8 +74,16 @@
     /** An existing bond was explicitly revoked */
     public static final int UNBOND_REASON_REMOVED = 6;
 
+    /* The user will be prompted to enter a pin */
+    public static final int PAIRING_VARIANT_PIN = 0;
+    /* The user will be prompted to enter a passkey */
+    public static final int PAIRING_VARIANT_PASSKEY = 1;
+    /* The user will be prompted to confirm the passkey displayed on the screen */
+    public static final int PAIRING_VARIANT_CONFIRMATION = 2;
+
+
     private static final String TAG = "BluetoothDevice";
-    
+
     private final IBluetoothDevice mService;
     /**
      * @hide - hide this because it takes a parameter of type
@@ -180,31 +188,6 @@
         return false;
     }
 
-    public String getVersion() {
-        try {
-            return mService.getVersion();
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-    public String getRevision() {
-        try {
-            return mService.getRevision();
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-    public String getManufacturer() {
-        try {
-            return mService.getManufacturer();
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-    public String getCompany() {
-        try {
-            return mService.getCompany();
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-
     /**
      * Get the current scan mode.
      * Used to determine if the local device is connectable and/or discoverable
@@ -241,11 +224,8 @@
     }
 
     public boolean startDiscovery() {
-        return startDiscovery(true);
-    }
-    public boolean startDiscovery(boolean resolveNames) {
         try {
-            return mService.startDiscovery(resolveNames);
+            return mService.startDiscovery();
         } catch (RemoteException e) {Log.e(TAG, "", e);}
         return false;
     }
@@ -263,88 +243,17 @@
         return false;
     }
 
-    public boolean startPeriodicDiscovery() {
-        try {
-            return mService.startPeriodicDiscovery();
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return false;
-    }
-    public boolean stopPeriodicDiscovery() {
-        try {
-            return mService.stopPeriodicDiscovery();
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return false;
-    }
-    public boolean isPeriodicDiscovery() {
-        try {
-            return mService.isPeriodicDiscovery();
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return false;
-    }
-
-    public String[] listRemoteDevices() {
-        try {
-            return mService.listRemoteDevices();
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-
     /**
-     * List remote devices that have a low level (ACL) connection.
-     *
-     * RFCOMM, SDP and L2CAP are all built on ACL connections. Devices can have
-     * an ACL connection even when not paired - this is common for SDP queries
-     * or for in-progress pairing requests.
-     *
-     * In most cases you probably want to test if a higher level protocol is
-     * connected, rather than testing ACL connections.
-     *
-     * @return bluetooth hardware addresses of remote devices with a current
-     *         ACL connection. Array size is 0 if no devices have a
-     *         connection. Null on error.
-     */
-    public String[] listAclConnections() {
-        try {
-            return mService.listAclConnections();
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-
-    /**
-     * Check if a specified remote device has a low level (ACL) connection.
-     *
-     * RFCOMM, SDP and L2CAP are all built on ACL connections. Devices can have
-     * an ACL connection even when not paired - this is common for SDP queries
-     * or for in-progress pairing requests.
-     *
-     * In most cases you probably want to test if a higher level protocol is
-     * connected, rather than testing ACL connections.
-     *
-     * @param address the Bluetooth hardware address you want to check.
-     * @return true if there is an ACL connection, false otherwise and on
-     *         error.
-     */
-    public boolean isAclConnected(String address) {
-        try {
-            return mService.isAclConnected(address);
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return false;
-    }
-
-    /**
-     * Perform a low level (ACL) disconnection of a remote device.
-     *
-     * This forcably disconnects the ACL layer connection to a remote device,
-     * which will cause all RFCOMM, SDP and L2CAP connections to this remote
-     * device to close.
+     * Removes the remote device and the pairing information associated
+     * with it.
      *
      * @param address the Bluetooth hardware address you want to disconnect.
      * @return true if the device was disconnected, false otherwise and on
      *         error.
      */
-    public boolean disconnectRemoteDeviceAcl(String address) {
+    public boolean removeBond(String address) {
         try {
-            return mService.disconnectRemoteDeviceAcl(address);
+            return mService.removeBond(address);
         } catch (RemoteException e) {Log.e(TAG, "", e);}
         return false;
     }
@@ -377,16 +286,6 @@
     }
 
     /**
-     * Remove an already exisiting bonding (delete the link key).
-     */
-    public boolean removeBond(String address) {
-        try {
-            return mService.removeBond(address);
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return false;
-    }
-
-    /**
      * List remote devices that are bonded (paired) to the local device.
      *
      * Bonding (pairing) is the process by which the user enters a pin code for
@@ -440,78 +339,25 @@
         return null;
     }
 
-    public String getRemoteVersion(String address) {
-        try {
-            return mService.getRemoteVersion(address);
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-    public String getRemoteRevision(String address) {
-        try {
-            return mService.getRemoteRevision(address);
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-    public String getRemoteManufacturer(String address) {
-        try {
-            return mService.getRemoteManufacturer(address);
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-    public String getRemoteCompany(String address) {
-        try {
-            return mService.getRemoteCompany(address);
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-
-    /**
-     * Returns the RFCOMM channel associated with the 16-byte UUID on
-     * the remote Bluetooth address.
-     *
-     * Performs a SDP ServiceSearchAttributeRequest transaction. The provided
-     * uuid is verified in the returned record. If there was a problem, or the
-     * specified uuid does not exist, -1 is returned.
-     */
-    public boolean getRemoteServiceChannel(String address, short uuid16,
-            IBluetoothDeviceCallback callback) {
-        try {
-            return mService.getRemoteServiceChannel(address, uuid16, callback);
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return false;
-    }
-
-    /**
-     * Get the major, minor and servics classes of a remote device.
-     * These classes are encoded as a 32-bit integer. See BluetoothClass.
-     * @param address remote device
-     * @return 32-bit class suitable for use with BluetoothClass, or
-     *         BluetoothClass.ERROR on error
-     */
     public int getRemoteClass(String address) {
         try {
             return mService.getRemoteClass(address);
         } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return BluetoothClass.ERROR;
+        return BluetoothError.ERROR_IPC;
     }
 
-    public byte[] getRemoteFeatures(String address) {
+     public String[] getRemoteUuids(String address) {
         try {
-            return mService.getRemoteFeatures(address);
+            return mService.getRemoteUuids(address);
         } catch (RemoteException e) {Log.e(TAG, "", e);}
         return null;
     }
-    public String lastSeen(String address) {
-        try {
-            return mService.lastSeen(address);
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
-    }
-    public String lastUsed(String address) {
-        try {
-            return mService.lastUsed(address);
-        } catch (RemoteException e) {Log.e(TAG, "", e);}
-        return null;
+
+    public int getRemoteServiceChannel(String address, String uuid) {
+         try {
+             return mService.getRemoteServiceChannel(address, uuid);
+         } catch (RemoteException e) {Log.e(TAG, "", e);}
+         return BluetoothError.ERROR_IPC;
     }
 
     public boolean setPin(String address, byte[] pin) {
@@ -520,9 +366,24 @@
         } catch (RemoteException e) {Log.e(TAG, "", e);}
         return false;
     }
-    public boolean cancelPin(String address) {
+
+    public boolean setPasskey(String address, int passkey) {
         try {
-            return mService.cancelPin(address);
+            return mService.setPasskey(address, passkey);
+        } catch (RemoteException e) {Log.e(TAG, "", e);}
+        return false;
+    }
+
+    public boolean setPairingConfirmation(String address, boolean confirm) {
+        try {
+            return mService.setPairingConfirmation(address, confirm);
+        } catch (RemoteException e) {Log.e(TAG, "", e);}
+        return false;
+    }
+
+    public boolean cancelPairingUserInput(String address) {
+        try {
+            return mService.cancelPairingUserInput(address);
         } catch (RemoteException e) {Log.e(TAG, "", e);}
         return false;
     }
diff --git a/core/java/android/bluetooth/BluetoothInputStream.java b/core/java/android/bluetooth/BluetoothInputStream.java
new file mode 100644
index 0000000..c060f32
--- /dev/null
+++ b/core/java/android/bluetooth/BluetoothInputStream.java
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * BluetoothInputStream.
+ *
+ * Used to write to a Bluetooth socket.
+ *
+ * @hide
+ */
+/*package*/ final class BluetoothInputStream extends InputStream {
+    private BluetoothSocket mSocket;
+
+    /*package*/ BluetoothInputStream(BluetoothSocket s) {
+        mSocket = s;
+    }
+
+    /**
+     * Return number of bytes available before this stream will block.
+     */
+    public int available() throws IOException {
+        return mSocket.availableNative();
+    }
+
+    public void close() throws IOException {
+        mSocket.close();
+    }
+
+    /**
+     * Reads a single byte from this stream and returns it as an integer in the
+     * range from 0 to 255. Returns -1 if the end of the stream has been
+     * reached. Blocks until one byte has been read, the end of the source
+     * stream is detected or an exception is thrown.
+     *
+     * @return the byte read or -1 if the end of stream has been reached.
+     * @throws IOException
+     *             if the stream is closed or another IOException occurs.
+     * @since Android 1.5
+     */
+    public int read() throws IOException {
+        byte b[] = new byte[1];
+        int ret = mSocket.readNative(b, 0, 1);
+        if (ret == 1) {
+            return (int)b[0] & 0xff;
+        } else {
+            return -1;
+        }
+    }
+
+    /**
+     * Reads at most {@code length} bytes from this stream and stores them in
+     * the byte array {@code b} starting at {@code offset}.
+     *
+     * @param b
+     *            the byte array in which to store the bytes read.
+     * @param offset
+     *            the initial position in {@code buffer} to store the bytes
+     *            read from this stream.
+     * @param length
+     *            the maximum number of bytes to store in {@code b}.
+     * @return the number of bytes actually read or -1 if the end of the stream
+     *         has been reached.
+     * @throws IndexOutOfBoundsException
+     *             if {@code offset < 0} or {@code length < 0}, or if
+     *             {@code offset + length} is greater than the length of
+     *             {@code b}.
+     * @throws IOException
+     *             if the stream is closed or another IOException occurs.
+     * @since Android 1.5
+     */
+    public int read(byte[] b, int offset, int length) throws IOException {
+        if (b == null) {
+            throw new NullPointerException("byte array is null");
+        }
+        if ((offset | length) < 0 || length > b.length - offset) {
+            throw new ArrayIndexOutOfBoundsException("invalid offset or length");
+        }
+        return mSocket.readNative(b, offset, length);
+    }
+}
diff --git a/core/java/android/bluetooth/BluetoothIntent.java b/core/java/android/bluetooth/BluetoothIntent.java
index 344601b..d6c79b4 100644
--- a/core/java/android/bluetooth/BluetoothIntent.java
+++ b/core/java/android/bluetooth/BluetoothIntent.java
@@ -57,6 +57,10 @@
         "android.bluetooth.intent.BOND_PREVIOUS_STATE";
     public static final String REASON =
         "android.bluetooth.intent.REASON";
+    public static final String PAIRING_VARIANT =
+        "android.bluetooth.intent.PAIRING_VARIANT";
+    public static final String PASSKEY =
+        "android.bluetooth.intent.PASSKEY";
 
     /** Broadcast when the local Bluetooth device state changes, for example
      *  when Bluetooth is enabled. Will contain int extra's BLUETOOTH_STATE and
diff --git a/core/java/android/bluetooth/BluetoothOutputStream.java b/core/java/android/bluetooth/BluetoothOutputStream.java
new file mode 100644
index 0000000..7e2ead4
--- /dev/null
+++ b/core/java/android/bluetooth/BluetoothOutputStream.java
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * BluetoothOutputStream.
+ *
+ * Used to read from a Bluetooth socket.
+ *
+ * @hide
+ */
+/*package*/ final class BluetoothOutputStream extends OutputStream {
+    private BluetoothSocket mSocket;
+
+    /*package*/ BluetoothOutputStream(BluetoothSocket s) {
+        mSocket = s;
+    }
+
+    /**
+     * Close this output stream and the socket associated with it.
+     */
+    public void close() throws IOException {
+        mSocket.close();
+    }
+
+    /**
+     * Writes a single byte to this stream. Only the least significant byte of
+     * the integer {@code oneByte} is written to the stream.
+     *
+     * @param oneByte
+     *            the byte to be written.
+     * @throws IOException
+     *             if an error occurs while writing to this stream.
+     * @since Android 1.0
+     */
+    public void write(int oneByte) throws IOException {
+        byte b[] = new byte[1];
+        b[0] = (byte)oneByte;
+        mSocket.writeNative(b, 0, 1);
+    }
+
+    /**
+     * Writes {@code count} bytes from the byte array {@code buffer} starting
+     * at position {@code offset} to this stream.
+     *
+     * @param b
+     *            the buffer to be written.
+     * @param offset
+     *            the start position in {@code buffer} from where to get bytes.
+     * @param count
+     *            the number of bytes from {@code buffer} to write to this
+     *            stream.
+     * @throws IOException
+     *             if an error occurs while writing to this stream.
+     * @throws IndexOutOfBoundsException
+     *             if {@code offset < 0} or {@code count < 0}, or if
+     *             {@code offset + count} is bigger than the length of
+     *             {@code buffer}.
+     * @since Android 1.0
+     */
+    public void write(byte[] b, int offset, int count) throws IOException {
+        if (b == null) {
+            throw new NullPointerException("buffer is null");
+        }
+        if ((offset | count) < 0 || count > b.length - offset) {
+            throw new IndexOutOfBoundsException("invalid offset or length");
+        }
+        mSocket.writeNative(b, offset, count);
+    }
+}
diff --git a/core/java/android/bluetooth/BluetoothServerSocket.java b/core/java/android/bluetooth/BluetoothServerSocket.java
new file mode 100644
index 0000000..f3baeab
--- /dev/null
+++ b/core/java/android/bluetooth/BluetoothServerSocket.java
@@ -0,0 +1,150 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth;
+
+import java.io.Closeable;
+import java.io.IOException;
+
+/**
+ * Server (listening) Bluetooth Socket.
+ *
+ * Currently only supports RFCOMM sockets.
+ *
+ * RFCOMM is a connection orientated, streaming transport over Bluetooth. It is
+ * also known as the Serial Port Profile (SPP).
+ *
+ * TODO: Consider exposing L2CAP sockets.
+ * TODO: Clean up javadoc grammer and formatting.
+ * TODO: Remove @hide
+ * @hide
+ */
+public final class BluetoothServerSocket implements Closeable {
+    private final BluetoothSocket mSocket;
+
+    /**
+     * Construct a listening, secure RFCOMM server socket.
+     * The remote device connecting to this socket will be authenticated and
+     * communication on this socket will be encrypted.
+     * Call #accept to retrieve connections to this socket.
+     * @return An RFCOMM BluetoothServerSocket
+     * @throws IOException On error, for example Bluetooth not available, or
+     *                     insufficient permissions.
+     */
+    public static BluetoothServerSocket listenUsingRfcommOn(int port) throws IOException {
+        BluetoothServerSocket socket = new BluetoothServerSocket(
+                BluetoothSocket.TYPE_RFCOMM, true, true, port);
+        try {
+            socket.mSocket.bindListenNative();
+        } catch (IOException e) {
+            try {
+                socket.close();
+            } catch (IOException e2) { }
+            throw e;
+        }
+        return socket;
+    }
+
+    /**
+     * Construct an unencrypted, unauthenticated, RFCOMM server socket.
+     * Call #accept to retrieve connections to this socket.
+     * @return An RFCOMM BluetoothServerSocket
+     * @throws IOException On error, for example Bluetooth not available, or
+     *                     insufficient permissions.
+     */
+    public static BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException {
+        BluetoothServerSocket socket = new BluetoothServerSocket(
+                BluetoothSocket.TYPE_RFCOMM, false, false, port);
+        try {
+            socket.mSocket.bindListenNative();
+        } catch (IOException e) {
+            try {
+                socket.close();
+            } catch (IOException e2) { }
+            throw e;
+        }
+        return socket;
+    }
+
+    /**
+     * Construct a SCO server socket.
+     * Call #accept to retrieve connections to this socket.
+     * @return A SCO BluetoothServerSocket
+     * @throws IOException On error, for example Bluetooth not available, or
+     *                     insufficient permissions.
+     */
+    public static BluetoothServerSocket listenUsingScoOn() throws IOException {
+        BluetoothServerSocket socket = new BluetoothServerSocket(
+                BluetoothSocket.TYPE_SCO, false, false, -1);
+        try {
+            socket.mSocket.bindListenNative();
+        } catch (IOException e) {
+            try {
+                socket.close();
+            } catch (IOException e2) { }
+            throw e;
+        }
+        return socket;
+    }
+
+    /**
+     * Construct a socket for incoming connections.
+     * @param type    type of socket
+     * @param auth    require the remote device to be authenticated
+     * @param encrypt require the connection to be encrypted
+     * @param port    remote port
+     * @throws IOException On error, for example Bluetooth not available, or
+     *                     insufficient priveleges
+     */
+    private BluetoothServerSocket(int type, boolean auth, boolean encrypt, int port)
+            throws IOException {
+        mSocket = new BluetoothSocket(type, -1, auth, encrypt, null, port);
+    }
+
+    /**
+     * Block until a connection is established.
+     * Returns a connected #BluetoothSocket. This server socket can be reused
+     * for subsequent incoming connections by calling #accept repeatedly.
+     * #close can be used to abort this call from another thread.
+     * @return A connected #BluetoothSocket
+     * @throws IOException On error, for example this call was aborted
+     */
+    public BluetoothSocket accept() throws IOException {
+        return accept(-1);
+    }
+
+    /**
+     * Block until a connection is established, with timeout.
+     * Returns a connected #BluetoothSocket. This server socket can be reused
+     * for subsequent incoming connections by calling #accept repeatedly.
+     * #close can be used to abort this call from another thread.
+     * @return A connected #BluetoothSocket
+     * @throws IOException On error, for example this call was aborted, or
+     *                     timeout
+     */
+    public BluetoothSocket accept(int timeout) throws IOException {
+        return mSocket.acceptNative(timeout);
+    }
+
+    /**
+     * Closes this socket.
+     * This will cause other blocking calls on this socket to immediately
+     * throw an IOException.
+     */
+    public void close() throws IOException {
+        mSocket.closeNative();
+    }
+}
diff --git a/core/java/android/bluetooth/BluetoothSocket.java b/core/java/android/bluetooth/BluetoothSocket.java
new file mode 100644
index 0000000..de1f326
--- /dev/null
+++ b/core/java/android/bluetooth/BluetoothSocket.java
@@ -0,0 +1,197 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * Represents a connected or connecting Bluetooth Socket.
+ *
+ * Currently only supports RFCOMM sockets.
+ *
+ * RFCOMM is a connection orientated, streaming transport over Bluetooth. It is
+ * also known as the Serial Port Profile (SPP).
+ *
+ * TODO: Consider exposing L2CAP sockets.
+ * TODO: Clean up javadoc grammer and formatting.
+ * TODO: Remove @hide
+ * @hide
+ */
+public final class BluetoothSocket implements Closeable {
+    /** Keep TYPE_RFCOMM etc in sync with BluetoothSocket.cpp */
+    /*package*/ static final int TYPE_RFCOMM = 1;
+    /*package*/ static final int TYPE_SCO = 2;
+    /*package*/ static final int TYPE_L2CAP = 3;
+
+    private final int mType;  /* one of TYPE_RFCOMM etc */
+    private final int mPort;  /* RFCOMM channel or L2CAP psm */
+    private final String mAddress;    /* remote address */
+    private final boolean mAuth;
+    private final boolean mEncrypt;
+    private final BluetoothInputStream mInputStream;
+    private final BluetoothOutputStream mOutputStream;
+
+    private int mSocketData;    /* used by native code only */
+
+    /**
+     * Construct a secure RFCOMM socket ready to start an outgoing connection.
+     * Call #connect on the returned #BluetoothSocket to begin the connection.
+     * The remote device will be authenticated and communication on this socket
+     * will be encrypted.
+     * @param address remote Bluetooth address that this socket can connect to
+     * @param port    remote port
+     * @return an RFCOMM BluetoothSocket
+     * @throws IOException on error, for example Bluetooth not available, or
+     *                     insufficient permissions.
+     */
+    public static BluetoothSocket createRfcommSocket(String address, int port)
+            throws IOException {
+        return new BluetoothSocket(TYPE_RFCOMM, -1, true, true, address, port);
+    }
+
+    /**
+     * Construct an insecure RFCOMM socket ready to start an outgoing
+     * connection.
+     * Call #connect on the returned #BluetoothSocket to begin the connection.
+     * The remote device will not be authenticated and communication on this
+     * socket will not be encrypted.
+     * @param address remote Bluetooth address that this socket can connect to
+     * @param port    remote port
+     * @return An RFCOMM BluetoothSocket
+     * @throws IOException On error, for example Bluetooth not available, or
+     *                     insufficient permissions.
+     */
+    public static BluetoothSocket createInsecureRfcommSocket(String address, int port)
+            throws IOException {
+        return new BluetoothSocket(TYPE_RFCOMM, -1, false, false, address, port);
+    }
+
+    /**
+     * Construct a SCO socket ready to start an outgoing connection.
+     * Call #connect on the returned #BluetoothSocket to begin the connection.
+     * @param address remote Bluetooth address that this socket can connect to
+     * @return a SCO BluetoothSocket
+     * @throws IOException on error, for example Bluetooth not available, or
+     *                     insufficient permissions.
+     */
+    public static BluetoothSocket createScoSocket(String address, int port)
+            throws IOException {
+        return new BluetoothSocket(TYPE_SCO, -1, true, true, address, port);
+    }
+
+    /**
+     * Construct a Bluetooth.
+     * @param type    type of socket
+     * @param fd      fd to use for connected socket, or -1 for a new socket
+     * @param auth    require the remote device to be authenticated
+     * @param encrypt require the connection to be encrypted
+     * @param address remote Bluetooth address that this socket can connect to
+     * @param port    remote port
+     * @throws IOException On error, for example Bluetooth not available, or
+     *                     insufficient priveleges
+     */
+    /*package*/ BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, String address,
+            int port) throws IOException {
+        mType = type;
+        mAuth = auth;
+        mEncrypt = encrypt;
+        mAddress = address;
+        mPort = port;
+        if (fd == -1) {
+            initSocketNative();
+        } else {
+            initSocketFromFdNative(fd);
+        }
+        mInputStream = new BluetoothInputStream(this);
+        mOutputStream = new BluetoothOutputStream(this);
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            close();
+        } finally {
+            super.finalize();
+        }
+    }
+
+    /**
+     * Attempt to connect to a remote device.
+     * This method will block until a connection is made or the connection
+     * fails. If this method returns without an exception then this socket
+     * is now connected. #close can be used to abort this call from another
+     * thread.
+     * @throws IOException On error, for example connection failure
+     */
+    public void connect() throws IOException {
+        connectNative();
+    }
+
+    /**
+     * Closes this socket.
+     * This will cause other blocking calls on this socket to immediately
+     * throw an IOException.
+     */
+    public void close() throws IOException {
+        closeNative();
+    }
+
+    /**
+     * Return the address we are connecting, or connected, to.
+     * @return Bluetooth address, or null if this socket has not yet attempted
+     *         or established a connection.
+     */
+    public String getAddress() {
+        return mAddress;
+    }
+
+    /**
+     * Get the input stream associated with this socket.
+     * The input stream will be returned even if the socket is not yet
+     * connected, but operations on that stream will throw IOException until
+     * the associated socket is connected.
+     * @return InputStream
+     */
+    public InputStream getInputStream() throws IOException {
+        return mInputStream;
+    }
+
+    /**
+     * Get the output stream associated with this socket.
+     * The output stream will be returned even if the socket is not yet
+     * connected, but operations on that stream will throw IOException until
+     * the associated socket is connected.
+     * @return OutputStream
+     */
+    public OutputStream getOutputStream() throws IOException {
+        return mOutputStream;
+    }
+
+    private native void initSocketNative() throws IOException;
+    private native void initSocketFromFdNative(int fd) throws IOException;
+    private native void connectNative() throws IOException;
+    /*package*/ native void bindListenNative() throws IOException;
+    /*package*/ native BluetoothSocket acceptNative(int timeout) throws IOException;
+    /*package*/ native int availableNative() throws IOException;
+    /*package*/ native int readNative(byte[] b, int offset, int length) throws IOException;
+    /*package*/ native int writeNative(byte[] b, int offset, int length) throws IOException;
+    /*package*/ native void closeNative() throws IOException;
+    private native void destroyNative() throws IOException;
+}
diff --git a/core/java/android/bluetooth/BluetoothUuid.java b/core/java/android/bluetooth/BluetoothUuid.java
new file mode 100644
index 0000000..f8316a5
--- /dev/null
+++ b/core/java/android/bluetooth/BluetoothUuid.java
@@ -0,0 +1,62 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth;
+
+import java.util.UUID;
+
+/**
+* Static helper methods and constants to decode the UUID of remote devices.
+*  @hide
+*/
+public final class BluetoothUuid {
+
+    /* See Bluetooth Assigned Numbers document - SDP section, to get the values of UUIDs
+     * for the various services.
+     *
+     * The following 128 bit values are calculated as:
+     *  uuid * 2^96 + BASE_UUID
+     */
+    public static final UUID AudioSink = UUID.fromString("0000110A-0000-1000-8000-00805F9B34FB");
+    public static final UUID AudioSource = UUID.fromString("0000110B-0000-1000-8000-00805F9B34FB");
+    public static final UUID AdvAudioDist = UUID.fromString("0000110D-0000-1000-8000-00805F9B34FB");
+    public static final UUID HSP       = UUID.fromString("00001108-0000-1000-8000-00805F9B34FB");
+    public static final UUID HeadsetHS = UUID.fromString("00001131-0000-1000-8000-00805F9B34FB");
+    public static final UUID Handsfree  = UUID.fromString("0000111e-0000-1000-8000-00805F9B34FB");
+    public static final UUID HandsfreeAudioGateway
+                                          = UUID.fromString("0000111f-0000-1000-8000-00805F9B34FB");
+
+    public static boolean isAudioSource(UUID uuid) {
+        return uuid.equals(AudioSource);
+    }
+
+    public static boolean isAudioSink(UUID uuid) {
+        return uuid.equals(AudioSink);
+    }
+
+    public static boolean isAdvAudioDist(UUID uuid) {
+        return uuid.equals(AdvAudioDist);
+    }
+
+    public static boolean isHandsfree(UUID uuid) {
+        return uuid.equals(Handsfree);
+    }
+
+    public static boolean isHeadset(UUID uuid) {
+        return uuid.equals(HSP) || uuid.equals(HeadsetHS);
+    }
+}
+
diff --git a/core/java/android/bluetooth/Database.java b/core/java/android/bluetooth/Database.java
deleted file mode 100644
index fef641a..0000000
--- a/core/java/android/bluetooth/Database.java
+++ /dev/null
@@ -1,200 +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.bluetooth;
-
-import android.bluetooth.RfcommSocket;
-
-import android.util.Log;
-
-import java.io.*;
-import java.util.*;
-
-/**
- * The Android Bluetooth API is not finalized, and *will* change. Use at your
- * own risk.
- * 
- * A low-level API to the Service Discovery Protocol (SDP) Database.
- *
- * Allows service records to be added to the local SDP database. Once added,
- * these services will be advertised to remote devices when they make SDP
- * queries on this device.
- *
- * Currently this API is a thin wrapper to the bluez SDP Database API. See:
- * http://wiki.bluez.org/wiki/Database
- * http://wiki.bluez.org/wiki/HOWTO/ManagingServiceRecords
- * @hide
- */
-public final class Database {
-    private static Database mInstance;
-
-    private static final String sLogName = "android.bluetooth.Database";
-
-    /**
-     * Class load time initialization
-     */
-    static {
-        classInitNative();
-    }
-    private native static void classInitNative();
-
-    /**
-     * Private to enforce singleton property
-     */
-    private Database() {
-        initializeNativeDataNative();
-    }
-    private native void initializeNativeDataNative();
-
-    protected void finalize() throws Throwable {
-        try {
-            cleanupNativeDataNative();
-        } finally {
-            super.finalize();
-        }
-    }
-    private native void cleanupNativeDataNative();
-
-    /**
-     * Singelton accessor
-     * @return The singleton instance of Database
-     */
-    public static synchronized Database getInstance() {
-        if (mInstance == null) {
-            mInstance = new Database();
-        }
-        return mInstance;
-    }
-
-    /**
-     * Advertise a service with an RfcommSocket.
-     *
-     * This adds the service the SDP Database with the following attributes
-     * set: Service Name, Protocol Descriptor List, Service Class ID List
-     * TODO: Construct a byte[] record directly, rather than via XML.
-     * @param       socket The rfcomm socket to advertise (by channel).
-     * @param       serviceName A short name for this service
-     * @param       uuid
-     *                  Unique identifier for this service, by which clients
-     *                  can search for your service
-     * @return      Handle to the new service record
-     */
-    public int advertiseRfcommService(RfcommSocket socket,
-                                      String serviceName,
-                                      UUID uuid) throws IOException {
-        String xmlRecord =
-                "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
-                "<record>\n" +
-                "  <attribute id=\"0x0001\">\n" + // ServiceClassIDList
-                "    <sequence>\n" +
-                "      <uuid value=\""
-                        + uuid.toString() +       // UUID for this service
-                        "\"/>\n" +
-                "    </sequence>\n" +
-                "  </attribute>\n" +
-                "  <attribute id=\"0x0004\">\n" + // ProtocolDescriptorList
-                "    <sequence>\n" +
-                "      <sequence>\n" +
-                "        <uuid value=\"0x0100\"/>\n" +  // L2CAP
-                "      </sequence>\n" +
-                "      <sequence>\n" +
-                "        <uuid value=\"0x0003\"/>\n" +  // RFCOMM
-                "        <uint8 value=\"" +
-                        socket.getPort() +              // RFCOMM port
-                        "\" name=\"channel\"/>\n" +
-                "      </sequence>\n" +
-                "    </sequence>\n" +
-                "  </attribute>\n" +
-                "  <attribute id=\"0x0100\">\n" + // ServiceName
-                "    <text value=\"" + serviceName + "\"/>\n" +
-                "  </attribute>\n" +
-                "</record>\n";
-        Log.i(sLogName, xmlRecord);
-        return addServiceRecordFromXml(xmlRecord);
-    }
-
-
-    /**
-     * Add a new service record.
-     * @param record The byte[] record
-     * @return       A handle to the new record
-     */
-    public synchronized int addServiceRecord(byte[] record) throws IOException {
-        int handle = addServiceRecordNative(record);
-        Log.i(sLogName, "Added SDP record: " + Integer.toHexString(handle));
-        return handle;
-    }
-    private native int addServiceRecordNative(byte[] record)
-            throws IOException;
-
-    /**
-     * Add a new service record, using XML.
-     * @param record The record as an XML string
-     * @return       A handle to the new record
-     */
-    public synchronized int addServiceRecordFromXml(String record) throws IOException {
-        int handle = addServiceRecordFromXmlNative(record);
-        Log.i(sLogName, "Added SDP record: " + Integer.toHexString(handle));
-        return handle;
-    }
-    private native int addServiceRecordFromXmlNative(String record)
-            throws IOException;
-
-    /**
-     * Update an exisiting service record.
-     * @param handle Handle to exisiting record
-     * @param record The updated byte[] record
-     */
-    public synchronized void updateServiceRecord(int handle, byte[] record) {
-        try {
-            updateServiceRecordNative(handle, record);
-        } catch (IOException e) {
-            Log.e(getClass().toString(), e.getMessage());
-        }
-    }
-    private native void updateServiceRecordNative(int handle, byte[] record)
-            throws IOException;
-
-    /**
-     * Update an exisiting record, using XML.
-     * @param handle Handle to exisiting record
-     * @param record The record as an XML string.
-     */
-    public synchronized void updateServiceRecordFromXml(int handle, String record) {
-        try {
-            updateServiceRecordFromXmlNative(handle, record);
-        } catch (IOException e) {
-            Log.e(getClass().toString(), e.getMessage());
-        }
-    }
-    private native void updateServiceRecordFromXmlNative(int handle, String record)
-            throws IOException;
-
-    /**
-     * Remove a service record.
-     * It is only possible to remove service records that were added by the
-     * current connection.
-     * @param handle Handle to exisiting record to be removed
-     */
-    public synchronized void removeServiceRecord(int handle) {
-        try {
-            removeServiceRecordNative(handle);
-        } catch (IOException e) {
-            Log.e(getClass().toString(), e.getMessage());
-        }
-    }
-    private native void removeServiceRecordNative(int handle) throws IOException;
-}
diff --git a/core/java/android/bluetooth/IBluetoothDevice.aidl b/core/java/android/bluetooth/IBluetoothDevice.aidl
index 6cd792e..a78752b 100644
--- a/core/java/android/bluetooth/IBluetoothDevice.aidl
+++ b/core/java/android/bluetooth/IBluetoothDevice.aidl
@@ -16,8 +16,6 @@
 
 package android.bluetooth;
 
-import android.bluetooth.IBluetoothDeviceCallback;
-
 /**
  * System private API for talking with the Bluetooth service.
  *
@@ -33,10 +31,6 @@
     String getAddress();
     String getName();
     boolean setName(in String name);
-    String getVersion();
-    String getRevision();
-    String getManufacturer();
-    String getCompany();
 
     int getScanMode();
     boolean setScanMode(int mode);
@@ -44,17 +38,9 @@
     int getDiscoverableTimeout();
     boolean setDiscoverableTimeout(int timeout);
 
-    boolean startDiscovery(boolean resolveNames);
+    boolean startDiscovery();
     boolean cancelDiscovery();
     boolean isDiscovering();
-    boolean startPeriodicDiscovery();
-    boolean stopPeriodicDiscovery();
-    boolean isPeriodicDiscovery();
-    String[] listRemoteDevices();
-
-    String[] listAclConnections();
-    boolean isAclConnected(in String address);
-    boolean disconnectRemoteDeviceAcl(in String address);
 
     boolean createBond(in String address);
     boolean cancelBondProcess(in String address);
@@ -63,16 +49,13 @@
     int getBondState(in String address);
 
     String getRemoteName(in String address);
-    String getRemoteVersion(in String address);
-    String getRemoteRevision(in String address);
     int getRemoteClass(in String address);
-    String getRemoteManufacturer(in String address);
-    String getRemoteCompany(in String address);
-    boolean getRemoteServiceChannel(in String address, int uuid16, in IBluetoothDeviceCallback callback);
-    byte[] getRemoteFeatures(in String adddress);
-    String lastSeen(in String address);
-    String lastUsed(in String address);
+    String[] getRemoteUuids(in String address);
+    int getRemoteServiceChannel(in String address, String uuid);
 
     boolean setPin(in String address, in byte[] pin);
-    boolean cancelPin(in String address);
+    boolean setPasskey(in String address, int passkey);
+    boolean setPairingConfirmation(in String address, boolean confirm);
+    boolean cancelPairingUserInput(in String address);
+
 }
diff --git a/core/java/android/bluetooth/IBluetoothDeviceCallback.aidl b/core/java/android/bluetooth/IBluetoothDeviceCallback.aidl
deleted file mode 100644
index d057093..0000000
--- a/core/java/android/bluetooth/IBluetoothDeviceCallback.aidl
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2008, 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.bluetooth;
-
-/**
- * {@hide}
- */
-oneway interface IBluetoothDeviceCallback
-{
-    void onGetRemoteServiceChannelResult(in String address, int channel);
-}
diff --git a/core/java/android/bluetooth/RfcommSocket.java b/core/java/android/bluetooth/RfcommSocket.java
deleted file mode 100644
index a33263f..0000000
--- a/core/java/android/bluetooth/RfcommSocket.java
+++ /dev/null
@@ -1,674 +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.bluetooth;
-
-import java.io.IOException;
-import java.io.FileOutputStream;
-import java.io.FileInputStream;
-import java.io.OutputStream;
-import java.io.InputStream;
-import java.io.FileDescriptor;
-
-/**
- * The Android Bluetooth API is not finalized, and *will* change. Use at your
- * own risk.
- * 
- * This class implements an API to the Bluetooth RFCOMM layer. An RFCOMM socket
- * is similar to a normal socket in that it takes an address and a port number.
- * The difference is of course that the address is a Bluetooth-device address,
- * and the port number is an RFCOMM channel. The API allows for the
- * establishment of listening sockets via methods
- * {@link #bind(String, int) bind}, {@link #listen(int) listen}, and
- * {@link #accept(RfcommSocket, int) accept}, as well as for the making of
- * outgoing connections with {@link #connect(String, int) connect},
- * {@link #connectAsync(String, int) connectAsync}, and
- * {@link #waitForAsyncConnect(int) waitForAsyncConnect}.
- * 
- * After constructing a socket, you need to {@link #create() create} it and then
- * {@link #destroy() destroy} it when you are done using it. Both
- * {@link #create() create} and {@link #accept(RfcommSocket, int) accept} return
- * a {@link java.io.FileDescriptor FileDescriptor} for the actual data.
- * Alternatively, you may call {@link #getInputStream() getInputStream} and
- * {@link #getOutputStream() getOutputStream} to retrieve the respective streams
- * without going through the FileDescriptor.
- *
- * @hide
- */
-public class RfcommSocket {
-
-    /**
-     * Used by the native implementation of the class.
-     */
-    private int mNativeData;
-
-    /**
-     * Used by the native implementation of the class.
-     */
-    private int mPort;
-
-    /**
-     * Used by the native implementation of the class.
-     */
-    private String mAddress;
-
-    /**
-     * We save the return value of {@link #create() create} and
-     * {@link #accept(RfcommSocket,int) accept} in this variable, and use it to
-     * retrieve the I/O streams.
-     */
-    private FileDescriptor mFd;
-
-    /**
-     * After a call to {@link #waitForAsyncConnect(int) waitForAsyncConnect},
-     * if the return value is zero, then, the the remaining time left to wait is
-     * written into this variable (by the native implementation). It is possible
-     * that {@link #waitForAsyncConnect(int) waitForAsyncConnect} returns before
-     * the user-specified timeout expires, which is why we save the remaining
-     * time in this member variable for the user to retrieve by calling method
-     * {@link #getRemainingAsyncConnectWaitingTimeMs() getRemainingAsyncConnectWaitingTimeMs}.
-     */
-    private int mTimeoutRemainingMs;
-
-    /**
-     * Set to true when an asynchronous (nonblocking) connect is in progress.
-     * {@see #connectAsync(String,int)}.
-     */
-    private boolean mIsConnecting;
-
-    /**
-     * Set to true after a successful call to {@link #bind(String,int) bind} and
-     * used for error checking in {@link #listen(int) listen}. Reset to false
-     * on {@link #destroy() destroy}.
-     */
-    private boolean mIsBound = false;
-
-    /**
-     * Set to true after a successful call to {@link #listen(int) listen} and
-     * used for error checking in {@link #accept(RfcommSocket,int) accept}.
-     * Reset to false on {@link #destroy() destroy}.
-     */
-    private boolean mIsListening = false;
-
-    /**
-     * Used to store the remaining time after an accept with a non-negative
-     * timeout returns unsuccessfully. It is possible that a blocking
-     * {@link #accept(int) accept} may wait for less than the time specified by
-     * the user, which is why we store the remainder in this member variable for
-     * it to be retrieved with method
-     * {@link #getRemainingAcceptWaitingTimeMs() getRemainingAcceptWaitingTimeMs}.
-     */
-    private int mAcceptTimeoutRemainingMs;
-
-    /**
-     * Maintained by {@link #getInputStream() getInputStream}.
-     */
-    protected FileInputStream mInputStream;
-
-    /**
-     * Maintained by {@link #getOutputStream() getOutputStream}.
-     */
-    protected FileOutputStream mOutputStream;
-
-    private native void initializeNativeDataNative();
-
-    /**
-     * Constructor.
-     */
-    public RfcommSocket() {
-        initializeNativeDataNative();
-    }
-
-    private native void cleanupNativeDataNative();
-
-    /**
-     * Called by the GC to clean up the native data that we set up when we
-     * construct the object.
-     */
-    protected void finalize() throws Throwable {
-        try {
-            cleanupNativeDataNative();
-        } finally {
-            super.finalize();
-        }
-    }
-
-    private native static void classInitNative();
-
-    static {
-        classInitNative();
-    }
-
-    /**
-     * Creates a socket. You need to call this method before performing any
-     * other operation on a socket.
-     * 
-     * @return FileDescriptor for the data stream.
-     * @throws IOException
-     * @see #destroy()
-     */
-    public FileDescriptor create() throws IOException {
-        if (mFd == null) {
-            mFd = createNative();
-        }
-        if (mFd == null) {
-            throw new IOException("socket not created");
-        }
-        return mFd;
-    }
-
-    private native FileDescriptor createNative();
-
-    /**
-     * Destroys a socket created by {@link #create() create}. Call this
-     * function when you no longer use the socket in order to release the
-     * underlying OS resources.
-     * 
-     * @see #create()
-     */
-    public void destroy() {
-        synchronized (this) {
-            destroyNative();
-            mFd = null;
-            mIsBound = false;
-            mIsListening = false;
-        }
-    }
-
-    private native void destroyNative();
-
-    /**
-     * Returns the {@link java.io.FileDescriptor FileDescriptor} of the socket.
-     * 
-     * @return the FileDescriptor
-     * @throws IOException
-     *             when the socket has not been {@link #create() created}.
-     */
-    public FileDescriptor getFileDescriptor() throws IOException {
-        if (mFd == null) {
-            throw new IOException("socket not created");
-        }
-        return mFd;
-    }
-
-    /**
-     * Retrieves the input stream from the socket. Alternatively, you can do
-     * that from the FileDescriptor returned by {@link #create() create} or
-     * {@link #accept(RfcommSocket, int) accept}.
-     * 
-     * @return InputStream
-     * @throws IOException
-     *             if you have not called {@link #create() create} on the
-     *             socket.
-     */
-    public InputStream getInputStream() throws IOException {
-        if (mFd == null) {
-            throw new IOException("socket not created");
-        }
-
-        synchronized (this) {
-            if (mInputStream == null) {
-                mInputStream = new FileInputStream(mFd);
-            }
-
-            return mInputStream;
-        }
-    }
-
-    /**
-     * Retrieves the output stream from the socket. Alternatively, you can do
-     * that from the FileDescriptor returned by {@link #create() create} or
-     * {@link #accept(RfcommSocket, int) accept}.
-     * 
-     * @return OutputStream
-     * @throws IOException
-     *             if you have not called {@link #create() create} on the
-     *             socket.
-     */
-    public OutputStream getOutputStream() throws IOException {
-        if (mFd == null) {
-            throw new IOException("socket not created");
-        }
-
-        synchronized (this) {
-            if (mOutputStream == null) {
-                mOutputStream = new FileOutputStream(mFd);
-            }
-
-            return mOutputStream;
-        }
-    }
-
-    /**
-     * Starts a blocking connect to a remote RFCOMM socket. It takes the address
-     * of a device and the RFCOMM channel (port) to which to connect.
-     * 
-     * @param address
-     *            is the Bluetooth address of the remote device.
-     * @param port
-     *            is the RFCOMM channel
-     * @return true on success, false on failure
-     * @throws IOException
-     *             if {@link #create() create} has not been called.
-     * @see #connectAsync(String, int)
-     */
-    public boolean connect(String address, int port) throws IOException {
-        synchronized (this) {
-            if (mFd == null) {
-                throw new IOException("socket not created");
-            }
-            return connectNative(address, port);
-        }
-    }
-
-    private native boolean connectNative(String address, int port);
-
-    /**
-     * Starts an asynchronous (nonblocking) connect to a remote RFCOMM socket.
-     * It takes the address of the device to connect to, as well as the RFCOMM
-     * channel (port). On successful return (return value is true), you need to
-     * call method {@link #waitForAsyncConnect(int) waitForAsyncConnect} to
-     * block for up to a specified number of milliseconds while waiting for the
-     * asyncronous connect to complete.
-     * 
-     * @param address
-     *            of remote device
-     * @param port
-     *            the RFCOMM channel
-     * @return true when the asynchronous connect has successfully started,
-     *         false if there was an error.
-     * @throws IOException
-     *             is you have not called {@link #create() create}
-     * @see #waitForAsyncConnect(int)
-     * @see #getRemainingAsyncConnectWaitingTimeMs()
-     * @see #connect(String, int)
-     */
-    public boolean connectAsync(String address, int port) throws IOException {
-        synchronized (this) {
-            if (mFd == null) {
-                throw new IOException("socket not created");
-            }
-            mIsConnecting = connectAsyncNative(address, port);
-            return mIsConnecting;
-        }
-    }
-
-    private native boolean connectAsyncNative(String address, int port);
-
-    /**
-     * Interrupts an asynchronous connect in progress. This method does nothing
-     * when there is no asynchronous connect in progress.
-     * 
-     * @throws IOException
-     *             if you have not called {@link #create() create}.
-     * @see #connectAsync(String, int)
-     */
-    public void interruptAsyncConnect() throws IOException {
-        synchronized (this) {
-            if (mFd == null) {
-                throw new IOException("socket not created");
-            }
-            if (mIsConnecting) {
-                mIsConnecting = !interruptAsyncConnectNative();
-            }
-        }
-    }
-
-    private native boolean interruptAsyncConnectNative();
-
-    /**
-     * Tells you whether there is an asynchronous connect in progress. This
-     * method returns an undefined value when there is a synchronous connect in
-     * progress.
-     * 
-     * @return true if there is an asyc connect in progress, false otherwise
-     * @see #connectAsync(String, int)
-     */
-    public boolean isConnecting() {
-        return mIsConnecting;
-    }
-
-    /**
-     * Blocks for a specified amount of milliseconds while waiting for an
-     * asynchronous connect to complete. Returns an integer value to indicate
-     * one of the following: the connect succeeded, the connect is still in
-     * progress, or the connect failed. It is possible for this method to block
-     * for less than the time specified by the user, and still return zero
-     * (i.e., async connect is still in progress.) For this reason, if the
-     * return value is zero, you need to call method
-     * {@link #getRemainingAsyncConnectWaitingTimeMs() getRemainingAsyncConnectWaitingTimeMs}
-     * to retrieve the remaining time.
-     * 
-     * @param timeoutMs
-     *            the time to block while waiting for the async connect to
-     *            complete.
-     * @return a positive value if the connect succeeds; zero, if the connect is
-     *         still in progress, and a negative value if the connect failed.
-     * 
-     * @throws IOException
-     * @see #getRemainingAsyncConnectWaitingTimeMs()
-     * @see #connectAsync(String, int)
-     */
-    public int waitForAsyncConnect(int timeoutMs) throws IOException {
-        synchronized (this) {
-            if (mFd == null) {
-                throw new IOException("socket not created");
-            }
-            int ret = waitForAsyncConnectNative(timeoutMs);
-            if (ret != 0) {
-                mIsConnecting = false;
-            }
-            return ret;
-        }
-    }
-
-    private native int waitForAsyncConnectNative(int timeoutMs);
-
-    /**
-     * Returns the number of milliseconds left to wait after the last call to
-     * {@link #waitForAsyncConnect(int) waitForAsyncConnect}.
-     * 
-     * It is possible that waitForAsyncConnect() waits for less than the time
-     * specified by the user, and still returns zero (i.e., async connect is
-     * still in progress.) For this reason, if the return value is zero, you
-     * need to call this method to retrieve the remaining time before you call
-     * waitForAsyncConnect again.
-     * 
-     * @return the remaining timeout in milliseconds.
-     * @see #waitForAsyncConnect(int)
-     * @see #connectAsync(String, int)
-     */
-    public int getRemainingAsyncConnectWaitingTimeMs() {
-        return mTimeoutRemainingMs;
-    }
-
-    /**
-     * Shuts down both directions on a socket.
-     * 
-     * @return true on success, false on failure; if the return value is false,
-     *         the socket might be left in a patially shut-down state (i.e. one
-     *         direction is shut down, but the other is still open.) In this
-     *         case, you should {@link #destroy() destroy} and then
-     *         {@link #create() create} the socket again.
-     * @throws IOException
-     *             is you have not caled {@link #create() create}.
-     * @see #shutdownInput()
-     * @see #shutdownOutput()
-     */
-    public boolean shutdown() throws IOException {
-        synchronized (this) {
-            if (mFd == null) {
-                throw new IOException("socket not created");
-            }
-            if (shutdownNative(true)) {
-                return shutdownNative(false);
-            }
-
-            return false;
-        }
-    }
-
-    /**
-     * Shuts down the input stream of the socket, but leaves the output stream
-     * in its current state.
-     * 
-     * @return true on success, false on failure
-     * @throws IOException
-     *             is you have not called {@link #create() create}
-     * @see #shutdown()
-     * @see #shutdownOutput()
-     */
-    public boolean shutdownInput() throws IOException {
-        synchronized (this) {
-            if (mFd == null) {
-                throw new IOException("socket not created");
-            }
-            return shutdownNative(true);
-        }
-    }
-
-    /**
-     * Shut down the output stream of the socket, but leaves the input stream in
-     * its current state.
-     * 
-     * @return true on success, false on failure
-     * @throws IOException
-     *             is you have not called {@link #create() create}
-     * @see #shutdown()
-     * @see #shutdownInput()
-     */
-    public boolean shutdownOutput() throws IOException {
-        synchronized (this) {
-            if (mFd == null) {
-                throw new IOException("socket not created");
-            }
-            return shutdownNative(false);
-        }
-    }
-
-    private native boolean shutdownNative(boolean shutdownInput);
-
-    /**
-     * Tells you whether a socket is connected to another socket. This could be
-     * for input or output or both.
-     * 
-     * @return true if connected, false otherwise.
-     * @see #isInputConnected()
-     * @see #isOutputConnected()
-     */
-    public boolean isConnected() {
-        return isConnectedNative() > 0;
-    }
-
-    /**
-     * Determines whether input is connected (i.e., whether you can receive data
-     * on this socket.)
-     * 
-     * @return true if input is connected, false otherwise.
-     * @see #isConnected()
-     * @see #isOutputConnected()
-     */
-    public boolean isInputConnected() {
-        return (isConnectedNative() & 1) != 0;
-    }
-
-    /**
-     * Determines whether output is connected (i.e., whether you can send data
-     * on this socket.)
-     * 
-     * @return true if output is connected, false otherwise.
-     * @see #isConnected()
-     * @see #isInputConnected()
-     */
-    public boolean isOutputConnected() {
-        return (isConnectedNative() & 2) != 0;
-    }
-
-    private native int isConnectedNative();
-
-    /**
-     * Binds a listening socket to the local device, or a non-listening socket
-     * to a remote device. The port is automatically selected as the first
-     * available port in the range 12 to 30.
-     *
-     * NOTE: Currently we ignore the device parameter and always bind the socket
-     * to the local device, assuming that it is a listening socket.
-     *
-     * TODO: Use bind(0) in native code to have the kernel select an unused
-     * port.
-     *
-     * @param device
-     *            Bluetooth address of device to bind to (currently ignored).
-     * @return true on success, false on failure
-     * @throws IOException
-     *             if you have not called {@link #create() create}
-     * @see #listen(int)
-     * @see #accept(RfcommSocket,int)
-     */
-    public boolean bind(String device) throws IOException {
-        if (mFd == null) {
-            throw new IOException("socket not created");
-        }
-        for (int port = 12; port <= 30; port++) {
-            if (bindNative(device, port)) {
-                mIsBound = true;
-                return true;
-            }
-        }
-        mIsBound = false;
-        return false;
-    }
-
-    /**
-     * Binds a listening socket to the local device, or a non-listening socket
-     * to a remote device.
-     *
-     * NOTE: Currently we ignore the device parameter and always bind the socket
-     * to the local device, assuming that it is a listening socket.
-     *
-     * @param device
-     *            Bluetooth address of device to bind to (currently ignored).
-     * @param port
-     *            RFCOMM channel to bind socket to.
-     * @return true on success, false on failure
-     * @throws IOException
-     *             if you have not called {@link #create() create}
-     * @see #listen(int)
-     * @see #accept(RfcommSocket,int)
-     */
-    public boolean bind(String device, int port) throws IOException {
-        if (mFd == null) {
-            throw new IOException("socket not created");
-        }
-        mIsBound = bindNative(device, port);
-        return mIsBound;
-    }
-
-    private native boolean bindNative(String device, int port);
-
-    /**
-     * Starts listening for incoming connections on this socket, after it has
-     * been bound to an address and RFCOMM channel with
-     * {@link #bind(String,int) bind}.
-     * 
-     * @param backlog
-     *            the number of pending incoming connections to queue for
-     *            {@link #accept(RfcommSocket, int) accept}.
-     * @return true on success, false on failure
-     * @throws IOException
-     *             if you have not called {@link #create() create} or if the
-     *             socket has not been bound to a device and RFCOMM channel.
-     */
-    public boolean listen(int backlog) throws IOException {
-        if (mFd == null) {
-            throw new IOException("socket not created");
-        }
-        if (!mIsBound) {
-            throw new IOException("socket not bound");
-        }
-        mIsListening = listenNative(backlog);
-        return mIsListening;
-    }
-
-    private native boolean listenNative(int backlog);
-
-    /**
-     * Accepts incoming-connection requests for a listening socket bound to an
-     * RFCOMM channel. The user may provide a time to wait for an incoming
-     * connection.
-     * 
-     * Note that this method may return null (i.e., no incoming connection)
-     * before the user-specified timeout expires. For this reason, on a null
-     * return value, you need to call
-     * {@link #getRemainingAcceptWaitingTimeMs() getRemainingAcceptWaitingTimeMs}
-     * in order to see how much time is left to wait, before you call this
-     * method again.
-     * 
-     * @param newSock
-     *            is set to the new socket that is created as a result of a
-     *            successful accept.
-     * @param timeoutMs
-     *            time (in milliseconds) to block while waiting to an
-     *            incoming-connection request. A negative value is an infinite
-     *            wait.
-     * @return FileDescriptor of newSock on success, null on failure. Failure
-     *         occurs if the timeout expires without a successful connect.
-     * @throws IOException
-     *             if the socket has not been {@link #create() create}ed, is
-     *             not bound, or is not a listening socket.
-     * @see #bind(String, int)
-     * @see #listen(int)
-     * @see #getRemainingAcceptWaitingTimeMs()
-     */
-    public FileDescriptor accept(RfcommSocket newSock, int timeoutMs)
-            throws IOException {
-        synchronized (newSock) {
-            if (mFd == null) {
-                throw new IOException("socket not created");
-            }
-            if (mIsListening == false) {
-                throw new IOException("not listening on socket");
-            }
-            newSock.mFd = acceptNative(newSock, timeoutMs);
-            return newSock.mFd;
-        }
-    }
-
-    /**
-     * Returns the number of milliseconds left to wait after the last call to
-     * {@link #accept(RfcommSocket, int) accept}.
-     * 
-     * Since accept() may return null (i.e., no incoming connection) before the
-     * user-specified timeout expires, you need to call this method in order to
-     * see how much time is left to wait, and wait for that amount of time
-     * before you call accept again.
-     * 
-     * @return the remaining time, in milliseconds.
-     */
-    public int getRemainingAcceptWaitingTimeMs() {
-        return mAcceptTimeoutRemainingMs;
-    }
-
-    private native FileDescriptor acceptNative(RfcommSocket newSock,
-            int timeoutMs);
-
-    /**
-     * Get the port (rfcomm channel) associated with this socket.
-     *
-     * This is only valid if the port has been set via a successful call to
-     * {@link #bind(String, int)}, {@link #connect(String, int)}
-     * or {@link #connectAsync(String, int)}. This can be checked
-     * with {@link #isListening()} and {@link #isConnected()}.
-     * @return Port (rfcomm channel)
-     */
-    public int getPort() throws IOException {
-        if (mFd == null) {
-            throw new IOException("socket not created");
-        }
-        if (!mIsListening && !isConnected()) {
-            throw new IOException("not listening or connected on socket");
-        }
-        return mPort;
-    }
-
-    /**
-     * Return true if this socket is listening ({@link #listen(int)}
-     * has been called successfully).
-     */
-    public boolean isListening() {
-        return mIsListening;
-    }
-}
diff --git a/core/java/android/content/AbstractCursorEntityIterator.java b/core/java/android/content/AbstractCursorEntityIterator.java
new file mode 100644
index 0000000..bf3c4de
--- /dev/null
+++ b/core/java/android/content/AbstractCursorEntityIterator.java
@@ -0,0 +1,112 @@
+package android.content;
+
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.os.RemoteException;
+
+/**
+ * An abstract class that makes it easy to implement an EntityIterator over a cursor.
+ * The user must implement {@link #newEntityFromCursorLocked}, which runs inside of a
+ * database transaction.
+ */
+public abstract class AbstractCursorEntityIterator implements EntityIterator {
+    private final Cursor mEntityCursor;
+    private final SQLiteDatabase mDb;
+    private volatile Entity mNextEntity;
+    private volatile boolean mIsClosed;
+
+    public AbstractCursorEntityIterator(SQLiteDatabase db, Cursor entityCursor) {
+        mEntityCursor = entityCursor;
+        mDb = db;
+        mNextEntity = null;
+        mIsClosed = false;
+    }
+
+    /**
+     * If there are entries left in the cursor then advance the cursor and use the new row to
+     * populate mNextEntity. If the cursor is at the end or if advancing it causes the cursor
+     * to become at the end then set mEntityCursor to null. If newEntityFromCursor returns null
+     * then continue advancing until it either returns a non-null Entity or the cursor reaches
+     * the end.
+     */
+    private void fillEntityIfAvailable() {
+        while (mNextEntity == null) {
+            if (!mEntityCursor.moveToNext()) {
+                // the cursor is at then end, bail out
+                return;
+            }
+            // This may return null if newEntityFromCursor is not able to create an entity
+            // from the current cursor position. In that case this method will loop and try
+            // the next cursor position
+            mNextEntity = newEntityFromCursorLocked(mEntityCursor);
+        }
+        mDb.beginTransaction();
+        try {
+            int position = mEntityCursor.getPosition();
+            mNextEntity = newEntityFromCursorLocked(mEntityCursor);
+            int newPosition = mEntityCursor.getPosition();
+            if (newPosition != position) {
+                throw new IllegalStateException("the cursor position changed during the call to"
+                        + "newEntityFromCursorLocked, from " + position + " to " + newPosition);
+            }
+        } finally {
+            mDb.endTransaction();
+        }
+    }
+
+    /**
+     * Checks if there are more Entities accessible via this iterator. This may not be called
+     * if the iterator is already closed.
+     * @return true if the call to next() will return an Entity.
+     */
+    public boolean hasNext() {
+        if (mIsClosed) {
+            throw new IllegalStateException("calling hasNext() when the iterator is closed");
+        }
+        fillEntityIfAvailable();
+        return mNextEntity != null;
+    }
+
+    /**
+     * Returns the next Entity that is accessible via this iterator. This may not be called
+     * if the iterator is already closed.
+     * @return the next Entity that is accessible via this iterator
+     */
+    public Entity next() {
+        if (mIsClosed) {
+            throw new IllegalStateException("calling next() when the iterator is closed");
+        }
+        if (!hasNext()) {
+            throw new IllegalStateException("you may only call next() if hasNext() is true");
+        }
+
+        try {
+            return mNextEntity;
+        } finally {
+            mNextEntity = null;
+        }
+    }
+
+    /**
+     * Closes this iterator making it invalid. If is invalid for the user to call any public
+     * method on the iterator once it has been closed.
+     */
+    public void close() {
+        if (mIsClosed) {
+            throw new IllegalStateException("closing when already closed");
+        }
+        mIsClosed = true;
+        mEntityCursor.close();
+    }
+
+    /**
+     * Returns a new Entity from the current cursor position. This is called from within a
+     * database transaction. If a new entity cannot be created from this cursor position (e.g.
+     * if the row that is referred to no longer exists) then this may return null. The cursor
+     * is guaranteed to be pointing to a valid row when this call is made. The implementation
+     * of newEntityFromCursorLocked is not allowed to change the position of the cursor.
+     * @param cursor from where to read the data for the Entity
+     * @return an Entity that corresponds to the current cursor position or null
+     */
+    public abstract Entity newEntityFromCursorLocked(Cursor cursor);
+}
diff --git a/core/java/android/content/AbstractSyncableContentProvider.java b/core/java/android/content/AbstractSyncableContentProvider.java
index 249d9ba..218f501 100644
--- a/core/java/android/content/AbstractSyncableContentProvider.java
+++ b/core/java/android/content/AbstractSyncableContentProvider.java
@@ -4,8 +4,9 @@
 import android.database.sqlite.SQLiteDatabase;
 import android.database.Cursor;
 import android.net.Uri;
-import android.accounts.AccountMonitor;
-import android.accounts.AccountMonitorListener;
+import android.accounts.OnAccountsUpdatedListener;
+import android.accounts.Account;
+import android.accounts.AccountManager;
 import android.provider.SyncConstValue;
 import android.util.Config;
 import android.util.Log;
@@ -14,9 +15,12 @@
 
 import java.util.Collections;
 import java.util.Map;
-import java.util.HashMap;
 import java.util.Vector;
 import java.util.ArrayList;
+import java.util.Set;
+import java.util.HashSet;
+
+import com.google.android.collect.Maps;
 
 /**
  * A specialization of the ContentProvider that centralizes functionality
@@ -32,26 +36,30 @@
     private final String mDatabaseName;
     private final int mDatabaseVersion;
     private final Uri mContentUri;
-    private AccountMonitor mAccountMonitor;
 
     /** the account set in the last call to onSyncStart() */
-    private String mSyncingAccount;
+    private Account mSyncingAccount;
 
     private SyncStateContentProviderHelper mSyncState = null;
 
-    private static final String[] sAccountProjection = new String[] {SyncConstValue._SYNC_ACCOUNT};
+    private static final String[] sAccountProjection =
+            new String[] {SyncConstValue._SYNC_ACCOUNT, SyncConstValue._SYNC_ACCOUNT_TYPE};
 
     private boolean mIsTemporary;
 
     private AbstractTableMerger mCurrentMerger = null;
     private boolean mIsMergeCancelled = false;
 
-    private static final String SYNC_ACCOUNT_WHERE_CLAUSE = SyncConstValue._SYNC_ACCOUNT + "=?";
+    private static final String SYNC_ACCOUNT_WHERE_CLAUSE =
+            SyncConstValue._SYNC_ACCOUNT + "=? AND " + SyncConstValue._SYNC_ACCOUNT_TYPE + "=?";
 
     protected boolean isTemporary() {
         return mIsTemporary;
     }
 
+    private final ThreadLocal<Boolean> mApplyingBatch = new ThreadLocal<Boolean>();
+    private final ThreadLocal<Set<Uri>> mPendingBatchNotifications = new ThreadLocal<Set<Uri>>();
+
     /**
      * Indicates whether or not this ContentProvider contains a full
      * set of data or just diffs. This knowledge comes in handy when
@@ -133,7 +141,8 @@
         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
             if (!upgradeDatabase(db, oldVersion, newVersion)) {
                 mSyncState.discardSyncData(db, null /* all accounts */);
-                getContext().getContentResolver().startSync(mContentUri, new Bundle());
+                ContentResolver.requestSync(null /* all accounts */,
+                        mContentUri.getAuthority(), new Bundle());
             }
         }
 
@@ -150,23 +159,36 @@
         mOpenHelper = new AbstractSyncableContentProvider.DatabaseHelper(getContext(),
                 mDatabaseName);
         mSyncState = new SyncStateContentProviderHelper(mOpenHelper);
-
-        AccountMonitorListener listener = new AccountMonitorListener() {
-            public void onAccountsUpdated(String[] accounts) {
-                // Some providers override onAccountsChanged(); give them a database to work with.
-                mDb = mOpenHelper.getWritableDatabase();
-                onAccountsChanged(accounts);
-                TempProviderSyncAdapter syncAdapter = (TempProviderSyncAdapter)getSyncAdapter();
-                if (syncAdapter != null) {
-                    syncAdapter.onAccountsChanged(accounts);
-                }
-            }
-        };
-        mAccountMonitor = new AccountMonitor(getContext(), listener);
+        AccountManager.get(getContext()).addOnAccountsUpdatedListener(
+                new OnAccountsUpdatedListener() {
+                    public void onAccountsUpdated(Account[] accounts) {
+                        // Some providers override onAccountsChanged(); give them a database to
+                        // work with.
+                        mDb = mOpenHelper.getWritableDatabase();
+                        // Only call onAccountsChanged on GAIA accounts; otherwise, the contacts and
+                        // calendar providers will choke as they try to sync unknown accounts with
+                        // AbstractGDataSyncAdapter, which will put acore into a crash loop
+                        ArrayList<Account> gaiaAccounts = new ArrayList<Account>();
+                        for (Account acct: accounts) {
+                            if (acct.mType.equals("com.google.GAIA")) {
+                                gaiaAccounts.add(acct);
+                            }
+                        }
+                        accounts = new Account[gaiaAccounts.size()];
+                        int i = 0;
+                        for (Account acct: gaiaAccounts) {
+                            accounts[i++] = acct;
+                        }
+                        onAccountsChanged(accounts);
+                        TempProviderSyncAdapter syncAdapter = getTempProviderSyncAdapter();
+                        if (syncAdapter != null) {
+                            syncAdapter.onAccountsChanged(accounts);
+                        }
+                    }
+                }, null /* handler */, true /* updateImmediately */);
 
         return true;
     }
-
     /**
      * Get a non-persistent instance of this content provider.
      * You must call {@link #close} on the returned
@@ -236,147 +258,117 @@
         return Collections.emptyList();
     }
 
-    /**
-     * <p>
-     * Call mOpenHelper.getWritableDatabase() and mDb.beginTransaction().
-     * {@link #endTransaction} MUST be called after calling this method.
-     * Those methods should be used like this:
-     * </p>
-     *
-     * <pre class="prettyprint">
-     * boolean successful = false;
-     * beginTransaction();
-     * try {
-     *     // Do something related to mDb
-     *     successful = true;
-     *     return ret;
-     * } finally {
-     *     endTransaction(successful);
-     * }
-     * </pre>
-     *
-     * @hide This method is dangerous from the view of database manipulation, though using
-     * this makes batch insertion/update/delete much faster.
-     */
-    public final void beginTransaction() {
+    @Override
+    public final int update(final Uri url, final ContentValues values,
+            final String selection, final String[] selectionArgs) {
         mDb = mOpenHelper.getWritableDatabase();
-        mDb.beginTransaction();
-    }
-
-    /**
-     * <p>
-     * Call mDb.endTransaction(). If successful is true, try to call
-     * mDb.setTransactionSuccessful() before calling mDb.endTransaction().
-     * This method MUST be used with {@link #beginTransaction()}.
-     * </p>
-     *
-     * @hide This method is dangerous from the view of database manipulation, though using
-     * this makes batch insertion/update/delete much faster.
-     */
-    public final void endTransaction(boolean successful) {
+        final boolean notApplyingBatch = !applyingBatch();
+        if (notApplyingBatch) {
+            mDb.beginTransaction();
+        }
         try {
-            if (successful) {
-                // setTransactionSuccessful() must be called just once during opening the
-                // transaction.
+            if (isTemporary() && mSyncState.matches(url)) {
+                int numRows = mSyncState.asContentProvider().update(
+                        url, values, selection, selectionArgs);
+                if (notApplyingBatch) {
+                    mDb.setTransactionSuccessful();
+                }
+                return numRows;
+            }
+
+            int result = updateInternal(url, values, selection, selectionArgs);
+            if (notApplyingBatch) {
                 mDb.setTransactionSuccessful();
             }
-        } finally {
-            mDb.endTransaction();
-        }
-    }
-
-    @Override
-    public final int update(final Uri uri, final ContentValues values,
-            final String selection, final String[] selectionArgs) {
-        boolean successful = false;
-        beginTransaction();
-        try {
-            int ret = nonTransactionalUpdate(uri, values, selection, selectionArgs);
-            successful = true;
-            return  ret;
-        } finally {
-            endTransaction(successful);
-        }
-    }
-
-    /**
-     * @hide
-     */
-    public final int nonTransactionalUpdate(final Uri uri, final ContentValues values,
-            final String selection, final String[] selectionArgs) {
-        if (isTemporary() && mSyncState.matches(uri)) {
-            int numRows = mSyncState.asContentProvider().update(
-                    uri, values, selection, selectionArgs);
-            return numRows;
-        }
-
-        int result = updateInternal(uri, values, selection, selectionArgs);
-        if (!isTemporary() && result > 0) {
-            getContext().getContentResolver().notifyChange(uri, null /* observer */,
-                    changeRequiresLocalSync(uri));
-        }
-
-        return result;
-    }
-
-    @Override
-    public final int delete(final Uri uri, final String selection,
-            final String[] selectionArgs) {
-        boolean successful = false;
-        beginTransaction();
-        try {
-            int ret = nonTransactionalDelete(uri, selection, selectionArgs);
-            successful = true;
-            return ret;
-        } finally {
-            endTransaction(successful);
-        }
-    }
-
-    /**
-     * @hide
-     */
-    public final int nonTransactionalDelete(final Uri uri, final String selection,
-            final String[] selectionArgs) {
-        if (isTemporary() && mSyncState.matches(uri)) {
-            int numRows = mSyncState.asContentProvider().delete(uri, selection, selectionArgs);
-            return numRows;
-        }
-        int result = deleteInternal(uri, selection, selectionArgs);
-        if (!isTemporary() && result > 0) {
-            getContext().getContentResolver().notifyChange(uri, null /* observer */,
-                    changeRequiresLocalSync(uri));
-        }
-        return result;
-    }
-
-    @Override
-    public final Uri insert(final Uri uri, final ContentValues values) {
-        boolean successful = false;
-        beginTransaction();
-        try {
-            Uri ret = nonTransactionalInsert(uri, values);
-            successful = true;
-            return ret;
-        } finally {
-            endTransaction(successful);
-        }
-    }
-
-    /**
-     * @hide
-     */
-    public final Uri nonTransactionalInsert(final Uri uri, final ContentValues values) {
-        if (isTemporary() && mSyncState.matches(uri)) {
-            Uri result = mSyncState.asContentProvider().insert(uri, values);
+            if (!isTemporary() && result > 0) {
+                if (notApplyingBatch) {
+                    getContext().getContentResolver().notifyChange(url, null /* observer */,
+                            changeRequiresLocalSync(url));
+                } else {
+                    mPendingBatchNotifications.get().add(url);
+                }
+            }
             return result;
+        } finally {
+            if (notApplyingBatch) {
+                mDb.endTransaction();
+            }
         }
-        Uri result = insertInternal(uri, values);
-        if (!isTemporary() && result != null) {
-            getContext().getContentResolver().notifyChange(uri, null /* observer */,
-                    changeRequiresLocalSync(uri));
+    }
+
+    @Override
+    public final int delete(final Uri url, final String selection,
+            final String[] selectionArgs) {
+        mDb = mOpenHelper.getWritableDatabase();
+        final boolean notApplyingBatch = !applyingBatch();
+        if (notApplyingBatch) {
+            mDb.beginTransaction();
         }
-        return result;
+        try {
+            if (isTemporary() && mSyncState.matches(url)) {
+                int numRows = mSyncState.asContentProvider().delete(url, selection, selectionArgs);
+                if (notApplyingBatch) {
+                    mDb.setTransactionSuccessful();
+                }
+                return numRows;
+            }
+            int result = deleteInternal(url, selection, selectionArgs);
+            if (notApplyingBatch) {
+                mDb.setTransactionSuccessful();
+            }
+            if (!isTemporary() && result > 0) {
+                if (notApplyingBatch) {
+                    getContext().getContentResolver().notifyChange(url, null /* observer */,
+                            changeRequiresLocalSync(url));
+                } else {
+                    mPendingBatchNotifications.get().add(url);
+                }
+            }
+            return result;
+        } finally {
+            if (notApplyingBatch) {
+                mDb.endTransaction();
+            }
+        }
+    }
+
+    private boolean applyingBatch() {
+        return mApplyingBatch.get() != null && mApplyingBatch.get();
+    }
+
+    @Override
+    public final Uri insert(final Uri url, final ContentValues values) {
+        mDb = mOpenHelper.getWritableDatabase();
+        final boolean notApplyingBatch = !applyingBatch();
+        if (notApplyingBatch) {
+            mDb.beginTransaction();
+        }
+        try {
+            if (isTemporary() && mSyncState.matches(url)) {
+                Uri result = mSyncState.asContentProvider().insert(url, values);
+                if (notApplyingBatch) {
+                    mDb.setTransactionSuccessful();
+                }
+                return result;
+            }
+            Uri result = insertInternal(url, values);
+            if (notApplyingBatch) {
+                mDb.setTransactionSuccessful();
+            }
+            if (!isTemporary() && result != null) {
+                if (notApplyingBatch) {
+                    getContext().getContentResolver().notifyChange(url, null /* observer */,
+                            changeRequiresLocalSync(url));
+                } else {
+                    mPendingBatchNotifications.get().add(url);
+                }
+            }
+            return result;
+        } finally {
+            if (notApplyingBatch) {
+                mDb.endTransaction();
+            }
+        }
     }
 
     @Override
@@ -411,6 +403,92 @@
     }
 
     /**
+     * <p>
+     * Start batch transaction. {@link #endTransaction} MUST be called after 
+     * calling this method. Those methods should be used like this:
+     * </p>
+     *
+     * <pre class="prettyprint">
+     * boolean successful = false;
+     * beginBatch()
+     * try {
+     *     // Do something related to mDb
+     *     successful = true;
+     *     return ret;
+     * } finally {
+     *     endBatch(successful);
+     * }
+     * </pre>
+     *
+     * @hide This method should be used only when {@link ContentProvider#applyBatch} is not enough and must be
+     * used with {@link #endBatch}.
+     * e.g. If returned value has to be used during one transaction, this method might be useful.
+     */
+    public final void beginBatch() {
+        // initialize if this is the first time this thread has applied a batch
+        if (mApplyingBatch.get() == null) {
+            mApplyingBatch.set(false);
+            mPendingBatchNotifications.set(new HashSet<Uri>());
+        }
+
+        if (applyingBatch()) {
+            throw new IllegalStateException(
+                    "applyBatch is not reentrant but mApplyingBatch is already set");
+        }
+        SQLiteDatabase db = getDatabase();
+        db.beginTransaction();
+        boolean successful = false;
+        try {
+            mApplyingBatch.set(true);
+            successful = true;
+        } finally {
+            if (!successful) {
+                // Something unexpected happened. We must call endTransaction() at least.
+                db.endTransaction();
+            }
+        }
+    }
+
+    /**
+     * <p>
+     * Finish batch transaction. If "successful" is true, try to call
+     * mDb.setTransactionSuccessful() before calling mDb.endTransaction().
+     * This method MUST be used with {@link #beginBatch()}.
+     * </p>
+     *
+     * @hide This method must be used with {@link #beginTransaction}
+     */
+    public final void endBatch(boolean successful) {
+        try {
+            if (successful) {
+                // setTransactionSuccessful() must be called just once during opening the
+                // transaction.
+                mDb.setTransactionSuccessful();
+            }
+        } finally {
+            mApplyingBatch.set(false);
+            getDatabase().endTransaction();
+            for (Uri url : mPendingBatchNotifications.get()) {
+                getContext().getContentResolver().notifyChange(url, null /* observer */,
+                        changeRequiresLocalSync(url));
+            }
+        }
+    }
+
+    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
+            throws OperationApplicationException {
+        boolean successful = false;
+        beginBatch();
+        try {
+            ContentProviderResult[] results = super.applyBatch(operations);
+            successful = true;
+            return results;
+        } finally {
+            endBatch(successful);
+        }
+    }
+
+    /**
      * Check if changes to this URI can be syncable changes.
      * @param uri the URI of the resource that was changed
      * @return true if changes to this URI can be syncable changes, false otherwise
@@ -437,8 +515,8 @@
      * @param context the sync context for the operation
      * @param account
      */
-    public void onSyncStart(SyncContext context, String account) {
-        if (TextUtils.isEmpty(account)) {
+    public void onSyncStart(SyncContext context, Account account) {
+        if (account == null) {
             throw new IllegalArgumentException("you passed in an empty account");
         }
         mSyncingAccount = account;
@@ -457,7 +535,7 @@
      * The account of the most recent call to onSyncStart()
      * @return the account
      */
-    public String getSyncingAccount() {
+    public Account getSyncingAccount() {
         return mSyncingAccount;
     }
 
@@ -568,12 +646,11 @@
      * Make sure that there are no entries for accounts that no longer exist
      * @param accountsArray the array of currently-existing accounts
      */
-    protected void onAccountsChanged(String[] accountsArray) {
-        Map<String, Boolean> accounts = new HashMap<String, Boolean>();
-        for (String account : accountsArray) {
+    protected void onAccountsChanged(Account[] accountsArray) {
+        Map<Account, Boolean> accounts = Maps.newHashMap();
+        for (Account account : accountsArray) {
             accounts.put(account, false);
         }
-        accounts.put(SyncConstValue.NON_SYNCABLE_ACCOUNT, false);
 
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
         Map<String, String> tableMap = db.getSyncedTables();
@@ -585,8 +662,7 @@
         try {
             mSyncState.onAccountsChanged(accountsArray);
             for (String table : tables) {
-                deleteRowsForRemovedAccounts(accounts, table,
-                        SyncConstValue._SYNC_ACCOUNT);
+                deleteRowsForRemovedAccounts(accounts, table);
             }
             db.setTransactionSuccessful();
         } finally {
@@ -601,23 +677,23 @@
      *
      * @param accounts a map of existing accounts
      * @param table the table to delete from
-     * @param accountColumnName the name of the column that is expected
-     * to hold the account.
      */
-    protected void deleteRowsForRemovedAccounts(Map<String, Boolean> accounts,
-            String table, String accountColumnName) {
+    protected void deleteRowsForRemovedAccounts(Map<Account, Boolean> accounts, String table) {
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
         Cursor c = db.query(table, sAccountProjection, null, null,
-                accountColumnName, null, null);
+                "_sync_account, _sync_account_type", null, null);
         try {
             while (c.moveToNext()) {
-                String account = c.getString(0);
-                if (TextUtils.isEmpty(account)) {
+                String accountName = c.getString(0);
+                String accountType = c.getString(1);
+                if (TextUtils.isEmpty(accountName)) {
                     continue;
                 }
+                Account account = new Account(accountName, accountType);
                 if (!accounts.containsKey(account)) {
                     int numDeleted;
-                    numDeleted = db.delete(table, accountColumnName + "=?", new String[]{account});
+                    numDeleted = db.delete(table, "_sync_account=? AND _sync_account_type=?",
+                            new String[]{account.mName, account.mType});
                     if (Config.LOGV) {
                         Log.v(TAG, "deleted " + numDeleted
                                 + " records from table " + table
@@ -634,7 +710,7 @@
      * Called when the sync system determines that this provider should no longer
      * contain records for the specified account.
      */
-    public void wipeAccount(String account) {
+    public void wipeAccount(Account account) {
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
         Map<String, String> tableMap = db.getSyncedTables();
         ArrayList<String> tables = new ArrayList<String>();
@@ -649,7 +725,8 @@
 
             // remove the data in the synced tables
             for (String table : tables) {
-                db.delete(table, SYNC_ACCOUNT_WHERE_CLAUSE, new String[]{account});
+                db.delete(table, SYNC_ACCOUNT_WHERE_CLAUSE,
+                        new String[]{account.mName, account.mType});
             }
             db.setTransactionSuccessful();
         } finally {
@@ -660,14 +737,14 @@
     /**
      * Retrieves the SyncData bytes for the given account. The byte array returned may be null.
      */
-    public byte[] readSyncDataBytes(String account) {
+    public byte[] readSyncDataBytes(Account account) {
         return mSyncState.readSyncDataBytes(mOpenHelper.getReadableDatabase(), account);
     }
 
     /**
      * Sets the SyncData bytes for the given account. The byte array may be null.
      */
-    public void writeSyncDataBytes(String account, byte[] data) {
+    public void writeSyncDataBytes(Account account, byte[] data) {
         mSyncState.writeSyncDataBytes(mOpenHelper.getWritableDatabase(), account, data);
     }
 }
diff --git a/core/java/android/content/AbstractTableMerger.java b/core/java/android/content/AbstractTableMerger.java
index 9f609a3..a3daa01 100644
--- a/core/java/android/content/AbstractTableMerger.java
+++ b/core/java/android/content/AbstractTableMerger.java
@@ -25,6 +25,7 @@
 import static android.provider.SyncConstValue.*;
 import android.text.TextUtils;
 import android.util.Log;
+import android.accounts.Account;
 
 /**
  * @hide
@@ -55,15 +56,17 @@
 
     private volatile boolean mIsMergeCancelled;
 
-    private static final String SELECT_MARKED = _SYNC_MARK + "> 0 and " + _SYNC_ACCOUNT + "=?";
+    private static final String SELECT_MARKED = _SYNC_MARK + "> 0 and "
+            + _SYNC_ACCOUNT + "=? and " + _SYNC_ACCOUNT_TYPE + "=?";
 
     private static final String SELECT_BY_SYNC_ID_AND_ACCOUNT =
-            _SYNC_ID +"=? and " + _SYNC_ACCOUNT + "=?";
+            _SYNC_ID +"=? and " + _SYNC_ACCOUNT + "=? and " + _SYNC_ACCOUNT_TYPE + "=?";
     private static final String SELECT_BY_ID = BaseColumns._ID +"=?";
 
     private static final String SELECT_UNSYNCED =
-            "(" + _SYNC_ACCOUNT + " IS NULL OR " + _SYNC_ACCOUNT + "=?) AND "
-            + "(" + _SYNC_ID + " IS NULL OR (" + _SYNC_DIRTY + " > 0 AND "
+            "(" + _SYNC_ACCOUNT + " IS NULL OR ("
+                + _SYNC_ACCOUNT + "=? and " + _SYNC_ACCOUNT_TYPE + "=?)) and "
+            + "(" + _SYNC_ID + " IS NULL OR (" + _SYNC_DIRTY + " > 0 and "
                                               + _SYNC_VERSION + " IS NOT NULL))";
 
     public AbstractTableMerger(SQLiteDatabase database,
@@ -134,7 +137,7 @@
      * construct a temporary instance to hold them.
      */
     public void merge(final SyncContext context,
-            final String account,
+            final Account account,
             final SyncableContentProvider serverDiffs,
             TempProviderSyncResult result,
             SyncResult syncResult, SyncableContentProvider temporaryInstanceFactory) {
@@ -157,7 +160,7 @@
      * @hide this is public for testing purposes only
      */
     public void mergeServerDiffs(SyncContext context,
-            String account, SyncableContentProvider serverDiffs, SyncResult syncResult) {
+            Account account, SyncableContentProvider serverDiffs, SyncResult syncResult) {
         boolean diffsArePartial = serverDiffs.getContainsDiffs();
         // mark the current rows so that we can distinguish these from new
         // inserts that occur during the merge
@@ -166,342 +169,340 @@
             mDb.update(mDeletedTable, mSyncMarkValues, null, null);
         }
 
-        // load the local database entries, so we can merge them with the server
-        final String[] accountSelectionArgs = new String[]{account};
-        Cursor localCursor = mDb.query(mTable, syncDirtyProjection,
-                SELECT_MARKED, accountSelectionArgs, null, null,
-                mTable + "." + _SYNC_ID);
-        Cursor deletedCursor;
-        if (mDeletedTable != null) {
-            deletedCursor = mDb.query(mDeletedTable, syncIdAndVersionProjection,
+        Cursor localCursor = null;
+        Cursor deletedCursor = null;
+        Cursor diffsCursor = null;
+        try {
+            // load the local database entries, so we can merge them with the server
+            final String[] accountSelectionArgs = new String[]{account.mName, account.mType};
+            localCursor = mDb.query(mTable, syncDirtyProjection,
                     SELECT_MARKED, accountSelectionArgs, null, null,
-                    mDeletedTable + "." + _SYNC_ID);
-        } else {
-            deletedCursor =
-                    mDb.rawQuery("select 'a' as _sync_id, 'b' as _sync_version limit 0", null);
-        }
-
-        // Apply updates and insertions from the server
-        Cursor diffsCursor = serverDiffs.query(mTableURL,
-                null, null, null, mTable + "." + _SYNC_ID);
-        int deletedSyncIDColumn = deletedCursor.getColumnIndexOrThrow(_SYNC_ID);
-        int deletedSyncVersionColumn = deletedCursor.getColumnIndexOrThrow(_SYNC_VERSION);
-        int serverSyncIDColumn = diffsCursor.getColumnIndexOrThrow(_SYNC_ID);
-        int serverSyncVersionColumn = diffsCursor.getColumnIndexOrThrow(_SYNC_VERSION);
-        int serverSyncLocalIdColumn = diffsCursor.getColumnIndexOrThrow(_SYNC_LOCAL_ID);
-
-        String lastSyncId = null;
-        int diffsCount = 0;
-        int localCount = 0;
-        localCursor.moveToFirst();
-        deletedCursor.moveToFirst();
-        while (diffsCursor.moveToNext()) {
-            if (mIsMergeCancelled) {
-                localCursor.close();
-                deletedCursor.close();
-                diffsCursor.close();
-                return;
-            }
-            mDb.yieldIfContended();
-            String serverSyncId = diffsCursor.getString(serverSyncIDColumn);
-            String serverSyncVersion = diffsCursor.getString(serverSyncVersionColumn);
-            long localRowId = 0;
-            String localSyncVersion = null;
-
-            diffsCount++;
-            context.setStatusText("Processing " + diffsCount + "/"
-                    + diffsCursor.getCount());
-            if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "processing server entry " +
-                    diffsCount + ", " + serverSyncId);
-
-            if (TRACE) {
-                if (diffsCount == 10) {
-                    Debug.startMethodTracing("atmtrace");
-                }
-                if (diffsCount == 20) {
-                    Debug.stopMethodTracing();
-                }
+                    mTable + "." + _SYNC_ID);
+            if (mDeletedTable != null) {
+                deletedCursor = mDb.query(mDeletedTable, syncIdAndVersionProjection,
+                        SELECT_MARKED, accountSelectionArgs, null, null,
+                        mDeletedTable + "." + _SYNC_ID);
+            } else {
+                deletedCursor =
+                        mDb.rawQuery("select 'a' as _sync_id, 'b' as _sync_version limit 0", null);
             }
 
-            boolean conflict = false;
-            boolean update = false;
-            boolean insert = false;
+            // Apply updates and insertions from the server
+            diffsCursor = serverDiffs.query(mTableURL,
+                    null, null, null, mTable + "." + _SYNC_ID);
+            int deletedSyncIDColumn = deletedCursor.getColumnIndexOrThrow(_SYNC_ID);
+            int deletedSyncVersionColumn = deletedCursor.getColumnIndexOrThrow(_SYNC_VERSION);
+            int serverSyncIDColumn = diffsCursor.getColumnIndexOrThrow(_SYNC_ID);
+            int serverSyncVersionColumn = diffsCursor.getColumnIndexOrThrow(_SYNC_VERSION);
+            int serverSyncLocalIdColumn = diffsCursor.getColumnIndexOrThrow(_SYNC_LOCAL_ID);
 
-            if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                Log.v(TAG, "found event with serverSyncID " + serverSyncId);
-            }
-            if (TextUtils.isEmpty(serverSyncId)) {
-                if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                    Log.e(TAG, "server entry doesn't have a serverSyncID");
-                }
-                continue;
-            }
-
-            // It is possible that the sync adapter wrote the same record multiple times,
-            // e.g. if the same record came via multiple feeds. If this happens just ignore
-            // the duplicate records.
-            if (serverSyncId.equals(lastSyncId)) {
-                if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                    Log.v(TAG, "skipping record with duplicate remote server id " + lastSyncId);
-                }
-                continue;
-            }
-            lastSyncId = serverSyncId;
-
-            String localSyncID = null;
-            boolean localSyncDirty = false;
-
-            while (!localCursor.isAfterLast()) {
+            String lastSyncId = null;
+            int diffsCount = 0;
+            int localCount = 0;
+            localCursor.moveToFirst();
+            deletedCursor.moveToFirst();
+            while (diffsCursor.moveToNext()) {
                 if (mIsMergeCancelled) {
-                    localCursor.deactivate();
-                    deletedCursor.deactivate();
-                    diffsCursor.deactivate();
                     return;
                 }
-                localCount++;
-                localSyncID = localCursor.getString(2);
+                mDb.yieldIfContended();
+                String serverSyncId = diffsCursor.getString(serverSyncIDColumn);
+                String serverSyncVersion = diffsCursor.getString(serverSyncVersionColumn);
+                long localRowId = 0;
+                String localSyncVersion = null;
 
-                // If the local record doesn't have a _sync_id then
-                // it is new. Ignore it for now, we will send an insert
-                // the the server later.
-                if (TextUtils.isEmpty(localSyncID)) {
-                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                        Log.v(TAG, "local record " +
-                                localCursor.getLong(1) +
-                                " has no _sync_id, ignoring");
+                diffsCount++;
+                context.setStatusText("Processing " + diffsCount + "/"
+                        + diffsCursor.getCount());
+                if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "processing server entry " +
+                        diffsCount + ", " + serverSyncId);
+
+                if (TRACE) {
+                    if (diffsCount == 10) {
+                        Debug.startMethodTracing("atmtrace");
                     }
-                    localCursor.moveToNext();
-                    localSyncID = null;
+                    if (diffsCount == 20) {
+                        Debug.stopMethodTracing();
+                    }
+                }
+
+                boolean conflict = false;
+                boolean update = false;
+                boolean insert = false;
+
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "found event with serverSyncID " + serverSyncId);
+                }
+                if (TextUtils.isEmpty(serverSyncId)) {
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.e(TAG, "server entry doesn't have a serverSyncID");
+                    }
                     continue;
                 }
 
-                int comp = serverSyncId.compareTo(localSyncID);
-
-                // the local DB has a record that the server doesn't have
-                if (comp > 0) {
+                // It is possible that the sync adapter wrote the same record multiple times,
+                // e.g. if the same record came via multiple feeds. If this happens just ignore
+                // the duplicate records.
+                if (serverSyncId.equals(lastSyncId)) {
                     if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                        Log.v(TAG, "local record " +
-                                localCursor.getLong(1) +
-                                " has _sync_id " + localSyncID +
-                                " that is < server _sync_id " + serverSyncId);
+                        Log.v(TAG, "skipping record with duplicate remote server id " + lastSyncId);
                     }
-                    if (diffsArePartial) {
-                        localCursor.moveToNext();
-                    } else {
-                        deleteRow(localCursor);
-                        if (mDeletedTable != null) {
-                            mDb.delete(mDeletedTable, _SYNC_ID +"=?", new String[] {localSyncID});
-                        }
-                        syncResult.stats.numDeletes++;
-                        mDb.yieldIfContended();
-                    }
-                    localSyncID = null;
                     continue;
                 }
+                lastSyncId = serverSyncId;
 
-                // the server has a record that the local DB doesn't have
-                if (comp < 0) {
-                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                        Log.v(TAG, "local record " +
-                                localCursor.getLong(1) +
-                                " has _sync_id " + localSyncID +
-                                " that is > server _sync_id " + serverSyncId);
+                String localSyncID = null;
+                boolean localSyncDirty = false;
+
+                while (!localCursor.isAfterLast()) {
+                    if (mIsMergeCancelled) {
+                        return;
                     }
-                    localSyncID = null;
-                }
+                    localCount++;
+                    localSyncID = localCursor.getString(2);
 
-                // the server and the local DB both have this record
-                if (comp == 0) {
-                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                        Log.v(TAG, "local record " +
-                                localCursor.getLong(1) +
-                                " has _sync_id " + localSyncID +
-                                " that matches the server _sync_id");
-                    }
-                    localSyncDirty = localCursor.getInt(0) != 0;
-                    localRowId = localCursor.getLong(1);
-                    localSyncVersion = localCursor.getString(3);
-                    localCursor.moveToNext();
-                }
-
-                break;
-            }
-
-            // If this record is in the deleted table then update the server version
-            // in the deleted table, if necessary, and then ignore it here.
-            // We will send a deletion indication to the server down a
-            // little further.
-            if (findInCursor(deletedCursor, deletedSyncIDColumn, serverSyncId)) {
-                if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                    Log.v(TAG, "remote record " + serverSyncId + " is in the deleted table");
-                }
-                final String deletedSyncVersion = deletedCursor.getString(deletedSyncVersionColumn);
-                if (!TextUtils.equals(deletedSyncVersion, serverSyncVersion)) {
-                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                        Log.v(TAG, "setting version of deleted record " + serverSyncId + " to "
-                                + serverSyncVersion);
-                    }
-                    ContentValues values = new ContentValues();
-                    values.put(_SYNC_VERSION, serverSyncVersion);
-                    mDb.update(mDeletedTable, values, "_sync_id=?", new String[]{serverSyncId});
-                }
-                continue;
-            }
-
-            // If the _sync_local_id is present in the diffsCursor
-            // then this record corresponds to a local record that was just
-            // inserted into the server and the _sync_local_id is the row id
-            // of the local record. Set these fields so that the next check
-            // treats this record as an update, which will allow the
-            // merger to update the record with the server's sync id
-            if (!diffsCursor.isNull(serverSyncLocalIdColumn)) {
-                localRowId = diffsCursor.getLong(serverSyncLocalIdColumn);
-                if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                    Log.v(TAG, "the remote record with sync id " + serverSyncId
-                            + " has a local sync id, " + localRowId);
-                }
-                localSyncID = serverSyncId;
-                localSyncDirty = false;
-                localSyncVersion = null;
-            }
-
-            if (!TextUtils.isEmpty(localSyncID)) {
-                // An existing server item has changed
-                // If serverSyncVersion is null, there is no edit URL;
-                // server won't let this change be written.
-                boolean recordChanged = (localSyncVersion == null) ||
-                        (serverSyncVersion == null) ||
-                        !serverSyncVersion.equals(localSyncVersion);
-                if (recordChanged) {
-                    if (localSyncDirty) {
+                    // If the local record doesn't have a _sync_id then
+                    // it is new. Ignore it for now, we will send an insert
+                    // the the server later.
+                    if (TextUtils.isEmpty(localSyncID)) {
                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                            Log.v(TAG, "remote record " + serverSyncId
-                                    + " conflicts with local _sync_id " + localSyncID
-                                    + ", local _id " + localRowId);
+                            Log.v(TAG, "local record " +
+                                    localCursor.getLong(1) +
+                                    " has no _sync_id, ignoring");
                         }
-                        conflict = true;
+                        localCursor.moveToNext();
+                        localSyncID = null;
+                        continue;
+                    }
+
+                    int comp = serverSyncId.compareTo(localSyncID);
+
+                    // the local DB has a record that the server doesn't have
+                    if (comp > 0) {
+                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                            Log.v(TAG, "local record " +
+                                    localCursor.getLong(1) +
+                                    " has _sync_id " + localSyncID +
+                                    " that is < server _sync_id " + serverSyncId);
+                        }
+                        if (diffsArePartial) {
+                            localCursor.moveToNext();
+                        } else {
+                            deleteRow(localCursor);
+                            if (mDeletedTable != null) {
+                                mDb.delete(mDeletedTable, _SYNC_ID +"=?", new String[] {localSyncID});
+                            }
+                            syncResult.stats.numDeletes++;
+                            mDb.yieldIfContended();
+                        }
+                        localSyncID = null;
+                        continue;
+                    }
+
+                    // the server has a record that the local DB doesn't have
+                    if (comp < 0) {
+                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                            Log.v(TAG, "local record " +
+                                    localCursor.getLong(1) +
+                                    " has _sync_id " + localSyncID +
+                                    " that is > server _sync_id " + serverSyncId);
+                        }
+                        localSyncID = null;
+                    }
+
+                    // the server and the local DB both have this record
+                    if (comp == 0) {
+                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                            Log.v(TAG, "local record " +
+                                    localCursor.getLong(1) +
+                                    " has _sync_id " + localSyncID +
+                                    " that matches the server _sync_id");
+                        }
+                        localSyncDirty = localCursor.getInt(0) != 0;
+                        localRowId = localCursor.getLong(1);
+                        localSyncVersion = localCursor.getString(3);
+                        localCursor.moveToNext();
+                    }
+
+                    break;
+                }
+
+                // If this record is in the deleted table then update the server version
+                // in the deleted table, if necessary, and then ignore it here.
+                // We will send a deletion indication to the server down a
+                // little further.
+                if (findInCursor(deletedCursor, deletedSyncIDColumn, serverSyncId)) {
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "remote record " + serverSyncId + " is in the deleted table");
+                    }
+                    final String deletedSyncVersion = deletedCursor.getString(deletedSyncVersionColumn);
+                    if (!TextUtils.equals(deletedSyncVersion, serverSyncVersion)) {
+                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                            Log.v(TAG, "setting version of deleted record " + serverSyncId + " to "
+                                    + serverSyncVersion);
+                        }
+                        ContentValues values = new ContentValues();
+                        values.put(_SYNC_VERSION, serverSyncVersion);
+                        mDb.update(mDeletedTable, values, "_sync_id=?", new String[]{serverSyncId});
+                    }
+                    continue;
+                }
+
+                // If the _sync_local_id is present in the diffsCursor
+                // then this record corresponds to a local record that was just
+                // inserted into the server and the _sync_local_id is the row id
+                // of the local record. Set these fields so that the next check
+                // treats this record as an update, which will allow the
+                // merger to update the record with the server's sync id
+                if (!diffsCursor.isNull(serverSyncLocalIdColumn)) {
+                    localRowId = diffsCursor.getLong(serverSyncLocalIdColumn);
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "the remote record with sync id " + serverSyncId
+                                + " has a local sync id, " + localRowId);
+                    }
+                    localSyncID = serverSyncId;
+                    localSyncDirty = false;
+                    localSyncVersion = null;
+                }
+
+                if (!TextUtils.isEmpty(localSyncID)) {
+                    // An existing server item has changed
+                    // If serverSyncVersion is null, there is no edit URL;
+                    // server won't let this change be written.
+                    boolean recordChanged = (localSyncVersion == null) ||
+                            (serverSyncVersion == null) ||
+                            !serverSyncVersion.equals(localSyncVersion);
+                    if (recordChanged) {
+                        if (localSyncDirty) {
+                            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                                Log.v(TAG, "remote record " + serverSyncId
+                                        + " conflicts with local _sync_id " + localSyncID
+                                        + ", local _id " + localRowId);
+                            }
+                            conflict = true;
+                        } else {
+                            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                                Log.v(TAG,
+                                        "remote record " +
+                                                serverSyncId +
+                                                " updates local _sync_id " +
+                                                localSyncID + ", local _id " +
+                                                localRowId);
+                            }
+                            update = true;
+                        }
                     } else {
                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
                             Log.v(TAG,
-                                    "remote record " +
-                                            serverSyncId +
-                                            " updates local _sync_id " +
-                                            localSyncID + ", local _id " +
-                                            localRowId);
+                                    "Skipping update: localSyncVersion: " + localSyncVersion +
+                                    ", serverSyncVersion: " + serverSyncVersion);
                         }
-                        update = true;
                     }
                 } else {
+                    // the local db doesn't know about this record so add it
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "remote record " + serverSyncId + " is new, inserting");
+                    }
+                    insert = true;
+                }
+
+                if (update) {
+                    updateRow(localRowId, serverDiffs, diffsCursor);
+                    syncResult.stats.numUpdates++;
+                } else if (conflict) {
+                    resolveRow(localRowId, serverSyncId, serverDiffs, diffsCursor);
+                    syncResult.stats.numUpdates++;
+                } else if (insert) {
+                    insertRow(serverDiffs, diffsCursor);
+                    syncResult.stats.numInserts++;
+                }
+            }
+
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "processed " + diffsCount + " server entries");
+            }
+
+            // If tombstones aren't in use delete any remaining local rows that
+            // don't have corresponding server rows. Keep the rows that don't
+            // have a sync id since those were created locally and haven't been
+            // synced to the server yet.
+            if (!diffsArePartial) {
+                while (!localCursor.isAfterLast() && !TextUtils.isEmpty(localCursor.getString(2))) {
+                    if (mIsMergeCancelled) {
+                        return;
+                    }
+                    localCount++;
+                    final String localSyncId = localCursor.getString(2);
                     if (Log.isLoggable(TAG, Log.VERBOSE)) {
                         Log.v(TAG,
-                                "Skipping update: localSyncVersion: " + localSyncVersion +
-                                ", serverSyncVersion: " + serverSyncVersion);
+                                "deleting local record " +
+                                        localCursor.getLong(1) +
+                                        " _sync_id " + localSyncId);
                     }
+                    deleteRow(localCursor);
+                    if (mDeletedTable != null) {
+                        mDb.delete(mDeletedTable, _SYNC_ID + "=?", new String[] {localSyncId});
+                    }
+                    syncResult.stats.numDeletes++;
+                    mDb.yieldIfContended();
                 }
-            } else {
-                // the local db doesn't know about this record so add it
-                if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                    Log.v(TAG, "remote record " + serverSyncId + " is new, inserting");
-                }
-                insert = true;
             }
-
-            if (update) {
-                updateRow(localRowId, serverDiffs, diffsCursor);
-                syncResult.stats.numUpdates++;
-            } else if (conflict) {
-                resolveRow(localRowId, serverSyncId, serverDiffs, diffsCursor);
-                syncResult.stats.numUpdates++;
-            } else if (insert) {
-                insertRow(serverDiffs, diffsCursor);
-                syncResult.stats.numInserts++;
-            }
+            if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "checked " + localCount +
+                    " local entries");
+        } finally {
+            if (diffsCursor != null) diffsCursor.close();
+            if (localCursor != null) localCursor.close();
+            if (deletedCursor != null) deletedCursor.close();
         }
 
-        if (Log.isLoggable(TAG, Log.VERBOSE)) {
-            Log.v(TAG, "processed " + diffsCount + " server entries");
-        }
-
-        // If tombstones aren't in use delete any remaining local rows that
-        // don't have corresponding server rows. Keep the rows that don't
-        // have a sync id since those were created locally and haven't been
-        // synced to the server yet.
-        if (!diffsArePartial) {
-            while (!localCursor.isAfterLast() && !TextUtils.isEmpty(localCursor.getString(2))) {
-                if (mIsMergeCancelled) {
-                    localCursor.deactivate();
-                    deletedCursor.deactivate();
-                    diffsCursor.deactivate();
-                    return;
-                }
-                localCount++;
-                final String localSyncId = localCursor.getString(2);
-                if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                    Log.v(TAG,
-                            "deleting local record " +
-                                    localCursor.getLong(1) +
-                                    " _sync_id " + localSyncId);
-                }
-                deleteRow(localCursor);
-                if (mDeletedTable != null) {
-                    mDb.delete(mDeletedTable, _SYNC_ID + "=?", new String[] {localSyncId});
-                }
-                syncResult.stats.numDeletes++;
-                mDb.yieldIfContended();
-            }
-        }
-
-        if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "checked " + localCount +
-                " local entries");
-        diffsCursor.deactivate();
-        localCursor.deactivate();
-        deletedCursor.deactivate();
 
         if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "applying deletions from the server");
 
         // Apply deletions from the server
         if (mDeletedTableURL != null) {
             diffsCursor = serverDiffs.query(mDeletedTableURL, null, null, null, null);
-
-            while (diffsCursor.moveToNext()) {
-                if (mIsMergeCancelled) {
-                    diffsCursor.deactivate();
-                    return;
+            try {
+                while (diffsCursor.moveToNext()) {
+                    if (mIsMergeCancelled) {
+                        return;
+                    }
+                    // delete all rows that match each element in the diffsCursor
+                    fullyDeleteMatchingRows(diffsCursor, account, syncResult);
+                    mDb.yieldIfContended();
                 }
-                // delete all rows that match each element in the diffsCursor
-                fullyDeleteMatchingRows(diffsCursor, account, syncResult);
-                mDb.yieldIfContended();
+            } finally {
+                diffsCursor.close();
             }
-            diffsCursor.deactivate();
         }
     }
 
-    private void fullyDeleteMatchingRows(Cursor diffsCursor, String account,
+    private void fullyDeleteMatchingRows(Cursor diffsCursor, Account account,
             SyncResult syncResult) {
         int serverSyncIdColumn = diffsCursor.getColumnIndexOrThrow(_SYNC_ID);
         final boolean deleteBySyncId = !diffsCursor.isNull(serverSyncIdColumn);
 
         // delete the rows explicitly so that the delete operation can be overridden
-        final Cursor c;
         final String[] selectionArgs;
-        if (deleteBySyncId) {
-            selectionArgs = new String[]{diffsCursor.getString(serverSyncIdColumn), account};
-            c = mDb.query(mTable, new String[]{BaseColumns._ID}, SELECT_BY_SYNC_ID_AND_ACCOUNT,
-                    selectionArgs, null, null, null);
-        } else {
-            int serverSyncLocalIdColumn = diffsCursor.getColumnIndexOrThrow(_SYNC_LOCAL_ID);
-            selectionArgs = new String[]{diffsCursor.getString(serverSyncLocalIdColumn)};
-            c = mDb.query(mTable, new String[]{BaseColumns._ID}, SELECT_BY_ID, selectionArgs,
-                    null, null, null);
-        }
+        Cursor c = null;
         try {
+            if (deleteBySyncId) {
+                selectionArgs = new String[]{diffsCursor.getString(serverSyncIdColumn),
+                        account.mName, account.mType};
+                c = mDb.query(mTable, new String[]{BaseColumns._ID}, SELECT_BY_SYNC_ID_AND_ACCOUNT,
+                        selectionArgs, null, null, null);
+            } else {
+                int serverSyncLocalIdColumn = diffsCursor.getColumnIndexOrThrow(_SYNC_LOCAL_ID);
+                selectionArgs = new String[]{diffsCursor.getString(serverSyncLocalIdColumn)};
+                c = mDb.query(mTable, new String[]{BaseColumns._ID}, SELECT_BY_ID, selectionArgs,
+                        null, null, null);
+            }
             c.moveToFirst();
             while (!c.isAfterLast()) {
                 deleteRow(c); // advances the cursor
                 syncResult.stats.numDeletes++;
             }
         } finally {
-            c.deactivate();
+          if (c != null) c.close();
         }
         if (deleteBySyncId && mDeletedTable != null) {
             mDb.delete(mDeletedTable, SELECT_BY_SYNC_ID_AND_ACCOUNT, selectionArgs);
@@ -519,43 +520,46 @@
      * Finds local changes, placing the results in the given result object.
      * @param temporaryInstanceFactory As an optimization for the case
      * where there are no client-side diffs, mergeResult may initially
-     * have no {@link android.content.TempProviderSyncResult#tempContentProvider}.  If this is
+     * have no {@link TempProviderSyncResult#tempContentProvider}.  If this is
      * the first in the sequence of AbstractTableMergers to find
      * client-side diffs, it will use the given ContentProvider to
      * create a temporary instance and store its {@link
-     * ContentProvider} in the mergeResult.
+     * android.content.ContentProvider} in the mergeResult.
      * @param account
      * @param syncResult
      */
     private void findLocalChanges(TempProviderSyncResult mergeResult,
-            SyncableContentProvider temporaryInstanceFactory, String account,
+            SyncableContentProvider temporaryInstanceFactory, Account account,
             SyncResult syncResult) {
         SyncableContentProvider clientDiffs = mergeResult.tempContentProvider;
         if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "generating client updates");
 
-        final String[] accountSelectionArgs = new String[]{account};
+        final String[] accountSelectionArgs = new String[]{account.mName, account.mType};
 
         // Generate the client updates and insertions
         // Create a cursor for dirty records
+        long numInsertsOrUpdates = 0;
         Cursor localChangesCursor = mDb.query(mTable, null, SELECT_UNSYNCED, accountSelectionArgs,
                 null, null, null);
-        long numInsertsOrUpdates = localChangesCursor.getCount();
-        while (localChangesCursor.moveToNext()) {
-            if (mIsMergeCancelled) {
-                localChangesCursor.close();
-                return;
+        try {
+            numInsertsOrUpdates = localChangesCursor.getCount();
+            while (localChangesCursor.moveToNext()) {
+                if (mIsMergeCancelled) {
+                    return;
+                }
+                if (clientDiffs == null) {
+                    clientDiffs = temporaryInstanceFactory.getTemporaryInstance();
+                }
+                mValues.clear();
+                cursorRowToContentValues(localChangesCursor, mValues);
+                mValues.remove("_id");
+                DatabaseUtils.cursorLongToContentValues(localChangesCursor, "_id", mValues,
+                        _SYNC_LOCAL_ID);
+                clientDiffs.insert(mTableURL, mValues);
             }
-            if (clientDiffs == null) {
-                clientDiffs = temporaryInstanceFactory.getTemporaryInstance();
-            }
-            mValues.clear();
-            cursorRowToContentValues(localChangesCursor, mValues);
-            mValues.remove("_id");
-            DatabaseUtils.cursorLongToContentValues(localChangesCursor, "_id", mValues,
-                    _SYNC_LOCAL_ID);
-            clientDiffs.insert(mTableURL, mValues);
+        } finally {
+          localChangesCursor.close();
         }
-        localChangesCursor.close();
 
         // Generate the client deletions
         if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "generating client deletions");
@@ -564,23 +568,25 @@
         if (mDeletedTable != null) {
             Cursor deletedCursor = mDb.query(mDeletedTable,
                     syncIdAndVersionProjection,
-                    _SYNC_ACCOUNT + "=? AND " + _SYNC_ID + " IS NOT NULL", accountSelectionArgs,
+                    _SYNC_ACCOUNT + "=? AND " + _SYNC_ACCOUNT_TYPE + "=? AND "
+                            + _SYNC_ID + " IS NOT NULL", accountSelectionArgs,
                     null, null, mDeletedTable + "." + _SYNC_ID);
-
-            numDeletedEntries = deletedCursor.getCount();
-            while (deletedCursor.moveToNext()) {
-                if (mIsMergeCancelled) {
-                    deletedCursor.close();
-                    return;
+            try {
+                numDeletedEntries = deletedCursor.getCount();
+                while (deletedCursor.moveToNext()) {
+                    if (mIsMergeCancelled) {
+                        return;
+                    }
+                    if (clientDiffs == null) {
+                        clientDiffs = temporaryInstanceFactory.getTemporaryInstance();
+                    }
+                    mValues.clear();
+                    DatabaseUtils.cursorRowToContentValues(deletedCursor, mValues);
+                    clientDiffs.insert(mDeletedTableURL, mValues);
                 }
-                if (clientDiffs == null) {
-                    clientDiffs = temporaryInstanceFactory.getTemporaryInstance();
-                }
-                mValues.clear();
-                DatabaseUtils.cursorRowToContentValues(deletedCursor, mValues);
-                clientDiffs.insert(mDeletedTableURL, mValues);
+            } finally {
+                deletedCursor.close();
             }
-            deletedCursor.close();
         }
 
         if (clientDiffs != null) {
diff --git a/core/java/android/content/AbstractThreadedSyncAdapter.java b/core/java/android/content/AbstractThreadedSyncAdapter.java
new file mode 100644
index 0000000..f15a902
--- /dev/null
+++ b/core/java/android/content/AbstractThreadedSyncAdapter.java
@@ -0,0 +1,176 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+import android.accounts.Account;
+import android.os.Bundle;
+import android.os.Process;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * An abstract implementation of a SyncAdapter that spawns a thread to invoke a sync operation.
+ * If a sync operation is already in progress when a startSync() request is received then an error
+ * will be returned to the new request and the existing request will be allowed to continue.
+ * When a startSync() is received and there is no sync operation in progress then a thread
+ * will be started to run the operation and {@link #performSync} will be invoked on that thread.
+ * If a cancelSync() is received that matches an existing sync operation then the thread
+ * that is running that sync operation will be interrupted, which will indicate to the thread
+ * that the sync has been canceled.
+ *
+ * @hide
+ */
+public abstract class AbstractThreadedSyncAdapter {
+    private final Context mContext;
+    private final AtomicInteger mNumSyncStarts;
+    private final ISyncAdapterImpl mISyncAdapterImpl;
+
+    // all accesses to this member variable must be synchronized on "this"
+    private SyncThread mSyncThread;
+
+    /** Kernel event log tag.  Also listed in data/etc/event-log-tags. */
+    public static final int LOG_SYNC_DETAILS = 2743;
+
+    /**
+     * Creates an {@link AbstractThreadedSyncAdapter}.
+     * @param context the {@link Context} that this is running within.
+     */
+    public AbstractThreadedSyncAdapter(Context context) {
+        mContext = context;
+        mISyncAdapterImpl = new ISyncAdapterImpl();
+        mNumSyncStarts = new AtomicInteger(0);
+        mSyncThread = null;
+    }
+
+    class ISyncAdapterImpl extends ISyncAdapter.Stub {
+        public void startSync(ISyncContext syncContext, String authority, Account account,
+                Bundle extras) {
+            final SyncContext syncContextClient = new SyncContext(syncContext);
+
+            boolean alreadyInProgress;
+            // synchronize to make sure that mSyncThread doesn't change between when we
+            // check it and when we use it
+            synchronized (this) {
+                if (mSyncThread == null) {
+                    mSyncThread = new SyncThread(
+                            "SyncAdapterThread-" + mNumSyncStarts.incrementAndGet(),
+                            syncContextClient, authority, account, extras);
+                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
+                    mSyncThread.start();
+                    alreadyInProgress = false;
+                } else {
+                    alreadyInProgress = true;
+                }
+            }
+
+            // do this outside since we don't want to call back into the syncContext while
+            // holding the synchronization lock
+            if (alreadyInProgress) {
+                syncContextClient.onFinished(SyncResult.ALREADY_IN_PROGRESS);
+            }
+        }
+
+        public void cancelSync(ISyncContext syncContext) {
+            // synchronize to make sure that mSyncThread doesn't change between when we
+            // check it and when we use it
+            synchronized (this) {
+                if (mSyncThread != null
+                        && mSyncThread.mSyncContext.getISyncContext() == syncContext) {
+                    mSyncThread.interrupt();
+                }
+            }
+        }
+    }
+
+    /**
+     * The thread that invokes performSync(). It also acquires the provider for this sync
+     * before calling performSync and releases it afterwards. Cancel this thread in order to
+     * cancel the sync.
+     */
+    private class SyncThread extends Thread {
+        private final SyncContext mSyncContext;
+        private final String mAuthority;
+        private final Account mAccount;
+        private final Bundle mExtras;
+
+        private SyncThread(String name, SyncContext syncContext, String authority,
+                Account account, Bundle extras) {
+            super(name);
+            mSyncContext = syncContext;
+            mAuthority = authority;
+            mAccount = account;
+            mExtras = extras;
+        }
+
+        public void run() {
+            if (isCanceled()) {
+                return;
+            }
+
+            SyncResult syncResult = new SyncResult();
+            ContentProviderClient provider = null;
+            try {
+                provider = mContext.getContentResolver().acquireContentProviderClient(mAuthority);
+                if (provider != null) {
+                    AbstractThreadedSyncAdapter.this.performSync(mAccount, mExtras,
+                            mAuthority, provider, syncResult);
+                } else {
+                    // TODO(fredq) update the syncResults to indicate that we were unable to
+                    // find the provider. maybe with a ProviderError?
+                }
+            } finally {
+                if (provider != null) {
+                    provider.release();
+                }
+                if (!isCanceled()) {
+                    mSyncContext.onFinished(syncResult);
+                }
+                // synchronize so that the assignment will be seen by other threads
+                // that also synchronize accesses to mSyncThread
+                synchronized (this) {
+                    mSyncThread = null;
+                }
+            }
+        }
+
+        private boolean isCanceled() {
+            return Thread.currentThread().isInterrupted();
+        }
+    }
+
+    /**
+     * @return a reference to the ISyncAdapter interface into this SyncAdapter implementation.
+     */
+    public final ISyncAdapter getISyncAdapter() {
+        return mISyncAdapterImpl;
+    }
+
+    /**
+     * Perform a sync for this account. SyncAdapter-specific parameters may
+     * be specified in extras, which is guaranteed to not be null. Invocations
+     * of this method are guaranteed to be serialized.
+     *
+     * @param account the account that should be synced
+     * @param extras SyncAdapter-specific parameters
+     * @param authority the authority of this sync request
+     * @param provider a ContentProviderClient that points to the ContentProvider for this
+     *   authority
+     * @param syncResult SyncAdapter-specific parameters
+     */
+    public abstract void performSync(Account account, Bundle extras,
+            String authority, ContentProviderClient provider, SyncResult syncResult);
+}
\ No newline at end of file
diff --git a/core/java/android/content/ActiveSyncInfo.java b/core/java/android/content/ActiveSyncInfo.java
index 63be8d1..209dffa 100644
--- a/core/java/android/content/ActiveSyncInfo.java
+++ b/core/java/android/content/ActiveSyncInfo.java
@@ -16,17 +16,18 @@
 
 package android.content;
 
+import android.accounts.Account;
 import android.os.Parcel;
 import android.os.Parcelable.Creator;
 
 /** @hide */
 public class ActiveSyncInfo {
     public final int authorityId;
-    public final String account;
+    public final Account account;
     public final String authority;
     public final long startTime;
     
-    ActiveSyncInfo(int authorityId, String account, String authority,
+    ActiveSyncInfo(int authorityId, Account account, String authority,
             long startTime) {
         this.authorityId = authorityId;
         this.account = account;
@@ -40,14 +41,14 @@
 
     public void writeToParcel(Parcel parcel, int flags) {
         parcel.writeInt(authorityId);
-        parcel.writeString(account);
+        account.writeToParcel(parcel, 0);
         parcel.writeString(authority);
         parcel.writeLong(startTime);
     }
 
     ActiveSyncInfo(Parcel parcel) {
         authorityId = parcel.readInt();
-        account = parcel.readString();
+        account = new Account(parcel);
         authority = parcel.readString();
         startTime = parcel.readLong();
     }
diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java
index 6b50405..5b29b97 100644
--- a/core/java/android/content/ContentProvider.java
+++ b/core/java/android/content/ContentProvider.java
@@ -34,6 +34,7 @@
 
 import java.io.File;
 import java.io.FileNotFoundException;
+import java.util.ArrayList;
 
 /**
  * Content providers are one of the primary building blocks of Android applications, providing
@@ -130,6 +131,12 @@
                     selectionArgs, sortOrder);
         }
 
+        public EntityIterator queryEntities(Uri uri, String selection, String[] selectionArgs,
+                String sortOrder) {
+            enforceReadPermission(uri);
+            return ContentProvider.this.queryEntities(uri, selection, selectionArgs, sortOrder);
+        }
+
         public String getType(Uri uri) {
             return ContentProvider.this.getType(uri);
         }
@@ -145,6 +152,25 @@
             return ContentProvider.this.bulkInsert(uri, initialValues);
         }
 
+        public Uri insertEntity(Uri uri, Entity entities) {
+            enforceWritePermission(uri);
+            return ContentProvider.this.insertEntity(uri, entities);
+        }
+
+        public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
+                throws OperationApplicationException {
+            for (ContentProviderOperation operation : operations) {
+                if (operation.isReadOperation()) {
+                    enforceReadPermission(operation.getUri());
+                }
+
+                if (operation.isWriteOperation()) {
+                    enforceWritePermission(operation.getUri());
+                }
+            }
+            return ContentProvider.this.applyBatch(operations);
+        }
+
         public int delete(Uri uri, String selection, String[] selectionArgs) {
             enforceWritePermission(uri);
             return ContentProvider.this.delete(uri, selection, selectionArgs);
@@ -156,6 +182,11 @@
             return ContentProvider.this.update(uri, values, selection, selectionArgs);
         }
 
+        public int updateEntity(Uri uri, Entity entity) {
+            enforceWritePermission(uri);
+            return ContentProvider.this.updateEntity(uri, entity);
+        }
+
         public ParcelFileDescriptor openFile(Uri uri, String mode)
                 throws FileNotFoundException {
             if (mode != null && mode.startsWith("rw")) enforceWritePermission(uri);
@@ -170,12 +201,6 @@
             return ContentProvider.this.openAssetFile(uri, mode);
         }
 
-        public ISyncAdapter getSyncAdapter() {
-            enforceWritePermission(null);
-            SyncAdapter sa = ContentProvider.this.getSyncAdapter();
-            return sa != null ? sa.getISyncAdapter() : null;
-        }
-
         private void enforceReadPermission(Uri uri) {
             final int uid = Binder.getCallingUid();
             if (uid == mMyUid) {
@@ -377,9 +402,10 @@
      * Example client call:<p>
      * <pre>// Request a specific record.
      * Cursor managedCursor = managedQuery(
-                Contacts.People.CONTENT_URI.addId(2),
+                ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
                 projection,    // Which columns to return.
                 null,          // WHERE clause.
+                null,          // WHERE clause value substitution
                 People.NAME + " ASC");   // Sort order.</pre>
      * Example implementation:<p>
      * <pre>// SQLiteQueryBuilder is a helper class that creates the
@@ -408,20 +434,28 @@
         return c;</pre>
      *
      * @param uri The URI to query. This will be the full URI sent by the client;
-     * if the client is requesting a specific record, the URI will end in a record number
-     * that the implementation should parse and add to a WHERE or HAVING clause, specifying
-     * that _id value.
+     *      if the client is requesting a specific record, the URI will end in a record number
+     *      that the implementation should parse and add to a WHERE or HAVING clause, specifying
+     *      that _id value.
      * @param projection The list of columns to put into the cursor. If
      *      null all columns are included.
      * @param selection A selection criteria to apply when filtering rows.
      *      If null then all rows are included.
+     * @param selectionArgs You may include ?s in selection, which will be replaced by
+     *      the values from selectionArgs, in order that they appear in the selection.
+     *      The values will be bound as Strings.
      * @param sortOrder How the rows in the cursor should be sorted.
-     *        If null then the provider is free to define the sort order.
+     *      If null then the provider is free to define the sort order.
      * @return a Cursor or null.
      */
     public abstract Cursor query(Uri uri, String[] projection,
             String selection, String[] selectionArgs, String sortOrder);
 
+    public EntityIterator queryEntities(Uri uri, String selection, String[] selectionArgs,
+            String sortOrder) {
+        throw new UnsupportedOperationException();
+    }
+
     /**
      * Return the MIME type of the data at the given URI. This should start with
      * <code>vnd.android.cursor.item</code> for a single record,
@@ -472,6 +506,10 @@
         return numValues;
     }
 
+    public Uri insertEntity(Uri uri, Entity entity) {
+        throw new UnsupportedOperationException();
+    }
+
     /**
      * A request to delete one or more rows. The selection clause is applied when performing
      * the deletion, allowing the operation to affect multiple rows in a
@@ -516,6 +554,10 @@
     public abstract int update(Uri uri, ContentValues values, String selection,
             String[] selectionArgs);
 
+    public int updateEntity(Uri uri, Entity entity) {
+        throw new UnsupportedOperationException();
+    }
+
     /**
      * Open a file blob associated with a content URI.
      * This method can be called from multiple
@@ -639,23 +681,6 @@
     }
 
     /**
-     * Get the sync adapter that is to be used by this content provider.
-     * This is intended for use by the sync system. If null then this
-     * content provider is considered not syncable.
-     * This method can be called from multiple
-     * threads, as described in
-     * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
-     * Processes and Threads</a>.
-     * 
-     * @return the SyncAdapter that is to be used by this ContentProvider, or null
-     *   if this ContentProvider is not syncable
-     * @hide
-     */
-    public SyncAdapter getSyncAdapter() {
-        return null;
-    }
-
-    /**
      * Returns true if this instance is a temporary content provider.
      * @return true if this instance is a temporary content provider
      */
@@ -697,4 +722,27 @@
             ContentProvider.this.onCreate();
         }
     }
-}
+
+    /**
+     * Applies each of the {@link ContentProviderOperation} objects and returns an array
+     * of their results. Passes through OperationApplicationException, which may be thrown
+     * by the call to {@link ContentProviderOperation#apply}.
+     * If all the applications succeed then a {@link ContentProviderResult} array with the
+     * same number of elements as the operations will be returned. It is implementation-specific
+     * how many, if any, operations will have been successfully applied if a call to
+     * apply results in a {@link OperationApplicationException}.
+     * @param operations the operations to apply
+     * @return the results of the applications
+     * @throws OperationApplicationException thrown if an application fails.
+     * See {@link ContentProviderOperation#apply} for more information.
+     */
+    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
+            throws OperationApplicationException {
+        final int numOperations = operations.size();
+        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
+        for (int i = 0; i < numOperations; i++) {
+            results[i] = operations.get(i).apply(this, results, i);
+        }
+        return results;
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/content/ContentProviderClient.java b/core/java/android/content/ContentProviderClient.java
new file mode 100644
index 0000000..452653e
--- /dev/null
+++ b/core/java/android/content/ContentProviderClient.java
@@ -0,0 +1,135 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.RemoteException;
+import android.os.ParcelFileDescriptor;
+import android.content.res.AssetFileDescriptor;
+
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+
+/**
+ * The public interface object used to interact with a {@link ContentProvider}. This is obtained by
+ * calling {@link ContentResolver#acquireContentProviderClient}. This object must be released
+ * using {@link #release} in order to indicate to the system that the {@link ContentProvider} is
+ * no longer needed and can be killed to free up resources.
+ */
+public class ContentProviderClient {
+    private final IContentProvider mContentProvider;
+    private final ContentResolver mContentResolver;
+
+    /**
+     * @hide
+     */
+    ContentProviderClient(ContentResolver contentResolver, IContentProvider contentProvider) {
+        mContentProvider = contentProvider;
+        mContentResolver = contentResolver;
+    }
+
+    /** see {@link ContentProvider#query} */
+    public Cursor query(Uri url, String[] projection, String selection,
+            String[] selectionArgs, String sortOrder) throws RemoteException {
+        return mContentProvider.query(url, projection, selection,  selectionArgs, sortOrder);
+    }
+
+    /** see {@link ContentProvider#getType} */
+    public String getType(Uri url) throws RemoteException {
+        return mContentProvider.getType(url);
+    }
+
+    /** see {@link ContentProvider#insert} */
+    public Uri insert(Uri url, ContentValues initialValues)
+            throws RemoteException {
+        return mContentProvider.insert(url, initialValues);
+    }
+
+    /** see {@link ContentProvider#bulkInsert} */
+    public int bulkInsert(Uri url, ContentValues[] initialValues) throws RemoteException {
+        return mContentProvider.bulkInsert(url, initialValues);
+    }
+
+    /** see {@link ContentProvider#delete} */
+    public int delete(Uri url, String selection, String[] selectionArgs)
+            throws RemoteException {
+        return mContentProvider.delete(url, selection, selectionArgs);
+    }
+
+    /** see {@link ContentProvider#update} */
+    public int update(Uri url, ContentValues values, String selection,
+            String[] selectionArgs) throws RemoteException {
+        return mContentProvider.update(url, values, selection, selectionArgs);
+    }
+
+    /** see {@link ContentProvider#openFile} */
+    public ParcelFileDescriptor openFile(Uri url, String mode)
+            throws RemoteException, FileNotFoundException {
+        return mContentProvider.openFile(url, mode);
+    }
+
+    /** see {@link ContentProvider#openAssetFile} */
+    public AssetFileDescriptor openAssetFile(Uri url, String mode)
+            throws RemoteException, FileNotFoundException {
+        return mContentProvider.openAssetFile(url, mode);
+    }
+
+    /** see {@link ContentProvider#queryEntities} */
+    public EntityIterator queryEntities(Uri uri, String selection, String[] selectionArgs,
+            String sortOrder) throws RemoteException {
+        return mContentProvider.queryEntities(uri, selection, selectionArgs, sortOrder);
+    }
+
+    /** see {@link ContentProvider#insertEntity} */
+    public Uri insertEntity(Uri uri, Entity entity) throws RemoteException {
+        return mContentProvider.insertEntity(uri, entity);
+    }
+
+    /** see {@link ContentProvider#updateEntity} */
+    public int updateEntity(Uri uri, Entity entity) throws RemoteException {
+        return mContentProvider.updateEntity(uri, entity);
+    }
+
+    /** see {@link ContentProvider#applyBatch} */
+    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
+            throws RemoteException, OperationApplicationException {
+        return mContentProvider.applyBatch(operations);
+    }
+
+    /**
+     * Call this to indicate to the system that the associated {@link ContentProvider} is no
+     * longer needed by this {@link ContentProviderClient}.
+     * @return true if this was release, false if it was already released
+     */
+    public boolean release() {
+        return mContentResolver.releaseProvider(mContentProvider);
+    }
+
+    /**
+     * Get a reference to the {@link ContentProvider} that is associated with this
+     * client. If the {@link ContentProvider} is running in a different process then
+     * null will be returned. This can be used if you know you are running in the same
+     * process as a provider, and want to get direct access to its implementation details.
+     *
+     * @return If the associated {@link ContentProvider} is local, returns it.
+     * Otherwise returns null.
+     */
+    public ContentProvider getLocalContentProvider() {
+        return ContentProvider.coerceToLocalContentProvider(mContentProvider);
+    }
+}
diff --git a/core/java/android/content/ContentProviderNative.java b/core/java/android/content/ContentProviderNative.java
index e5e3f74..a4c217b 100644
--- a/core/java/android/content/ContentProviderNative.java
+++ b/core/java/android/content/ContentProviderNative.java
@@ -33,6 +33,7 @@
 import android.os.Parcelable;
 
 import java.io.FileNotFoundException;
+import java.util.ArrayList;
 
 /**
  * {@hide}
@@ -105,6 +106,20 @@
                     return true;
                 }
 
+                case QUERY_ENTITIES_TRANSACTION:
+                {
+                    data.enforceInterface(IContentProvider.descriptor);
+                    Uri url = Uri.CREATOR.createFromParcel(data);
+                    String selection = data.readString();
+                    String[] selectionArgs = data.readStringArray();
+                    String sortOrder = data.readString();
+                    EntityIterator entityIterator = queryEntities(url, selection, selectionArgs,
+                            sortOrder);
+                    reply.writeNoException();
+                    reply.writeStrongBinder(new IEntityIteratorImpl(entityIterator).asBinder());
+                    return true;
+                }
+
                 case GET_TYPE_TRANSACTION:
                 {
                     data.enforceInterface(IContentProvider.descriptor);
@@ -140,6 +155,43 @@
                     return true;
                 }
 
+                case INSERT_ENTITIES_TRANSACTION:
+                {
+                    data.enforceInterface(IContentProvider.descriptor);
+                    Uri uri = Uri.CREATOR.createFromParcel(data);
+                    Entity entity = (Entity) data.readParcelable(null);
+                    Uri newUri = insertEntity(uri, entity);
+                    reply.writeNoException();
+                    Uri.writeToParcel(reply, newUri);
+                    return true;
+                }
+
+                case UPDATE_ENTITIES_TRANSACTION:
+                {
+                    data.enforceInterface(IContentProvider.descriptor);
+                    Uri uri = Uri.CREATOR.createFromParcel(data);
+                    Entity entity = (Entity) data.readParcelable(null);
+                    int count = updateEntity(uri, entity);
+                    reply.writeNoException();
+                    reply.writeInt(count);
+                    return true;
+                }
+
+                case APPLY_BATCH_TRANSACTION:
+                {
+                    data.enforceInterface(IContentProvider.descriptor);
+                    final int numOperations = data.readInt();
+                    final ArrayList<ContentProviderOperation> operations =
+                            new ArrayList<ContentProviderOperation>(numOperations);
+                    for (int i = 0; i < numOperations; i++) {
+                        operations.add(i, ContentProviderOperation.CREATOR.createFromParcel(data));
+                    }
+                    final ContentProviderResult[] results = applyBatch(operations);
+                    reply.writeNoException();
+                    reply.writeTypedArray(results, 0);
+                    return true;
+                }
+
                 case DELETE_TRANSACTION:
                 {
                     data.enforceInterface(IContentProvider.descriptor);
@@ -206,15 +258,6 @@
                     }
                     return true;
                 }
-
-                case GET_SYNC_ADAPTER_TRANSACTION:
-                {
-                    data.enforceInterface(IContentProvider.descriptor);
-                    ISyncAdapter sa = getSyncAdapter();
-                    reply.writeNoException();
-                    reply.writeStrongBinder(sa != null ? sa.asBinder() : null);
-                    return true;
-                }
             }
         } catch (Exception e) {
             DatabaseUtils.writeExceptionToParcel(reply, e);
@@ -224,6 +267,25 @@
         return super.onTransact(code, data, reply, flags);
     }
 
+    private class IEntityIteratorImpl extends IEntityIterator.Stub {
+        private final EntityIterator mEntityIterator;
+
+        IEntityIteratorImpl(EntityIterator iterator) {
+            mEntityIterator = iterator;
+        }
+        public boolean hasNext() throws RemoteException {
+            return mEntityIterator.hasNext();
+        }
+
+        public Entity next() throws RemoteException {
+            return mEntityIterator.next();
+        }
+
+        public void close() throws RemoteException {
+            mEntityIterator.close();
+        }
+    }
+
     public IBinder asBinder()
     {
         return this;
@@ -297,7 +359,7 @@
         BulkCursorToCursorAdaptor adaptor = new BulkCursorToCursorAdaptor();
         IBulkCursor bulkCursor = bulkQuery(url, projection, selection, selectionArgs, sortOrder,
                 adaptor.getObserver(), window);
-         
+
         if (bulkCursor == null) {
             return null;
         }
@@ -305,6 +367,54 @@
         return adaptor;
     }
 
+    public EntityIterator queryEntities(Uri url, String selection, String[] selectionArgs,
+            String sortOrder)
+            throws RemoteException {
+        Parcel data = Parcel.obtain();
+        Parcel reply = Parcel.obtain();
+
+        data.writeInterfaceToken(IContentProvider.descriptor);
+
+        url.writeToParcel(data, 0);
+        data.writeString(selection);
+        data.writeStringArray(selectionArgs);
+        data.writeString(sortOrder);
+
+        mRemote.transact(IContentProvider.QUERY_ENTITIES_TRANSACTION, data, reply, 0);
+
+        DatabaseUtils.readExceptionFromParcel(reply);
+
+        IBinder entityIteratorBinder = reply.readStrongBinder();
+
+        data.recycle();
+        reply.recycle();
+
+        return new RemoteEntityIterator(IEntityIterator.Stub.asInterface(entityIteratorBinder));
+    }
+
+    static class RemoteEntityIterator implements EntityIterator {
+        private final IEntityIterator mEntityIterator;
+        RemoteEntityIterator(IEntityIterator entityIterator) {
+            mEntityIterator = entityIterator;
+        }
+
+        public boolean hasNext() throws RemoteException {
+            return mEntityIterator.hasNext();
+        }
+
+        public Entity next() throws RemoteException {
+            return mEntityIterator.next();
+        }
+
+        public void close() {
+            try {
+                mEntityIterator.close();
+            } catch (RemoteException e) {
+                // doesn't matter
+            }
+        }
+    }
+
     public String getType(Uri url) throws RemoteException
     {
         Parcel data = Parcel.obtain();
@@ -366,6 +476,66 @@
         return count;
     }
 
+    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
+            throws RemoteException, OperationApplicationException {
+        Parcel data = Parcel.obtain();
+        Parcel reply = Parcel.obtain();
+
+        data.writeInterfaceToken(IContentProvider.descriptor);
+        data.writeInt(operations.size());
+        for (ContentProviderOperation operation : operations) {
+            operation.writeToParcel(data, 0);
+        }
+        mRemote.transact(IContentProvider.APPLY_BATCH_TRANSACTION, data, reply, 0);
+
+        DatabaseUtils.readExceptionWithOperationApplicationExceptionFromParcel(reply);
+        final ContentProviderResult[] results =
+                reply.createTypedArray(ContentProviderResult.CREATOR);
+
+        data.recycle();
+        reply.recycle();
+
+        return results;
+    }
+
+    public Uri insertEntity(Uri uri, Entity entity) throws RemoteException {
+        Parcel data = Parcel.obtain();
+        Parcel reply = Parcel.obtain();
+
+        try {
+            data.writeInterfaceToken(IContentProvider.descriptor);
+            uri.writeToParcel(data, 0);
+            data.writeParcelable(entity, 0);
+
+            mRemote.transact(IContentProvider.INSERT_ENTITIES_TRANSACTION, data, reply, 0);
+
+            DatabaseUtils.readExceptionFromParcel(reply);
+            return Uri.CREATOR.createFromParcel(reply);
+        } finally {
+            data.recycle();
+            reply.recycle();
+        }
+    }
+
+    public int updateEntity(Uri uri, Entity entity) throws RemoteException {
+        Parcel data = Parcel.obtain();
+        Parcel reply = Parcel.obtain();
+
+        try {
+            data.writeInterfaceToken(IContentProvider.descriptor);
+            uri.writeToParcel(data, 0);
+            data.writeParcelable(entity, 0);
+
+            mRemote.transact(IContentProvider.UPDATE_ENTITIES_TRANSACTION, data, reply, 0);
+
+            DatabaseUtils.readExceptionFromParcel(reply);
+            return reply.readInt();
+        } finally {
+            data.recycle();
+            reply.recycle();
+        }
+    }
+
     public int delete(Uri url, String selection, String[] selectionArgs)
             throws RemoteException {
         Parcel data = Parcel.obtain();
@@ -456,23 +626,6 @@
         return fd;
     }
 
-    public ISyncAdapter getSyncAdapter() throws RemoteException {
-        Parcel data = Parcel.obtain();
-        Parcel reply = Parcel.obtain();
-
-        data.writeInterfaceToken(IContentProvider.descriptor);
-
-        mRemote.transact(IContentProvider.GET_SYNC_ADAPTER_TRANSACTION, data, reply, 0);
-
-        DatabaseUtils.readExceptionFromParcel(reply);
-        ISyncAdapter syncAdapter = ISyncAdapter.Stub.asInterface(reply.readStrongBinder());
-
-        data.recycle();
-        reply.recycle();
-
-        return syncAdapter;
-    }
-
     private IBinder mRemote;
 }
 
diff --git a/core/java/android/content/ContentProviderOperation.java b/core/java/android/content/ContentProviderOperation.java
new file mode 100644
index 0000000..8b0b6ab
--- /dev/null
+++ b/core/java/android/content/ContentProviderOperation.java
@@ -0,0 +1,529 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+import android.net.Uri;
+import android.database.Cursor;
+import android.os.Parcelable;
+import android.os.Parcel;
+import android.os.Debug;
+
+import java.util.Map;
+import java.util.HashMap;
+
+public class ContentProviderOperation implements Parcelable {
+    private final static int TYPE_INSERT = 1;
+    private final static int TYPE_UPDATE = 2;
+    private final static int TYPE_DELETE = 3;
+    private final static int TYPE_COUNT = 4;
+
+    private final int mType;
+    private final Uri mUri;
+    private final String mSelection;
+    private final String[] mSelectionArgs;
+    private final ContentValues mValues;
+    private final Integer mExpectedCount;
+    private final ContentValues mValuesBackReferences;
+    private final Map<Integer, Integer> mSelectionArgsBackReferences;
+
+    private static final String[] COUNT_COLUMNS = new String[]{"count(*)"};
+
+    /**
+     * Creates a {@link ContentProviderOperation} by copying the contents of a
+     * {@link Builder}.
+     */
+    private ContentProviderOperation(Builder builder) {
+        mType = builder.mType;
+        mUri = builder.mUri;
+        mValues = builder.mValues;
+        mSelection = builder.mSelection;
+        mSelectionArgs = builder.mSelectionArgs;
+        mExpectedCount = builder.mExpectedCount;
+        mSelectionArgsBackReferences = builder.mSelectionArgsBackReferences;
+        mValuesBackReferences = builder.mValuesBackReferences;
+    }
+
+    private ContentProviderOperation(Parcel source) {
+        mType = source.readInt();
+        mUri = Uri.CREATOR.createFromParcel(source);
+        mValues = source.readInt() != 0 ? ContentValues.CREATOR.createFromParcel(source) : null;
+        mSelection = source.readInt() != 0 ? source.readString() : null;
+        mSelectionArgs = source.readInt() != 0 ? source.readStringArray() : null;
+        mExpectedCount = source.readInt() != 0 ? source.readInt() : null;
+        mValuesBackReferences = source.readInt() != 0
+                
+                ? ContentValues.CREATOR.createFromParcel(source)
+                : null;
+        mSelectionArgsBackReferences = source.readInt() != 0
+                ? new HashMap<Integer, Integer>()
+                : null;
+        if (mSelectionArgsBackReferences != null) {
+            final int count = source.readInt();
+            for (int i = 0; i < count; i++) {
+                mSelectionArgsBackReferences.put(source.readInt(), source.readInt());
+            }
+        }
+    }
+
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(mType);
+        Uri.writeToParcel(dest, mUri);
+        if (mValues != null) {
+            dest.writeInt(1);
+            mValues.writeToParcel(dest, 0);
+        } else {
+            dest.writeInt(0);
+        }
+        if (mSelection != null) {
+            dest.writeInt(1);
+            dest.writeString(mSelection);
+        } else {
+            dest.writeInt(0);
+        }
+        if (mSelectionArgs != null) {
+            dest.writeInt(1);
+            dest.writeStringArray(mSelectionArgs);
+        } else {
+            dest.writeInt(0);
+        }
+        if (mExpectedCount != null) {
+            dest.writeInt(1);
+            dest.writeInt(mExpectedCount);
+        } else {
+            dest.writeInt(0);
+        }
+        if (mValuesBackReferences != null) {
+            dest.writeInt(1);
+            mValuesBackReferences.writeToParcel(dest, 0);
+        } else {
+            dest.writeInt(0);
+        }
+        if (mSelectionArgsBackReferences != null) {
+            dest.writeInt(1);
+            dest.writeInt(mSelectionArgsBackReferences.size());
+            for (Map.Entry<Integer, Integer> entry : mSelectionArgsBackReferences.entrySet()) {
+                dest.writeInt(entry.getKey());
+                dest.writeInt(entry.getValue());
+            }
+        } else {
+            dest.writeInt(0);
+        }
+    }
+
+    /**
+     * Create a {@link Builder} suitable for building an insert {@link ContentProviderOperation}.
+     * @param uri The {@link Uri} that is the target of the insert.
+     * @return a {@link Builder}
+     */
+    public static Builder newInsert(Uri uri) {
+        return new Builder(TYPE_INSERT, uri);
+    }
+
+    /**
+     * Create a {@link Builder} suitable for building an update {@link ContentProviderOperation}.
+     * @param uri The {@link Uri} that is the target of the update.
+     * @return a {@link Builder}
+     */
+    public static Builder newUpdate(Uri uri) {
+        return new Builder(TYPE_UPDATE, uri);
+    }
+
+    /**
+     * Create a {@link Builder} suitable for building a delete {@link ContentProviderOperation}.
+     * @param uri The {@link Uri} that is the target of the delete.
+     * @return a {@link Builder}
+     */
+    public static Builder newDelete(Uri uri) {
+        return new Builder(TYPE_DELETE, uri);
+    }
+
+    /**
+     * Create a {@link Builder} suitable for building a count query. When used in conjunction
+     * with {@link Builder#withExpectedCount(int)} this is useful for checking that the
+     * uri/selection has the expected number of rows.
+     * {@link ContentProviderOperation}.
+     * @param uri The {@link Uri} to query.
+     * @return a {@link Builder}
+     */
+    public static Builder newCountQuery(Uri uri) {
+        return new Builder(TYPE_COUNT, uri);
+    }
+
+    public Uri getUri() {
+        return mUri;
+    }
+
+    public boolean isWriteOperation() {
+        return mType == TYPE_DELETE || mType == TYPE_INSERT || mType == TYPE_UPDATE;
+    }
+
+    public boolean isReadOperation() {
+        return mType == TYPE_COUNT;
+    }
+
+    /**
+     * Applies this operation using the given provider. The backRefs array is used to resolve any
+     * back references that were requested using
+     * {@link Builder#withValueBackReferences(ContentValues)} and
+     * {@link Builder#withSelectionBackReference}.
+     * @param provider the {@link ContentProvider} on which this batch is applied
+     * @param backRefs a {@link ContentProviderResult} array that will be consulted
+     * to resolve any requested back references.
+     * @param numBackRefs the number of valid results on the backRefs array.
+     * @return a {@link ContentProviderResult} that contains either the {@link Uri} of the inserted
+     * row if this was an insert otherwise the number of rows affected.
+     * @throws OperationApplicationException thrown if either the insert fails or
+     * if the number of rows affected didn't match the expected count
+     */
+    public ContentProviderResult apply(ContentProvider provider, ContentProviderResult[] backRefs,
+            int numBackRefs) throws OperationApplicationException {
+        ContentValues values = resolveValueBackReferences(backRefs, numBackRefs);
+        String[] selectionArgs =
+                resolveSelectionArgsBackReferences(backRefs, numBackRefs);
+
+        if (mType == TYPE_INSERT) {
+            Uri newUri = provider.insert(mUri, values);
+            if (newUri == null) {
+                throw new OperationApplicationException("insert failed");
+            }
+            return new ContentProviderResult(newUri);
+        }
+
+        int numRows;
+        if (mType == TYPE_DELETE) {
+            numRows = provider.delete(mUri, mSelection, selectionArgs);
+        } else if (mType == TYPE_UPDATE) {
+            numRows = provider.update(mUri, values, mSelection, selectionArgs);
+        } else if (mType == TYPE_COUNT) {
+            Cursor cursor = provider.query(mUri, COUNT_COLUMNS, mSelection, selectionArgs, null);
+            try {
+                if (!cursor.moveToNext()) {
+                    throw new RuntimeException("since we are doing a count query we should always "
+                            + "be able to move to the first row");
+                }
+                if (cursor.getCount() != 1) {
+                    throw new RuntimeException("since we are doing a count query there should "
+                            + "always be exacly row, found " + cursor.getCount());
+                }
+                numRows = cursor.getInt(0);
+            } finally {
+                cursor.close();
+            }
+        } else {
+            throw new IllegalStateException("bad type, " + mType);
+        }
+
+        if (mExpectedCount != null && mExpectedCount != numRows) {
+            throw new OperationApplicationException("wrong number of rows: " + numRows);
+        }
+
+        return new ContentProviderResult(numRows);
+    }
+
+    /**
+     * The ContentValues back references are represented as a ContentValues object where the
+     * key refers to a column and the value is an index of the back reference whose
+     * valued should be associated with the column.
+     * @param backRefs an array of previous results
+     * @param numBackRefs the number of valid previous results in backRefs
+     * @return the ContentValues that should be used in this operation application after
+     * expansion of back references. This can be called if either mValues or mValuesBackReferences
+     * is null
+     * @VisibleForTesting this is intended to be a private method but it is exposed for
+     * unit testing purposes
+     */
+    public ContentValues resolveValueBackReferences(
+            ContentProviderResult[] backRefs, int numBackRefs) {
+        if (mValuesBackReferences == null) {
+            return mValues;
+        }
+        final ContentValues values;
+        if (mValues == null) {
+            values = new ContentValues();
+        } else {
+            values = new ContentValues(mValues);
+        }
+        for (Map.Entry<String, Object> entry : mValuesBackReferences.valueSet()) {
+            String key = entry.getKey();
+            Integer backRefIndex = mValuesBackReferences.getAsInteger(key);
+            if (backRefIndex == null) {
+                throw new IllegalArgumentException("values backref " + key + " is not an integer");
+            }
+            values.put(key, backRefToValue(backRefs, numBackRefs, backRefIndex));
+        }
+        return values;
+    }
+
+    /**
+     * The Selection Arguments back references are represented as a Map of Integer->Integer where
+     * the key is an index into the selection argument array (see {@link Builder#withSelection})
+     * and the value is the index of the previous result that should be used for that selection
+     * argument array slot.
+     * @param backRefs an array of previous results
+     * @param numBackRefs the number of valid previous results in backRefs
+     * @return the ContentValues that should be used in this operation application after
+     * expansion of back references. This can be called if either mValues or mValuesBackReferences
+     * is null
+     * @VisibleForTesting this is intended to be a private method but it is exposed for
+     * unit testing purposes
+     */
+    public String[] resolveSelectionArgsBackReferences(
+            ContentProviderResult[] backRefs, int numBackRefs) {
+        if (mSelectionArgsBackReferences == null) {
+            return mSelectionArgs;
+        }
+        String[] newArgs = new String[mSelectionArgs.length];
+        System.arraycopy(mSelectionArgs, 0, newArgs, 0, mSelectionArgs.length);
+        for (Map.Entry<Integer, Integer> selectionArgBackRef
+                : mSelectionArgsBackReferences.entrySet()) {
+            final Integer selectionArgIndex = selectionArgBackRef.getKey();
+            final int backRefIndex = selectionArgBackRef.getValue();
+            newArgs[selectionArgIndex] = backRefToValue(backRefs, numBackRefs, backRefIndex);
+        }
+        return newArgs;
+    }
+
+    /**
+     * Return the string representation of the requested back reference.
+     * @param backRefs an array of results
+     * @param numBackRefs the number of items in the backRefs array that are valid
+     * @param backRefIndex which backRef to be used
+     * @throws ArrayIndexOutOfBoundsException thrown if the backRefIndex is larger than
+     * the numBackRefs
+     * @return the string representation of the requested back reference.
+     */
+    private static String backRefToValue(ContentProviderResult[] backRefs, int numBackRefs,
+            Integer backRefIndex) {
+        if (backRefIndex >= numBackRefs) {
+            throw new ArrayIndexOutOfBoundsException("asked for back ref " + backRefIndex
+                    + " but there are only " + numBackRefs + " back refs");
+        }
+        ContentProviderResult backRef = backRefs[backRefIndex];
+        String backRefValue;
+        if (backRef.uri != null) {
+            backRefValue = backRef.uri.getLastPathSegment();
+        } else {
+            backRefValue = String.valueOf(backRef.count);
+        }
+        return backRefValue;
+    }
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public static final Creator<ContentProviderOperation> CREATOR =
+            new Creator<ContentProviderOperation>() {
+        public ContentProviderOperation createFromParcel(Parcel source) {
+            return new ContentProviderOperation(source);
+        }
+
+        public ContentProviderOperation[] newArray(int size) {
+            return new ContentProviderOperation[size];
+        }
+    };
+
+
+    /**
+     * Used to add parameters to a {@link ContentProviderOperation}. The {@link Builder} is
+     * first created by calling {@link ContentProviderOperation#newInsert(android.net.Uri)},
+     * {@link ContentProviderOperation#newUpdate(android.net.Uri)},
+     * {@link ContentProviderOperation#newDelete(android.net.Uri)} or
+     * {@link ContentProviderOperation#newCountQuery(android.net.Uri)}. The withXXX methods
+     * can then be used to add parameters to the builder. See the specific methods to find for
+     * which {@link Builder} type each is allowed. Call {@link #build} to create the
+     * {@link ContentProviderOperation} once all the parameters have been supplied.
+     */
+    public static class Builder {
+        private final int mType;
+        private final Uri mUri;
+        private String mSelection;
+        private String[] mSelectionArgs;
+        private ContentValues mValues;
+        private Integer mExpectedCount;
+        private ContentValues mValuesBackReferences;
+        private Map<Integer, Integer> mSelectionArgsBackReferences;
+
+        /** Create a {@link Builder} of a given type. The uri must not be null. */
+        private Builder(int type, Uri uri) {
+            if (uri == null) {
+                throw new IllegalArgumentException("uri must not be null");
+            }
+            mType = type;
+            mUri = uri;
+        }
+
+        /** Create a ContentProviderOperation from this {@link Builder}. */
+        public ContentProviderOperation build() {
+            if (mType == TYPE_UPDATE) {
+                if ((mValues == null || mValues.size() == 0)
+                        && (mValuesBackReferences == null || mValuesBackReferences.size() == 0)) {
+                    throw new IllegalArgumentException("Empty values");
+                }
+            }
+            return new ContentProviderOperation(this);
+        }
+
+        /**
+         * Add a {@link ContentValues} of back references. The key is the name of the column
+         * and the value is an integer that is the index of the previous result whose
+         * value should be used for the column. The value is added as a {@link String}.
+         * A column value from the back references takes precedence over a value specified in
+         * {@link #withValues}.
+         * This can only be used with builders of type insert or update.
+         * @return this builder, to allow for chaining.
+         */
+        public Builder withValueBackReferences(ContentValues backReferences) {
+            if (mType != TYPE_INSERT && mType != TYPE_UPDATE) {
+                throw new IllegalArgumentException(
+                        "only inserts and updates can have value back-references");
+            }
+            mValuesBackReferences = backReferences;
+            return this;
+        }
+
+        /**
+         * Add a ContentValues back reference.
+         * A column value from the back references takes precedence over a value specified in
+         * {@link #withValues}.
+         * This can only be used with builders of type insert or update.
+         * @return this builder, to allow for chaining.
+         */
+        public Builder withValueBackReference(String key, int previousResult) {
+            if (mType != TYPE_INSERT && mType != TYPE_UPDATE) {
+                throw new IllegalArgumentException(
+                        "only inserts and updates can have value back-references");
+            }
+            if (mValuesBackReferences == null) {
+                mValuesBackReferences = new ContentValues();
+            }
+            mValuesBackReferences.put(key, previousResult);
+            return this;
+        }
+
+        /**
+         * Add a back references as a selection arg. Any value at that index of the selection arg
+         * that was specified by {@link #withSelection} will be overwritten.
+         * This can only be used with builders of type update, delete, or count query.
+         * @return this builder, to allow for chaining.
+         */
+        public Builder withSelectionBackReference(int selectionArgIndex, int previousResult) {
+            if (mType != TYPE_COUNT && mType != TYPE_UPDATE && mType != TYPE_DELETE) {
+                throw new IllegalArgumentException(
+                        "only deletes, updates and counts can have selection back-references");
+            }
+            if (mSelectionArgsBackReferences == null) {
+                mSelectionArgsBackReferences = new HashMap<Integer, Integer>();
+            }
+            mSelectionArgsBackReferences.put(selectionArgIndex, previousResult);
+            return this;
+        }
+
+        /**
+         * The ContentValues to use. This may be null. These values may be overwritten by
+         * the corresponding value specified by {@link #withValueBackReference} or by
+         * future calls to {@link #withValues} or {@link #withValue}.
+         * This can only be used with builders of type insert or update.
+         * @return this builder, to allow for chaining.
+         */
+        public Builder withValues(ContentValues values) {
+            if (mType != TYPE_INSERT && mType != TYPE_UPDATE) {
+                throw new IllegalArgumentException("only inserts and updates can have values");
+            }
+            if (mValues == null) {
+                mValues = new ContentValues();
+            }
+            mValues.putAll(values);
+            return this;
+        }
+
+        /**
+         * A value to insert or update. This value may be overwritten by
+         * the corresponding value specified by {@link #withValueBackReference}.
+         * This can only be used with builders of type insert or update.
+         * @param key the name of this value
+         * @param value the value itself. the type must be acceptable for insertion by
+         * {@link ContentValues#put}
+         * @return this builder, to allow for chaining.
+         */
+        public Builder withValue(String key, Object value) {
+            if (mType != TYPE_INSERT && mType != TYPE_UPDATE) {
+                throw new IllegalArgumentException("only inserts and updates can have values");
+            }
+            if (mValues == null) {
+                mValues = new ContentValues();
+            }
+            if (value == null) {
+                mValues.putNull(key);
+            } else if (value instanceof String) {
+                mValues.put(key, (String) value);
+            } else if (value instanceof Byte) {
+                mValues.put(key, (Byte) value);
+            } else if (value instanceof Short) {
+                mValues.put(key, (Short) value);
+            } else if (value instanceof Integer) {
+                mValues.put(key, (Integer) value);
+            } else if (value instanceof Long) {
+                mValues.put(key, (Long) value);
+            } else if (value instanceof Float) {
+                mValues.put(key, (Float) value);
+            } else if (value instanceof Double) {
+                mValues.put(key, (Double) value);
+            } else if (value instanceof Boolean) {
+                mValues.put(key, (Boolean) value);
+            } else if (value instanceof byte[]) {
+                mValues.put(key, (byte[]) value);
+            } else {
+                throw new IllegalArgumentException("bad value type: " + value.getClass().getName());
+            }
+            return this;
+        }
+        
+        /**
+         * The selection and arguments to use. An occurrence of '?' in the selection will be
+         * replaced with the corresponding occurence of the selection argument. Any of the
+         * selection arguments may be overwritten by a selection argument back reference as
+         * specified by {@link #withSelectionBackReference}.
+         * This can only be used with builders of type update, delete, or count query.
+         * @return this builder, to allow for chaining.
+         */
+        public Builder withSelection(String selection, String[] selectionArgs) {
+            if (mType != TYPE_DELETE && mType != TYPE_UPDATE && mType != TYPE_COUNT) {
+                throw new IllegalArgumentException(
+                        "only deletes, updates and counts can have selections");
+            }
+            mSelection = selection;
+            mSelectionArgs = selectionArgs;
+            return this;
+        }
+
+        /**
+         * If set then if the number of rows affected by this operation do not match
+         * this count {@link OperationApplicationException} will be throw.
+         * This can only be used with builders of type update, delete, or count query.
+         * @return this builder, to allow for chaining.
+         */
+        public Builder withExpectedCount(int count) {
+            if (mType != TYPE_DELETE && mType != TYPE_UPDATE && mType != TYPE_COUNT) {
+                throw new IllegalArgumentException(
+                        "only deletes, updates and counts can have expected counts");
+            }
+            mExpectedCount = count;
+            return this;
+        }
+    }
+}
diff --git a/core/java/android/content/ContentProviderResult.java b/core/java/android/content/ContentProviderResult.java
new file mode 100644
index 0000000..5d188ef
--- /dev/null
+++ b/core/java/android/content/ContentProviderResult.java
@@ -0,0 +1,84 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+import android.net.Uri;
+import android.os.Parcelable;
+import android.os.Parcel;
+
+/**
+ * Contains the result of the application of a {@link ContentProviderOperation}. It is guaranteed
+ * to have exactly one of {@link #uri} or {@link #count} set.
+ */
+public class ContentProviderResult implements Parcelable {
+    public final Uri uri;
+    public final Integer count;
+
+    public ContentProviderResult(Uri uri) {
+        if (uri == null) throw new IllegalArgumentException("uri must not be null");
+        this.uri = uri;
+        this.count = null;
+    }
+
+    public ContentProviderResult(int count) {
+        this.count = count;
+        this.uri = null;
+    }
+
+    public ContentProviderResult(Parcel source) {
+        int type = source.readInt();
+        if (type == 1) {
+            count = source.readInt();
+            uri = null;
+        } else {
+            count = null;
+            uri = Uri.CREATOR.createFromParcel(source);
+        }
+    }
+
+    public void writeToParcel(Parcel dest, int flags) {
+        if (uri == null) {
+            dest.writeInt(1);
+            dest.writeInt(count);
+        } else {
+            dest.writeInt(2);
+            uri.writeToParcel(dest, 0);
+        }
+    }
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public static final Creator<ContentProviderResult> CREATOR =
+            new Creator<ContentProviderResult>() {
+        public ContentProviderResult createFromParcel(Parcel source) {
+            return new ContentProviderResult(source);
+        }
+
+        public ContentProviderResult[] newArray(int size) {
+            return new ContentProviderResult[size];
+        }
+    };
+
+    public String toString() {
+        if (uri != null) {
+            return "ContentProviderResult(uri=" + uri.toString() + ")";
+        }
+        return "ContentProviderResult(count=" + count + ")";
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index 74144fc..98ed098 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -30,6 +30,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.text.TextUtils;
+import android.accounts.Account;
 import android.util.Config;
 import android.util.Log;
 
@@ -40,15 +41,25 @@
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.util.List;
+import java.util.ArrayList;
 
 
 /**
  * This class provides applications access to the content model.
  */
 public abstract class ContentResolver {
-    public final static String SYNC_EXTRAS_ACCOUNT = "account";
+    /**
+     * @deprecated instead use
+     * {@link #requestSync(android.accounts.Account, String, android.os.Bundle)}
+     */
+    public static final String SYNC_EXTRAS_ACCOUNT = "account";
     public static final String SYNC_EXTRAS_EXPEDITED = "expedited";
+    /**
+     * @deprecated instead use
+     * {@link #SYNC_EXTRAS_MANUAL}
+     */
     public static final String SYNC_EXTRAS_FORCE = "force";
+    public static final String SYNC_EXTRAS_MANUAL = "force";
     public static final String SYNC_EXTRAS_UPLOAD = "upload";
     public static final String SYNC_EXTRAS_OVERRIDE_TOO_MANY_DELETIONS = "deletions_override";
     public static final String SYNC_EXTRAS_DISCARD_LOCAL_DELETIONS = "discard_deletions";
@@ -88,7 +99,35 @@
      * in the cursor is the same.
      */
     public static final String CURSOR_DIR_BASE_TYPE = "vnd.android.cursor.dir";
-    
+
+    /** @hide */
+    public static final int SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS = 1;
+    /** @hide */
+    public static final int SYNC_ERROR_AUTHENTICATION = 2;
+    /** @hide */
+    public static final int SYNC_ERROR_IO = 3;
+    /** @hide */
+    public static final int SYNC_ERROR_PARSE = 4;
+    /** @hide */
+    public static final int SYNC_ERROR_CONFLICT = 5;
+    /** @hide */
+    public static final int SYNC_ERROR_TOO_MANY_DELETIONS = 6;
+    /** @hide */
+    public static final int SYNC_ERROR_TOO_MANY_RETRIES = 7;
+    /** @hide */
+    public static final int SYNC_ERROR_INTERNAL = 8;
+
+    /** @hide */
+    public static final int SYNC_OBSERVER_TYPE_SETTINGS = 1<<0;
+    /** @hide */
+    public static final int SYNC_OBSERVER_TYPE_PENDING = 1<<1;
+    /** @hide */
+    public static final int SYNC_OBSERVER_TYPE_ACTIVE = 1<<2;
+    /** @hide */
+    public static final int SYNC_OBSERVER_TYPE_STATUS = 1<<3;
+    /** @hide */
+    public static final int SYNC_OBSERVER_TYPE_ALL = 0x7fffffff;
+
     public ContentResolver(Context context) {
         mContext = context;
     }
@@ -166,6 +205,87 @@
     }
 
     /**
+     * EntityIterator wrapper that releases the associated ContentProviderClient when the
+     * iterator is closed.
+     */
+    private class EntityIteratorWrapper implements EntityIterator {
+        private final EntityIterator mInner;
+        private final ContentProviderClient mClient;
+        private volatile boolean mClientReleased;
+
+        EntityIteratorWrapper(EntityIterator inner, ContentProviderClient client) {
+            mInner = inner;
+            mClient = client;
+            mClientReleased = false;
+        }
+
+        public boolean hasNext() throws RemoteException {
+            if (mClientReleased) {
+                throw new IllegalStateException("this iterator is already closed");
+            }
+            return mInner.hasNext();
+        }
+
+        public Entity next() throws RemoteException {
+            if (mClientReleased) {
+                throw new IllegalStateException("this iterator is already closed");
+            }
+            return mInner.next();
+        }
+
+        public void close() {
+            mClient.release();
+            mInner.close();
+            mClientReleased = true;
+        }
+
+        protected void finalize() throws Throwable {
+            if (!mClientReleased) {
+                mClient.release();
+            }
+            super.finalize();
+        }
+    }
+
+    /**
+     * Query the given URI, returning an {@link EntityIterator} over the result set.
+     *
+     * @param uri The URI, using the content:// scheme, for the content to
+     *         retrieve.
+     * @param selection A filter declaring which rows to return, formatted as an
+     *         SQL WHERE clause (excluding the WHERE itself). Passing null will
+     *         return all rows for the given URI.
+     * @param selectionArgs You may include ?s in selection, which will be
+     *         replaced by the values from selectionArgs, in the order that they
+     *         appear in the selection. The values will be bound as Strings.
+     * @param sortOrder How to order the rows, formatted as an SQL ORDER BY
+     *         clause (excluding the ORDER BY itself). Passing null will use the
+     *         default sort order, which may be unordered.
+     * @return An EntityIterator object
+     * @throws RemoteException thrown if a RemoteException is encountered while attempting
+     *   to communicate with a remote provider.
+     * @throws IllegalArgumentException thrown if there is no provider that matches the uri
+     */
+    public final EntityIterator queryEntities(Uri uri,
+            String selection, String[] selectionArgs, String sortOrder) throws RemoteException {
+        ContentProviderClient provider = acquireContentProviderClient(uri);
+        if (provider == null) {
+            throw new IllegalArgumentException("Unknown URL " + uri);
+        }
+        try {
+            EntityIterator entityIterator =
+                    provider.queryEntities(uri, selection, selectionArgs, sortOrder);
+            return new EntityIteratorWrapper(entityIterator, provider);
+        } catch(RuntimeException e) {
+            provider.release();
+            throw e;
+        } catch(RemoteException e) {
+            provider.release();
+            throw e;
+        }
+    }
+
+    /**
      * Open a stream on to the content associated with a content URI.  If there
      * is no data associated with the URI, FileNotFoundException is thrown.
      *
@@ -485,6 +605,36 @@
     }
 
     /**
+     * Applies each of the {@link ContentProviderOperation} objects and returns an array
+     * of their results. Passes through OperationApplicationException, which may be thrown
+     * by the call to {@link ContentProviderOperation#apply}.
+     * If all the applications succeed then a {@link ContentProviderResult} array with the
+     * same number of elements as the operations will be returned. It is implementation-specific
+     * how many, if any, operations will have been successfully applied if a call to
+     * apply results in a {@link OperationApplicationException}.
+     * @param authority the authority of the ContentProvider to which this batch should be applied
+     * @param operations the operations to apply
+     * @return the results of the applications
+     * @throws OperationApplicationException thrown if an application fails.
+     * See {@link ContentProviderOperation#apply} for more information.
+     * @throws RemoteException thrown if a RemoteException is encountered while attempting
+     *   to communicate with a remote provider.
+     */
+    public ContentProviderResult[] applyBatch(String authority,
+            ArrayList<ContentProviderOperation> operations)
+            throws RemoteException, OperationApplicationException {
+        ContentProviderClient provider = acquireContentProviderClient(authority);
+        if (provider == null) {
+            throw new IllegalArgumentException("Unknown authority " + authority);
+        }
+        try {
+            return provider.applyBatch(operations);
+        } finally {
+            provider.release();
+        }
+    }
+
+    /**
      * Inserts multiple rows into a table at the given URL.
      *
      * This function make no guarantees about the atomicity of the insertions.
@@ -592,6 +742,46 @@
     }
 
     /**
+     * Returns a {@link ContentProviderClient} that is associated with the {@link ContentProvider}
+     * that services the content at uri, starting the provider if necessary. Returns
+     * null if there is no provider associated wih the uri. The caller must indicate that they are
+     * done with the provider by calling {@link ContentProviderClient#release} which will allow
+     * the system to release the provider it it determines that there is no other reason for
+     * keeping it active.
+     * @param uri specifies which provider should be acquired
+     * @return a {@link ContentProviderClient} that is associated with the {@link ContentProvider}
+     * that services the content at uri or null if there isn't one.
+     */
+    public final ContentProviderClient acquireContentProviderClient(Uri uri) {
+        IContentProvider provider = acquireProvider(uri);
+        if (provider != null) {
+            return new ContentProviderClient(this, provider);
+        }
+
+        return null;
+    }
+
+    /**
+     * Returns a {@link ContentProviderClient} that is associated with the {@link ContentProvider}
+     * with the authority of name, starting the provider if necessary. Returns
+     * null if there is no provider associated wih the uri. The caller must indicate that they are
+     * done with the provider by calling {@link ContentProviderClient#release} which will allow
+     * the system to release the provider it it determines that there is no other reason for
+     * keeping it active.
+     * @param name specifies which provider should be acquired
+     * @return a {@link ContentProviderClient} that is associated with the {@link ContentProvider}
+     * with the authority of name or null if there isn't one.
+     */
+    public final ContentProviderClient acquireContentProviderClient(String name) {
+        IContentProvider provider = acquireProvider(name);
+        if (provider != null) {
+            return new ContentProviderClient(this, provider);
+        }
+
+        return null;
+    }
+
+    /**
      * Register an observer class that gets callbacks when data identified by a
      * given content URI changes.
      *
@@ -676,11 +866,42 @@
      *
      * @param uri the uri of the provider to sync or null to sync all providers.
      * @param extras any extras to pass to the SyncAdapter.
+     * @deprecated instead use
+     * {@link #requestSync(android.accounts.Account, String, android.os.Bundle)}
      */
     public void startSync(Uri uri, Bundle extras) {
+        Account account = null;
+        if (extras != null) {
+            String accountName = extras.getString(SYNC_EXTRAS_ACCOUNT);
+            if (!TextUtils.isEmpty(accountName)) {
+                account = new Account(accountName, "com.google.GAIA");
+            }
+            extras.remove(SYNC_EXTRAS_ACCOUNT);
+        }
+        requestSync(account, uri != null ? uri.getAuthority() : null, extras);
+    }
+
+    /**
+     * Start an asynchronous sync operation. If you want to monitor the progress
+     * of the sync you may register a SyncObserver. Only values of the following
+     * types may be used in the extras bundle:
+     * <ul>
+     * <li>Integer</li>
+     * <li>Long</li>
+     * <li>Boolean</li>
+     * <li>Float</li>
+     * <li>Double</li>
+     * <li>String</li>
+     * </ul>
+     *
+     * @param account which account should be synced
+     * @param authority which authority should be synced
+     * @param extras any extras to pass to the SyncAdapter.
+     */
+    public static void requestSync(Account account, String authority, Bundle extras) {
         validateSyncExtrasBundle(extras);
         try {
-            getContentService().startSync(uri, extras);
+            getContentService().requestSync(account, authority, extras);
         } catch (RemoteException e) {
         }
     }
@@ -694,6 +915,7 @@
      * <li>Float</li>
      * <li>Double</li>
      * <li>String</li>
+     * <li>Account</li>
      * <li>null</li>
      * </ul>
      * @param extras the Bundle to check
@@ -709,6 +931,7 @@
                 if (value instanceof Float) continue;
                 if (value instanceof Double) continue;
                 if (value instanceof String) continue;
+                if (value instanceof Account) continue;
                 throw new IllegalArgumentException("unexpected value type: "
                         + value.getClass().getName());
             }
@@ -719,13 +942,186 @@
         }
     }
 
+    /**
+     * Cancel any active or pending syncs that match the Uri. If the uri is null then
+     * all syncs will be canceled.
+     *
+     * @param uri the uri of the provider to sync or null to sync all providers.
+     * @deprecated instead use {@link #cancelSync(android.accounts.Account, String)}
+     */
     public void cancelSync(Uri uri) {
+        cancelSync(null /* all accounts */, uri != null ? uri.getAuthority() : null);
+    }
+
+    /**
+     * Cancel any active or pending syncs that match account and authority. The account and
+     * authority can each independently be set to null, which means that syncs with any account
+     * or authority, respectively, will match.
+     *
+     * @param account filters the syncs that match by this account
+     * @param authority filters the syncs that match by this authority
+     */
+    public static void cancelSync(Account account, String authority) {
         try {
-            getContentService().cancelSync(uri);
+            getContentService().cancelSync(account, authority);
         } catch (RemoteException e) {
         }
     }
 
+    /**
+     * Get information about the SyncAdapters that are known to the system.
+     * @return an array of SyncAdapters that have registered with the system
+     */
+    public static SyncAdapterType[] getSyncAdapterTypes() {
+        try {
+            return getContentService().getSyncAdapterTypes();
+        } catch (RemoteException e) {
+            throw new RuntimeException("the ContentService should always be reachable", e);
+        }
+    }
+
+    /**
+     * Check if the provider should be synced when a network tickle is received
+     *
+     * @param account the account whose setting we are querying
+     * @param authority the provider whose setting we are querying
+     * @return true if the provider should be synced when a network tickle is received
+     */
+    public static boolean getSyncAutomatically(Account account, String authority) {
+        try {
+            return getContentService().getSyncAutomatically(account, authority);
+        } catch (RemoteException e) {
+            throw new RuntimeException("the ContentService should always be reachable", e);
+        }
+    }
+
+    /**
+     * Set whether or not the provider is synced when it receives a network tickle.
+     *
+     * @param account the account whose setting we are querying
+     * @param authority the provider whose behavior is being controlled
+     * @param sync true if the provider should be synced when tickles are received for it
+     */
+    public static void setSyncAutomatically(Account account, String authority, boolean sync) {
+        try {
+            getContentService().setSyncAutomatically(account, authority, sync);
+        } catch (RemoteException e) {
+            // exception ignored; if this is thrown then it means the runtime is in the midst of
+            // being restarted
+        }
+    }
+
+    /**
+     * Gets the master auto-sync setting that applies to all the providers and accounts.
+     * If this is false then the per-provider auto-sync setting is ignored.
+     *
+     * @return the master auto-sync setting that applies to all the providers and accounts
+     */
+    public static boolean getMasterSyncAutomatically() {
+        try {
+            return getContentService().getMasterSyncAutomatically();
+        } catch (RemoteException e) {
+            throw new RuntimeException("the ContentService should always be reachable", e);
+        }
+    }
+
+    /**
+     * Sets the master auto-sync setting that applies to all the providers and accounts.
+     * If this is false then the per-provider auto-sync setting is ignored.
+     *
+     * @param sync the master auto-sync setting that applies to all the providers and accounts
+     */
+    public static void setMasterSyncAutomatically(boolean sync) {
+        try {
+            getContentService().setMasterSyncAutomatically(sync);
+        } catch (RemoteException e) {
+            // exception ignored; if this is thrown then it means the runtime is in the midst of
+            // being restarted
+        }
+    }
+
+    /**
+     * Returns true if there is currently a sync operation for the given
+     * account or authority in the pending list, or actively being processed.
+     * @param account the account whose setting we are querying
+     * @param authority the provider whose behavior is being queried
+     * @return true if a sync is active for the given account or authority.
+     */
+    public static boolean isSyncActive(Account account, String authority) {
+        try {
+            return getContentService().isSyncActive(account, authority);
+        } catch (RemoteException e) {
+            throw new RuntimeException("the ContentService should always be reachable", e);
+        }
+    }
+
+    /**
+     * If a sync is active returns the information about it, otherwise returns false.
+     * @return the ActiveSyncInfo for the currently active sync or null if one is not active.
+     * @hide
+     */
+    public static ActiveSyncInfo getActiveSync() {
+        try {
+            return getContentService().getActiveSync();
+        } catch (RemoteException e) {
+            throw new RuntimeException("the ContentService should always be reachable", e);
+        }
+    }
+
+    /**
+     * Returns the status that matches the authority. If there are multiples accounts for
+     * the authority, the one with the latest "lastSuccessTime" status is returned.
+     * @param account the account whose setting we are querying
+     * @param authority the provider whose behavior is being queried
+     * @return the SyncStatusInfo for the authority, or null if none exists
+     * @hide
+     */
+    public static SyncStatusInfo getSyncStatus(Account account, String authority) {
+        try {
+            return getContentService().getSyncStatus(account, authority);
+        } catch (RemoteException e) {
+            throw new RuntimeException("the ContentService should always be reachable", e);
+        }
+    }
+
+    /**
+     * Return true if the pending status is true of any matching authorities.
+     * @param account the account whose setting we are querying
+     * @param authority the provider whose behavior is being queried
+     * @return true if there is a pending sync with the matching account and authority
+     */
+    public static boolean isSyncPending(Account account, String authority) {
+        try {
+            return getContentService().isSyncPending(account, authority);
+        } catch (RemoteException e) {
+            throw new RuntimeException("the ContentService should always be reachable", e);
+        }
+    }
+
+    public static Object addStatusChangeListener(int mask, final SyncStatusObserver callback) {
+        try {
+            ISyncStatusObserver.Stub observer = new ISyncStatusObserver.Stub() {
+                public void onStatusChanged(int which) throws RemoteException {
+                    callback.onStatusChanged(which);
+                }
+            };
+            getContentService().addStatusChangeListener(mask, observer);
+            return observer;
+        } catch (RemoteException e) {
+            throw new RuntimeException("the ContentService should always be reachable", e);
+        }
+    }
+
+    public static void removeStatusChangeListener(Object handle) {
+        try {
+            getContentService().removeStatusChangeListener((ISyncStatusObserver.Stub) handle);
+        } catch (RemoteException e) {
+            // exception ignored; if this is thrown then it means the runtime is in the midst of
+            // being restarted
+        }
+    }
+
+
     private final class CursorWrapperInner extends CursorWrapper {
         private IContentProvider mContentProvider;
         public static final String TAG="CursorWrapperInner";
diff --git a/core/java/android/content/ContentService.java b/core/java/android/content/ContentService.java
index 6cd2c54..7a1ad2b 100644
--- a/core/java/android/content/ContentService.java
+++ b/core/java/android/content/ContentService.java
@@ -16,6 +16,7 @@
 
 package android.content;
 
+import android.accounts.Account;
 import android.database.IContentObserver;
 import android.database.sqlite.SQLiteException;
 import android.net.Uri;
@@ -160,7 +161,9 @@
             }
             if (syncToNetwork) {
                 SyncManager syncManager = getSyncManager();
-                if (syncManager != null) syncManager.scheduleLocalSync(uri);
+                if (syncManager != null) {
+                    syncManager.scheduleLocalSync(null /* all accounts */, uri.getAuthority());
+                }
             }
         } finally {
             restoreCallingIdentity(identityToken);
@@ -186,14 +189,16 @@
         }
     }
 
-    public void startSync(Uri url, Bundle extras) {
+    public void requestSync(Account account, String authority, Bundle extras) {
         ContentResolver.validateSyncExtrasBundle(extras);
         // This makes it so that future permission checks will be in the context of this
         // process rather than the caller's process. We will restore this before returning.
         long identityToken = clearCallingIdentity();
         try {
             SyncManager syncManager = getSyncManager();
-            if (syncManager != null) syncManager.startSync(url, extras);
+            if (syncManager != null) {
+                syncManager.scheduleSync(account, authority, extras, 0 /* no delay */);
+            }
         } finally {
             restoreCallingIdentity(identityToken);
         }
@@ -201,34 +206,50 @@
 
     /**
      * Clear all scheduled sync operations that match the uri and cancel the active sync
-     * if it matches the uri. If the uri is null, clear all scheduled syncs and cancel
-     * the active one, if there is one.
-     * @param uri Filter on the sync operations to cancel, or all if null.
+     * if they match the authority and account, if they are present.
+     * @param account filter the pending and active syncs to cancel using this account
+     * @param authority filter the pending and active syncs to cancel using this authority
      */
-    public void cancelSync(Uri uri) {
+    public void cancelSync(Account account, String authority) {
         // This makes it so that future permission checks will be in the context of this
         // process rather than the caller's process. We will restore this before returning.
         long identityToken = clearCallingIdentity();
         try {
             SyncManager syncManager = getSyncManager();
             if (syncManager != null) {
-                syncManager.clearScheduledSyncOperations(uri);
-                syncManager.cancelActiveSync(uri);
+                syncManager.clearScheduledSyncOperations(account, authority);
+                syncManager.cancelActiveSync(account, authority);
             }
         } finally {
             restoreCallingIdentity(identityToken);
         }
     }
 
-    public boolean getSyncProviderAutomatically(String providerName) {
+    /**
+     * Get information about the SyncAdapters that are known to the system.
+     * @return an array of SyncAdapters that have registered with the system
+     */
+    public SyncAdapterType[] getSyncAdapterTypes() {
+        // This makes it so that future permission checks will be in the context of this
+        // process rather than the caller's process. We will restore this before returning.
+        long identityToken = clearCallingIdentity();
+        try {
+            SyncManager syncManager = getSyncManager();
+            return syncManager.getSyncAdapterTypes();
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
+    }
+    
+    public boolean getSyncAutomatically(Account account, String providerName) {
         mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_SETTINGS,
                 "no permission to read the sync settings");
         long identityToken = clearCallingIdentity();
         try {
             SyncManager syncManager = getSyncManager();
             if (syncManager != null) {
-                return syncManager.getSyncStorageEngine().getSyncProviderAutomatically(
-                        null, providerName);
+                return syncManager.getSyncStorageEngine().getSyncAutomatically(
+                        account, providerName);
             }
         } finally {
             restoreCallingIdentity(identityToken);
@@ -236,29 +257,29 @@
         return false;
     }
 
-    public void setSyncProviderAutomatically(String providerName, boolean sync) {
+    public void setSyncAutomatically(Account account, String providerName, boolean sync) {
         mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
                 "no permission to write the sync settings");
         long identityToken = clearCallingIdentity();
         try {
             SyncManager syncManager = getSyncManager();
             if (syncManager != null) {
-                syncManager.getSyncStorageEngine().setSyncProviderAutomatically(
-                        null, providerName, sync);
+                syncManager.getSyncStorageEngine().setSyncAutomatically(
+                        account, providerName, sync);
             }
         } finally {
             restoreCallingIdentity(identityToken);
         }
     }
 
-    public boolean getListenForNetworkTickles() {
+    public boolean getMasterSyncAutomatically() {
         mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_SETTINGS,
                 "no permission to read the sync settings");
         long identityToken = clearCallingIdentity();
         try {
             SyncManager syncManager = getSyncManager();
             if (syncManager != null) {
-                return syncManager.getSyncStorageEngine().getListenForNetworkTickles();
+                return syncManager.getSyncStorageEngine().getMasterSyncAutomatically();
             }
         } finally {
             restoreCallingIdentity(identityToken);
@@ -266,21 +287,21 @@
         return false;
     }
     
-    public void setListenForNetworkTickles(boolean flag) {
+    public void setMasterSyncAutomatically(boolean flag) {
         mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
                 "no permission to write the sync settings");
         long identityToken = clearCallingIdentity();
         try {
             SyncManager syncManager = getSyncManager();
             if (syncManager != null) {
-                syncManager.getSyncStorageEngine().setListenForNetworkTickles(flag);
+                syncManager.getSyncStorageEngine().setMasterSyncAutomatically(flag);
             }
         } finally {
             restoreCallingIdentity(identityToken);
         }
     }
 
-    public boolean isSyncActive(String account, String authority) {
+    public boolean isSyncActive(Account account, String authority) {
         mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
                 "no permission to read the sync stats");
         long identityToken = clearCallingIdentity();
@@ -311,7 +332,7 @@
         return null;
     }
     
-    public SyncStatusInfo getStatusByAuthority(String authority) {
+    public SyncStatusInfo getSyncStatus(Account account, String authority) {
         mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
                 "no permission to read the sync stats");
         long identityToken = clearCallingIdentity();
@@ -327,15 +348,14 @@
         return null;
     }
     
-    public boolean isAuthorityPending(String account, String authority) {
+    public boolean isSyncPending(Account account, String authority) {
         mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
                 "no permission to read the sync stats");
         long identityToken = clearCallingIdentity();
         try {
             SyncManager syncManager = getSyncManager();
             if (syncManager != null) {
-                return syncManager.getSyncStorageEngine().isAuthorityPending(
-                        account, authority);
+                return syncManager.getSyncStorageEngine().isSyncPending(account, authority);
             }
         } finally {
             restoreCallingIdentity(identityToken);
@@ -348,8 +368,7 @@
         try {
             SyncManager syncManager = getSyncManager();
             if (syncManager != null) {
-                syncManager.getSyncStorageEngine().addStatusChangeListener(
-                        mask, callback);
+                syncManager.getSyncStorageEngine().addStatusChangeListener(mask, callback);
             }
         } finally {
             restoreCallingIdentity(identityToken);
@@ -361,8 +380,7 @@
         try {
             SyncManager syncManager = getSyncManager();
             if (syncManager != null) {
-                syncManager.getSyncStorageEngine().removeStatusChangeListener(
-                        callback);
+                syncManager.getSyncStorageEngine().removeStatusChangeListener(callback);
             }
         } finally {
             restoreCallingIdentity(identityToken);
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 9e37ae4..c6c9835 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -1110,6 +1110,16 @@
     public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";
     /**
      * Use with {@link #getSystemService} to retrieve a
+     * {@link android.accounts.AccountManager} for receiving intents at a
+     * time of your choosing.
+     * TODO STOPSHIP perform a final review of the the account apis before shipping
+     *
+     * @see #getSystemService
+     * @see android.accounts.AccountManager
+     */
+    public static final String ACCOUNT_SERVICE = "account";
+    /**
+     * Use with {@link #getSystemService} to retrieve a
      * {@link android.app.ActivityManager} for interacting with the global
      * system state.
      *
diff --git a/core/java/android/content/Entity.aidl b/core/java/android/content/Entity.aidl
new file mode 100644
index 0000000..fb201f3
--- /dev/null
+++ b/core/java/android/content/Entity.aidl
@@ -0,0 +1,20 @@
+/* //device/java/android/android/content/Entity.aidl
+**
+** Copyright 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.content;
+
+parcelable Entity;
diff --git a/core/java/android/content/Entity.java b/core/java/android/content/Entity.java
new file mode 100644
index 0000000..325dce5
--- /dev/null
+++ b/core/java/android/content/Entity.java
@@ -0,0 +1,104 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+import android.os.Parcelable;
+import android.os.Parcel;
+import android.net.Uri;
+import android.util.Log;
+
+import java.util.ArrayList;
+
+/**
+ * Objects that pass through the ContentProvider and ContentResolver's methods that deal with
+ * Entities must implement this abstract base class and thus themselves be Parcelable.
+ */
+public final class Entity implements Parcelable {
+    final private ContentValues mValues;
+    final private ArrayList<NamedContentValues> mSubValues;
+
+    public Entity(ContentValues values) {
+        mValues = values;
+        mSubValues = new ArrayList<NamedContentValues>();
+    }
+
+    public ContentValues getEntityValues() {
+        return mValues;
+    }
+
+    public ArrayList<NamedContentValues> getSubValues() {
+        return mSubValues;
+    }
+
+    public void addSubValue(Uri uri, ContentValues values) {
+        mSubValues.add(new Entity.NamedContentValues(uri, values));
+    }
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public void writeToParcel(Parcel dest, int flags) {
+        mValues.writeToParcel(dest, 0);
+        dest.writeInt(mSubValues.size());
+        for (NamedContentValues value : mSubValues) {
+            value.uri.writeToParcel(dest, 0);
+            value.values.writeToParcel(dest, 0);
+        }
+    }
+
+    private Entity(Parcel source) {
+        mValues = ContentValues.CREATOR.createFromParcel(source);
+        final int numValues = source.readInt();
+        mSubValues = new ArrayList<NamedContentValues>(numValues);
+        for (int i = 0; i < numValues; i++) {
+            final Uri uri = Uri.CREATOR.createFromParcel(source);
+            final ContentValues values = ContentValues.CREATOR.createFromParcel(source);
+            mSubValues.add(new NamedContentValues(uri, values));
+        }
+    }
+
+    public static final Creator<Entity> CREATOR = new Creator<Entity>() {
+        public Entity createFromParcel(Parcel source) {
+            return new Entity(source);
+        }
+
+        public Entity[] newArray(int size) {
+            return new Entity[size];
+        }
+    };
+
+    public static class NamedContentValues {
+        public final Uri uri;
+        public final ContentValues values;
+
+        public NamedContentValues(Uri uri, ContentValues values) {
+            this.uri = uri;
+            this.values = values;
+        }
+    }
+
+    public String toString() {
+        final StringBuilder sb = new StringBuilder();
+        sb.append("Entity: ").append(getEntityValues());
+        for (Entity.NamedContentValues namedValue : getSubValues()) {
+            sb.append("\n  ").append(namedValue.uri);
+            sb.append("\n  -> ").append(namedValue.values);
+        }
+        return sb.toString();
+    }
+}
diff --git a/core/java/android/content/EntityIterator.java b/core/java/android/content/EntityIterator.java
new file mode 100644
index 0000000..5e5f14c
--- /dev/null
+++ b/core/java/android/content/EntityIterator.java
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+import android.os.RemoteException;
+
+public interface EntityIterator {
+    /**
+     * Returns whether there are more elements to iterate, i.e. whether the
+     * iterator is positioned in front of an element.
+     *
+     * @return {@code true} if there are more elements, {@code false} otherwise.
+     * @see #next
+     * @since Android 1.0
+     */
+    public boolean hasNext() throws RemoteException;
+
+    /**
+     * Returns the next object in the iteration, i.e. returns the element in
+     * front of the iterator and advances the iterator by one position.
+     *
+     * @return the next object.
+     * @throws java.util.NoSuchElementException
+     *             if there are no more elements.
+     * @see #hasNext
+     * @since Android 1.0
+     */
+    public Entity next() throws RemoteException;
+
+    /**
+     * Indicates that this iterator is no longer needed and that any associated resources
+     * may be released (such as a SQLite cursor).
+     */
+    public void close();
+}
diff --git a/core/java/android/content/IContentProvider.java b/core/java/android/content/IContentProvider.java
index 0606956..7e5aba5 100644
--- a/core/java/android/content/IContentProvider.java
+++ b/core/java/android/content/IContentProvider.java
@@ -28,6 +28,7 @@
 import android.os.ParcelFileDescriptor;
 
 import java.io.FileNotFoundException;
+import java.util.ArrayList;
 
 /**
  * The ipc interface to talk to a content provider.
@@ -43,19 +44,25 @@
             CursorWindow window) throws RemoteException;
     public Cursor query(Uri url, String[] projection, String selection,
             String[] selectionArgs, String sortOrder) throws RemoteException;
+    public EntityIterator queryEntities(Uri url, String selection,
+            String[] selectionArgs, String sortOrder)
+            throws RemoteException;
     public String getType(Uri url) throws RemoteException;
     public Uri insert(Uri url, ContentValues initialValues)
             throws RemoteException;
     public int bulkInsert(Uri url, ContentValues[] initialValues) throws RemoteException;
+    public Uri insertEntity(Uri uri, Entity entities) throws RemoteException;
     public int delete(Uri url, String selection, String[] selectionArgs)
             throws RemoteException;
     public int update(Uri url, ContentValues values, String selection,
             String[] selectionArgs) throws RemoteException;
+    public int updateEntity(Uri uri, Entity entity) throws RemoteException;
     public ParcelFileDescriptor openFile(Uri url, String mode)
             throws RemoteException, FileNotFoundException;
     public AssetFileDescriptor openAssetFile(Uri url, String mode)
             throws RemoteException, FileNotFoundException;
-    public ISyncAdapter getSyncAdapter() throws RemoteException;
+    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
+            throws RemoteException, OperationApplicationException;
 
     /* IPC constants */
     static final String descriptor = "android.content.IContentProvider";
@@ -65,8 +72,11 @@
     static final int INSERT_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 2;
     static final int DELETE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 3;
     static final int UPDATE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 9;
-    static final int GET_SYNC_ADAPTER_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 10;
     static final int BULK_INSERT_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 12;
     static final int OPEN_FILE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 13;
     static final int OPEN_ASSET_FILE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 14;
+    static final int INSERT_ENTITIES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 16;
+    static final int UPDATE_ENTITIES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 17;
+    static final int QUERY_ENTITIES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 18;
+    static final int APPLY_BATCH_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 19;
 }
diff --git a/core/java/android/content/IContentService.aidl b/core/java/android/content/IContentService.aidl
index 8617d949..658a5bc 100644
--- a/core/java/android/content/IContentService.aidl
+++ b/core/java/android/content/IContentService.aidl
@@ -16,8 +16,10 @@
 
 package android.content;
 
+import android.accounts.Account;
 import android.content.ActiveSyncInfo;
 import android.content.ISyncStatusObserver;
+import android.content.SyncAdapterType;
 import android.content.SyncStatusInfo;
 import android.net.Uri;
 import android.os.Bundle;
@@ -34,15 +36,15 @@
     void notifyChange(in Uri uri, IContentObserver observer,
             boolean observerWantsSelfNotifications, boolean syncToNetwork);
 
-    void startSync(in Uri url, in Bundle extras);
-    void cancelSync(in Uri uri);
+    void requestSync(in Account account, String authority, in Bundle extras);
+    void cancelSync(in Account account, String authority);
     
     /**
      * Check if the provider should be synced when a network tickle is received
      * @param providerName the provider whose setting we are querying
      * @return true of the provider should be synced when a network tickle is received
      */
-    boolean getSyncProviderAutomatically(String providerName);
+    boolean getSyncAutomatically(in Account account, String providerName);
 
     /**
      * Set whether or not the provider is synced when it receives a network tickle.
@@ -50,32 +52,38 @@
      * @param providerName the provider whose behavior is being controlled
      * @param sync true if the provider should be synced when tickles are received for it
      */
-    void setSyncProviderAutomatically(String providerName, boolean sync);
+    void setSyncAutomatically(in Account account, String providerName, boolean sync);
 
-    void setListenForNetworkTickles(boolean flag);
+    void setMasterSyncAutomatically(boolean flag);
 
-    boolean getListenForNetworkTickles();
+    boolean getMasterSyncAutomatically();
     
     /**
      * Returns true if there is currently a sync operation for the given
      * account or authority in the pending list, or actively being processed.
      */
-    boolean isSyncActive(String account, String authority);
+    boolean isSyncActive(in Account account, String authority);
     
     ActiveSyncInfo getActiveSync();
     
     /**
+     * Returns the types of the SyncAdapters that are registered with the system.
+     * @return Returns the types of the SyncAdapters that are registered with the system.
+     */
+    SyncAdapterType[] getSyncAdapterTypes();
+
+    /**
      * Returns the status that matches the authority. If there are multiples accounts for
      * the authority, the one with the latest "lastSuccessTime" status is returned.
      * @param authority the authority whose row should be selected
      * @return the SyncStatusInfo for the authority, or null if none exists
      */
-    SyncStatusInfo getStatusByAuthority(String authority);
+    SyncStatusInfo getSyncStatus(in Account account, String authority);
 
     /**
      * Return true if the pending status is true of any matching authorities.
      */
-    boolean isAuthorityPending(String account, String authority);
+    boolean isSyncPending(in Account account, String authority);
     
     void addStatusChangeListener(int mask, ISyncStatusObserver callback);
     
diff --git a/core/java/android/content/IEntityIterator.java b/core/java/android/content/IEntityIterator.java
new file mode 100644
index 0000000..1c478b3
--- /dev/null
+++ b/core/java/android/content/IEntityIterator.java
@@ -0,0 +1,181 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+import android.os.Binder;
+import android.os.IBinder;
+import android.os.IInterface;
+import android.os.Parcel;
+import android.os.RemoteException;
+import android.os.Parcelable;
+import android.util.Log;
+
+/**
+ * ICPC interface methods for an iterator over Entity objects.
+ * @hide
+ */
+public interface IEntityIterator extends IInterface {
+    /** Local-side IPC implementation stub class. */
+    public static abstract class Stub extends Binder implements IEntityIterator {
+        private static final String TAG = "IEntityIterator";
+        private static final java.lang.String DESCRIPTOR = "android.content.IEntityIterator";
+
+        /** Construct the stub at attach it to the interface. */
+        public Stub() {
+            this.attachInterface(this, DESCRIPTOR);
+        }
+        /**
+         * Cast an IBinder object into an IEntityIterator interface,
+         * generating a proxy if needed.
+         */
+        public static IEntityIterator asInterface(IBinder obj) {
+            if ((obj==null)) {
+                return null;
+            }
+            IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
+            if (((iin!=null)&&(iin instanceof IEntityIterator))) {
+                return ((IEntityIterator)iin);
+            }
+            return new IEntityIterator.Stub.Proxy(obj);
+        }
+
+        public IBinder asBinder() {
+            return this;
+        }
+
+        public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
+                throws RemoteException {
+            switch (code) {
+                case INTERFACE_TRANSACTION:
+                {
+                    reply.writeString(DESCRIPTOR);
+                    return true;
+                }
+
+                case TRANSACTION_hasNext:
+                {
+                    data.enforceInterface(DESCRIPTOR);
+                    boolean _result;
+                    try {
+                        _result = this.hasNext();
+                    } catch (Exception e) {
+                        Log.e(TAG, "caught exception in hasNext()", e);
+                        reply.writeException(e);
+                        return true;
+                    }
+                    reply.writeNoException();
+                    reply.writeInt(((_result)?(1):(0)));
+                    return true;
+                }
+
+                case TRANSACTION_next:
+                {
+                    data.enforceInterface(DESCRIPTOR);
+                    Entity entity;
+                    try {
+                        entity = this.next();
+                    } catch (RemoteException e) {
+                        Log.e(TAG, "caught exception in next()", e);
+                        reply.writeException(e);
+                        return true;
+                    }
+                    reply.writeNoException();
+                    entity.writeToParcel(reply, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
+                    return true;
+                }
+
+                case TRANSACTION_close:
+                {
+                    data.enforceInterface(DESCRIPTOR);
+                    try {
+                        this.close();
+                    } catch (RemoteException e) {
+                        Log.e(TAG, "caught exception in close()", e);
+                        reply.writeException(e);
+                        return true;
+                    }
+                    reply.writeNoException();
+                    return true;
+                }
+            }
+            return super.onTransact(code, data, reply, flags);
+        }
+
+        private static class Proxy implements IEntityIterator {
+            private IBinder mRemote;
+            Proxy(IBinder remote) {
+                mRemote = remote;
+            }
+            public IBinder asBinder() {
+                return mRemote;
+            }
+            public java.lang.String getInterfaceDescriptor() {
+                return DESCRIPTOR;
+            }
+            public boolean hasNext() throws RemoteException {
+                Parcel _data = Parcel.obtain();
+                Parcel _reply = Parcel.obtain();
+                boolean _result;
+                try {
+                    _data.writeInterfaceToken(DESCRIPTOR);
+                    mRemote.transact(Stub.TRANSACTION_hasNext, _data, _reply, 0);
+                    _reply.readException();
+                    _result = (0!=_reply.readInt());
+                }
+                finally {
+                    _reply.recycle();
+                    _data.recycle();
+                }
+                return _result;
+            }
+
+            public Entity next() throws RemoteException {
+                Parcel _data = Parcel.obtain();
+                Parcel _reply = Parcel.obtain();
+                try {
+                    _data.writeInterfaceToken(DESCRIPTOR);
+                    mRemote.transact(Stub.TRANSACTION_next, _data, _reply, 0);
+                    _reply.readException();
+                    return Entity.CREATOR.createFromParcel(_reply);
+                } finally {
+                    _reply.recycle();
+                    _data.recycle();
+                }
+            }
+
+            public void close() throws RemoteException {
+                Parcel _data = Parcel.obtain();
+                Parcel _reply = Parcel.obtain();
+                try {
+                    _data.writeInterfaceToken(DESCRIPTOR);
+                    mRemote.transact(Stub.TRANSACTION_close, _data, _reply, 0);
+                    _reply.readException();
+                }
+                finally {
+                    _reply.recycle();
+                    _data.recycle();
+                }
+            }
+        }
+        static final int TRANSACTION_hasNext = (IBinder.FIRST_CALL_TRANSACTION + 0);
+        static final int TRANSACTION_next = (IBinder.FIRST_CALL_TRANSACTION + 1);
+        static final int TRANSACTION_close = (IBinder.FIRST_CALL_TRANSACTION + 2);
+    }
+    public boolean hasNext() throws RemoteException;
+    public Entity next() throws RemoteException;
+    public void close() throws RemoteException;
+}
diff --git a/core/java/android/content/ISyncAdapter.aidl b/core/java/android/content/ISyncAdapter.aidl
index 671188c..4660527 100644
--- a/core/java/android/content/ISyncAdapter.aidl
+++ b/core/java/android/content/ISyncAdapter.aidl
@@ -16,6 +16,7 @@
 
 package android.content;
 
+import android.accounts.Account;
 import android.os.Bundle;
 import android.content.ISyncContext;
 
@@ -30,14 +31,17 @@
      *
      * @param syncContext the ISyncContext used to indicate the progress of the sync. When
      *   the sync is finished (successfully or not) ISyncContext.onFinished() must be called.
+     * @param authority the authority that should be synced
      * @param account the account that should be synced
      * @param extras SyncAdapter-specific parameters
      */
-    void startSync(ISyncContext syncContext, String account, in Bundle extras);
+    void startSync(ISyncContext syncContext, String authority,
+      in Account account, in Bundle extras);
 
     /**
      * Cancel the most recently initiated sync. Due to race conditions, this may arrive
      * after the ISyncContext.onFinished() for that sync was called.
+     * @param syncContext the ISyncContext that was passed to {@link #startSync}
      */
-    void cancelSync();
+    void cancelSync(ISyncContext syncContext);
 }
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index a5f298c..66b507d 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -75,10 +75,10 @@
  * <p>Some examples of action/data pairs are:</p>
  *
  * <ul>
- *   <li> <p><b>{@link #ACTION_VIEW} <i>content://contacts/1</i></b> -- Display
+ *   <li> <p><b>{@link #ACTION_VIEW} <i>content://contacts/people/1</i></b> -- Display
  *     information about the person whose identifier is "1".</p>
  *   </li>
- *   <li> <p><b>{@link #ACTION_DIAL} <i>content://contacts/1</i></b> -- Display
+ *   <li> <p><b>{@link #ACTION_DIAL} <i>content://contacts/people/1</i></b> -- Display
  *     the phone dialer with the person filled in.</p>
  *   </li>
  *   <li> <p><b>{@link #ACTION_VIEW} <i>tel:123</i></b> -- Display
@@ -89,10 +89,10 @@
  *   <li> <p><b>{@link #ACTION_DIAL} <i>tel:123</i></b> -- Display
  *     the phone dialer with the given number filled in.</p>
  *   </li>
- *   <li> <p><b>{@link #ACTION_EDIT} <i>content://contacts/1</i></b> -- Edit
+ *   <li> <p><b>{@link #ACTION_EDIT} <i>content://contacts/people/1</i></b> -- Edit
  *     information about the person whose identifier is "1".</p>
  *   </li>
- *   <li> <p><b>{@link #ACTION_VIEW} <i>content://contacts/</i></b> -- Display
+ *   <li> <p><b>{@link #ACTION_VIEW} <i>content://contacts/people/</i></b> -- Display
  *     a list of people, which the user can browse through.  This example is a
  *     typical top-level entry into the Contacts application, showing you the
  *     list of people. Selecting a particular person to view would result in a
@@ -156,7 +156,7 @@
  * defined in the Intent class, but applications can also define their own.
  * These strings use java style scoping, to ensure they are unique -- for
  * example, the standard {@link #ACTION_VIEW} is called
- * "android.app.action.VIEW".</p>
+ * "android.intent.action.VIEW".</p>
  *
  * <p>Put together, the set of actions, data types, categories, and extra data
  * defines a language for the system allowing for the expression of phrases
@@ -347,7 +347,7 @@
  *     <li> <p><b>{ action=android.app.action.MAIN,
  *         category=android.app.category.LAUNCHER }</b> is the actual intent
  *         used by the Launcher to populate its top-level list.</p>
- *     <li> <p><b>{ action=android.app.action.VIEW
+ *     <li> <p><b>{ action=android.intent.action.VIEW
  *          data=content://com.google.provider.NotePad/notes }</b>
  *         displays a list of all the notes under
  *         "content://com.google.provider.NotePad/notes", which
@@ -399,7 +399,7 @@
  * NoteEditor activity:</p>
  *
  * <ul>
- *     <li> <p><b>{ action=android.app.action.VIEW
+ *     <li> <p><b>{ action=android.intent.action.VIEW
  *          data=content://com.google.provider.NotePad/notes/<var>{ID}</var> }</b>
  *         shows the user the content of note <var>{ID}</var>.</p>
  *     <li> <p><b>{ action=android.app.action.EDIT
@@ -1382,7 +1382,7 @@
      * by the system.
      */
     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
-    public static final String ACTION_POWER_CONNECTED = "android.intent.action.ACTION_POWER_CONNECTED";
+    public static final String ACTION_POWER_CONNECTED = "android.intent.action.POWER_CONNECTED";
     /**
      * Broadcast Action:  External power has been removed from the device.
      * This is intended for applications that wish to register specifically to this notification.
@@ -1394,7 +1394,8 @@
      * by the system.
      */
     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
-    public static final String ACTION_POWER_DISCONNECTED = "android.intent.action.ACTION_POWER_DISCONNECTED";
+    public static final String ACTION_POWER_DISCONNECTED =
+            "android.intent.action.POWER_DISCONNECTED";
     /**
      * Broadcast Action:  Device is shutting down.
      * This is broadcast when the device is being shut down (completely turned
@@ -1731,6 +1732,20 @@
     public static final String ACTION_TTS_QUEUE_PROCESSING_COMPLETED =
             "android.intent.action.TTS_QUEUE_PROCESSING_COMPLETED";
 
+    /**
+     * Broadcast Action: a remote intent is to be broadcasted.
+     *
+     * A remote intent is used for remote RPC between devices. The remote intent
+     * is serialized and sent from one device to another device. The receiving
+     * device parses the remote intent and broadcasts it. Note that anyone can
+     * broadcast a remote intent. However, if the intent receiver of the remote intent
+     * does not trust intent broadcasts from arbitrary intent senders, it should require
+     * the sender to hold certain permissions so only trusted sender's broadcast will be
+     * let through.
+     */
+    public static final String ACTION_REMOTE_INTENT =
+            "android.intent.action.REMOTE_INTENT";
+
     // ---------------------------------------------------------------------
     // ---------------------------------------------------------------------
     // Standard intent categories (see addCategory()).
@@ -1989,6 +2004,13 @@
     public static final String EXTRA_INSTALLER_PACKAGE_NAME
             = "android.intent.extra.INSTALLER_PACKAGE_NAME";
 
+    /**
+     * Used in the extra field in the remote intent. It's astring token passed with the
+     * remote intent.
+     */
+    public static final String EXTRA_REMOTE_INTENT_TOKEN =
+            "android.intent.extra.remote_intent_token";
+
     // ---------------------------------------------------------------------
     // ---------------------------------------------------------------------
     // Intent flags (see mFlags variable).
diff --git a/core/java/android/content/OperationApplicationException.java b/core/java/android/content/OperationApplicationException.java
new file mode 100644
index 0000000..d4101bf
--- /dev/null
+++ b/core/java/android/content/OperationApplicationException.java
@@ -0,0 +1,36 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+/**
+ * Thrown when an application of a {@link ContentProviderOperation} fails due the specified
+ * constraints.
+ */
+public class OperationApplicationException extends Exception {
+    public OperationApplicationException() {
+        super();
+    }
+    public OperationApplicationException(String message) {
+        super(message);
+    }
+    public OperationApplicationException(String message, Throwable cause) {
+        super(message, cause);
+    }
+    public OperationApplicationException(Throwable cause) {
+        super(cause);
+    }
+}
diff --git a/core/java/android/content/SyncAdapter.java b/core/java/android/content/SyncAdapter.java
index 7826e50..1d5ade1 100644
--- a/core/java/android/content/SyncAdapter.java
+++ b/core/java/android/content/SyncAdapter.java
@@ -18,6 +18,7 @@
 
 import android.os.Bundle;
 import android.os.RemoteException;
+import android.accounts.Account;
 
 /**
  * @hide
@@ -29,12 +30,12 @@
     public static final int LOG_SYNC_DETAILS = 2743;
 
     class Transport extends ISyncAdapter.Stub {
-        public void startSync(ISyncContext syncContext, String account,
+        public void startSync(ISyncContext syncContext, String authority, Account account,
                 Bundle extras) throws RemoteException {
             SyncAdapter.this.startSync(new SyncContext(syncContext), account, extras);
         }
 
-        public void cancelSync() throws RemoteException {
+        public void cancelSync(ISyncContext syncContext) throws RemoteException {
             SyncAdapter.this.cancelSync();
         }
     }
@@ -42,9 +43,9 @@
     Transport mTransport = new Transport();
 
     /**
-     * Get the Transport object.  (note this is package private).
+     * Get the Transport object.
      */
-    final ISyncAdapter getISyncAdapter()
+    public final ISyncAdapter getISyncAdapter()
     {
         return mTransport;
     }
@@ -59,7 +60,7 @@
      * @param account the account that should be synced
      * @param extras SyncAdapter-specific parameters
      */
-    public abstract void startSync(SyncContext syncContext, String account, Bundle extras);
+    public abstract void startSync(SyncContext syncContext, Account account, Bundle extras);
 
     /**
      * Cancel the most recently initiated sync. Due to race conditions, this may arrive
diff --git a/include/utils/executablepath.h b/core/java/android/content/SyncAdapterType.aidl
similarity index 65%
copy from include/utils/executablepath.h
copy to core/java/android/content/SyncAdapterType.aidl
index c979432..e67841f 100644
--- a/include/utils/executablepath.h
+++ b/core/java/android/content/SyncAdapterType.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,15 +14,7 @@
  * limitations under the License.
  */
 
-#ifndef _UTILS_EXECUTABLEPATH_H
-#define _UTILS_EXECUTABLEPATH_H
+package android.content;
 
-#include <limits.h>
+parcelable SyncAdapterType;
 
-// returns the path to this executable
-#if __cplusplus
-extern "C"
-#endif
-void executablepath(char s[PATH_MAX]);
-
-#endif // _UTILS_EXECUTABLEPATH_H
diff --git a/core/java/android/content/SyncAdapterType.java b/core/java/android/content/SyncAdapterType.java
new file mode 100644
index 0000000..5a96003
--- /dev/null
+++ b/core/java/android/content/SyncAdapterType.java
@@ -0,0 +1,82 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+import android.text.TextUtils;
+import android.os.Parcelable;
+import android.os.Parcel;
+
+/**
+ * Value type that represents a SyncAdapterType. This object overrides {@link #equals} and
+ * {@link #hashCode}, making it suitable for use as the key of a {@link java.util.Map}
+ */
+public class SyncAdapterType implements Parcelable {
+    public final String authority;
+    public final String accountType;
+
+    public SyncAdapterType(String authority, String accountType) {
+        if (TextUtils.isEmpty(authority)) {
+            throw new IllegalArgumentException("the authority must not be empty: " + authority);
+        }
+        if (TextUtils.isEmpty(accountType)) {
+            throw new IllegalArgumentException("the accountType must not be empty: " + accountType);
+        }
+        this.authority = authority;
+        this.accountType = accountType;
+    }
+
+    public boolean equals(Object o) {
+        if (o == this) return true;
+        if (!(o instanceof SyncAdapterType)) return false;
+        final SyncAdapterType other = (SyncAdapterType)o;
+        return authority.equals(other.authority) && accountType.equals(other.accountType);
+    }
+
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + authority.hashCode();
+        result = 31 * result + accountType.hashCode();
+        return result;
+    }
+
+    public String toString() {
+        return "SyncAdapterType {name=" + authority + ", type=" + accountType + "}";
+    }
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeString(authority);
+        dest.writeString(accountType);
+    }
+
+    public SyncAdapterType(Parcel source) {
+        this(source.readString(), source.readString());
+    }
+
+    public static final Creator<SyncAdapterType> CREATOR = new Creator<SyncAdapterType>() {
+        public SyncAdapterType createFromParcel(Parcel source) {
+            return new SyncAdapterType(source);
+        }
+
+        public SyncAdapterType[] newArray(int size) {
+            return new SyncAdapterType[size];
+        }
+    };
+}
\ No newline at end of file
diff --git a/core/java/android/content/SyncAdaptersCache.java b/core/java/android/content/SyncAdaptersCache.java
new file mode 100644
index 0000000..ce47d76
--- /dev/null
+++ b/core/java/android/content/SyncAdaptersCache.java
@@ -0,0 +1,55 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+import android.content.pm.RegisteredServicesCache;
+import android.content.res.TypedArray;
+import android.content.Context;
+import android.util.AttributeSet;
+
+/**
+ * A cache of services that export the {@link android.content.ISyncAdapter} interface.
+ * @hide
+ */
+/* package private */ class SyncAdaptersCache extends RegisteredServicesCache<SyncAdapterType> {
+    private static final String TAG = "Account";
+
+    private static final String SERVICE_INTERFACE = "android.content.SyncAdapter";
+    private static final String SERVICE_META_DATA = "android.content.SyncAdapter";
+    private static final String ATTRIBUTES_NAME = "sync-adapter";
+
+    SyncAdaptersCache(Context context) {
+        super(context, SERVICE_INTERFACE, SERVICE_META_DATA, ATTRIBUTES_NAME);
+    }
+
+    public SyncAdapterType parseServiceAttributes(String packageName, AttributeSet attrs) {
+        TypedArray sa = mContext.getResources().obtainAttributes(attrs,
+                com.android.internal.R.styleable.SyncAdapter);
+        try {
+            final String authority =
+                    sa.getString(com.android.internal.R.styleable.SyncAdapter_contentAuthority);
+            final String accountType =
+                    sa.getString(com.android.internal.R.styleable.SyncAdapter_accountType);
+            if (authority == null || accountType == null) {
+                return null;
+            }
+            return new SyncAdapterType(authority, accountType);
+        } finally {
+            sa.recycle();
+        }
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/content/SyncManager.java b/core/java/android/content/SyncManager.java
index 4d2cce8..d54e260 100644
--- a/core/java/android/content/SyncManager.java
+++ b/core/java/android/content/SyncManager.java
@@ -21,8 +21,9 @@
 import com.android.internal.R;
 import com.android.internal.util.ArrayUtils;
 
-import android.accounts.AccountMonitor;
-import android.accounts.AccountMonitorListener;
+import android.accounts.Account;
+import android.accounts.AccountManager;
+import android.accounts.OnAccountsUpdatedListener;
 import android.app.AlarmManager;
 import android.app.Notification;
 import android.app.NotificationManager;
@@ -30,11 +31,10 @@
 import android.content.pm.ApplicationInfo;
 import android.content.pm.IPackageManager;
 import android.content.pm.PackageManager;
-import android.content.pm.ProviderInfo;
 import android.content.pm.ResolveInfo;
+import android.content.pm.RegisteredServicesCache;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
-import android.net.Uri;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.HandlerThread;
@@ -48,7 +48,6 @@
 import android.os.SystemClock;
 import android.os.SystemProperties;
 import android.provider.Settings;
-import android.text.TextUtils;
 import android.text.format.DateUtils;
 import android.text.format.Time;
 import android.util.Config;
@@ -72,11 +71,12 @@
 import java.util.Map;
 import java.util.PriorityQueue;
 import java.util.Random;
+import java.util.Collection;
 
 /**
  * @hide
  */
-class SyncManager {
+class SyncManager implements OnAccountsUpdatedListener {
     private static final String TAG = "SyncManager";
 
     // used during dumping of the Sync history
@@ -117,14 +117,11 @@
     private static final String HANDLE_SYNC_ALARM_WAKE_LOCK = "SyncManagerHandleSyncAlarmWakeLock";
 
     private Context mContext;
-    private ContentResolver mContentResolver;
 
     private String mStatusText = "";
     private long mHeartbeatTime = 0;
 
-    private AccountMonitor mAccountMonitor;
-
-    private volatile String[] mAccounts = null;
+    private volatile Account[] mAccounts = null;
 
     volatile private PowerManager.WakeLock mSyncWakeLock;
     volatile private PowerManager.WakeLock mHandleAlarmWakeLock;
@@ -151,17 +148,18 @@
     private final PendingIntent mSyncAlarmIntent;
     private final PendingIntent mSyncPollAlarmIntent;
 
+    private final SyncAdaptersCache mSyncAdapters;
+
     private BroadcastReceiver mStorageIntentReceiver =
             new BroadcastReceiver() {
                 public void onReceive(Context context, Intent intent) {
-                    ensureContentResolver();
                     String action = intent.getAction();
                     if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action)) {
                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
                             Log.v(TAG, "Internal storage is low.");
                         }
                         mStorageIsLow = true;
-                        cancelActiveSync(null /* no url */);
+                        cancelActiveSync(null /* any account */, null /* any authority */);
                     } else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) {
                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
                             Log.v(TAG, "Internal storage is ok.");
@@ -172,6 +170,43 @@
                 }
             };
 
+    private BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() {
+        public void onReceive(Context context, Intent intent) {
+            if (!mFactoryTest) {
+                AccountManager.get(mContext).addOnAccountsUpdatedListener(SyncManager.this,
+                        mSyncHandler, true /* updateImmediately */);
+            }
+        }
+    };
+
+    public void onAccountsUpdated(Account[] accounts) {
+        final boolean hadAccountsAlready = mAccounts != null;
+        mAccounts = accounts;
+
+        // if a sync is in progress yet it is no longer in the accounts list,
+        // cancel it
+        ActiveSyncContext activeSyncContext = mActiveSyncContext;
+        if (activeSyncContext != null) {
+            if (!ArrayUtils.contains(accounts, activeSyncContext.mSyncOperation.account)) {
+                Log.d(TAG, "canceling sync since the account has been removed");
+                sendSyncFinishedOrCanceledMessage(activeSyncContext,
+                        null /* no result since this is a cancel */);
+            }
+        }
+
+        // we must do this since we don't bother scheduling alarms when
+        // the accounts are not set yet
+        sendCheckAlarmsMessage();
+
+        mSyncStorageEngine.doDatabaseCleanup(accounts);
+
+        if (hadAccountsAlready && accounts.length > 0) {
+            // request a sync so that if the password was changed we will
+            // retry any sync that failed when it was wrong
+            scheduleSync(null, null, null, 0 /* no delay */);
+        }
+    }
+
     private BroadcastReceiver mConnectivityIntentReceiver =
             new BroadcastReceiver() {
         public void onReceive(Context context, Intent intent) {
@@ -229,7 +264,11 @@
 
     private static final String SYNCMANAGER_PREFS_FILENAME = "/data/system/syncmanager.prefs";
 
+    private final boolean mFactoryTest;
+
     public SyncManager(Context context, boolean factoryTest) {
+        mFactoryTest = factoryTest;
+
         // Initialize the SyncStorageEngine first, before registering observers
         // and creating threads and so on; it may fail if the disk is full.
         SyncStorageEngine.init(context);
@@ -244,6 +283,8 @@
 
         mPackageManager = null;
 
+        mSyncAdapters = new SyncAdaptersCache(mContext);
+
         mSyncAlarmIntent = PendingIntent.getBroadcast(
                 mContext, 0 /* ignored */, new Intent(ACTION_SYNC_ALARM), 0);
 
@@ -253,6 +294,9 @@
         IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
         context.registerReceiver(mConnectivityIntentReceiver, intentFilter);
 
+        intentFilter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
+        context.registerReceiver(mBootCompletedReceiver, intentFilter);
+
         intentFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
         intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
         context.registerReceiver(mStorageIntentReceiver, intentFilter);
@@ -282,48 +326,12 @@
         mHandleAlarmWakeLock.setReferenceCounted(false);
 
         mSyncStorageEngine.addStatusChangeListener(
-                SyncStorageEngine.CHANGE_SETTINGS, new ISyncStatusObserver.Stub() {
+                ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, new ISyncStatusObserver.Stub() {
             public void onStatusChanged(int which) {
                 // force the sync loop to run if the settings change
                 sendCheckAlarmsMessage();
             }
         });
-        
-        if (!factoryTest) {
-            AccountMonitorListener listener = new AccountMonitorListener() {
-                public void onAccountsUpdated(String[] accounts) {
-                    final boolean hadAccountsAlready = mAccounts != null;
-                    // copy the accounts into a new array and change mAccounts to point to it
-                    String[] newAccounts = new String[accounts.length];
-                    System.arraycopy(accounts, 0, newAccounts, 0, accounts.length);
-                    mAccounts = newAccounts;
-
-                    // if a sync is in progress yet it is no longer in the accounts list, cancel it
-                    ActiveSyncContext activeSyncContext = mActiveSyncContext;
-                    if (activeSyncContext != null) {
-                        if (!ArrayUtils.contains(newAccounts,
-                                activeSyncContext.mSyncOperation.account)) {
-                            Log.d(TAG, "canceling sync since the account has been removed");
-                            sendSyncFinishedOrCanceledMessage(activeSyncContext,
-                                    null /* no result since this is a cancel */);
-                        }
-                    }
-
-                    // we must do this since we don't bother scheduling alarms when
-                    // the accounts are not set yet
-                    sendCheckAlarmsMessage();
-
-                    mSyncStorageEngine.doDatabaseCleanup(accounts);
-
-                    if (hadAccountsAlready && mAccounts.length > 0) {
-                        // request a sync so that if the password was changed we will retry any sync
-                        // that failed when it was wrong
-                        startSync(null /* all providers */, null /* no extras */);
-                    }
-                }
-            };
-            mAccountMonitor = new AccountMonitor(context, listener);
-        }
     }
 
     private synchronized void initializeSyncPoll() {
@@ -397,7 +405,8 @@
         scheduleSyncPollAlarm(nextRelativePollTimeMs);
 
         // perform a poll
-        scheduleSync(null /* sync all syncable providers */, new Bundle(), 0 /* no delay */);
+        scheduleSync(null /* sync all syncable accounts */, null /* sync all syncable providers */,
+                new Bundle(), 0 /* no delay */);
     }
 
     private void writeSyncPollTime(long when) {
@@ -452,19 +461,13 @@
         return mSyncStorageEngine;
     }
     
-    private void ensureContentResolver() {
-        if (mContentResolver == null) {
-            mContentResolver = mContext.getContentResolver();
-        }
-    }
-
     private void ensureAlarmService() {
         if (mAlarmService == null) {
             mAlarmService = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
         }
     }
 
-    public String getSyncingAccount() {
+    public Account getSyncingAccount() {
         ActiveSyncContext activeSyncContext = mActiveSyncContext;
         return (activeSyncContext != null) ? activeSyncContext.mSyncOperation.account : null;
     }
@@ -499,20 +502,21 @@
      *
      * <p>You'll start getting callbacks after this.
      *
-     * @param url The Uri of a specific provider to be synced, or
-     *          null to sync all providers.
+     * @param requestedAccount the account to sync, may be null to signify all accounts
+     * @param requestedAuthority the authority to sync, may be null to indicate all authorities
      * @param extras a Map of SyncAdapter-specific information to control
 *          syncs of a specific provider. Can be null. Is ignored
 *          if the url is null.
      * @param delay how many milliseconds in the future to wait before performing this
-     *   sync. -1 means to make this the next sync to perform.
      */
-    public void scheduleSync(Uri url, Bundle extras, long delay) {
+    public void scheduleSync(Account requestedAccount, String requestedAuthority,
+            Bundle extras, long delay) {
         boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
         if (isLoggable) {
             Log.v(TAG, "scheduleSync:"
                     + " delay " + delay
-                    + ", url " + ((url == null) ? "(null)" : url)
+                    + ", account " + requestedAccount
+                    + ", authority " + requestedAuthority
                     + ", extras " + ((extras == null) ? "(null)" : extras));
         }
 
@@ -535,10 +539,9 @@
             delay = -1; // this means schedule at the front of the queue
         }
 
-        String[] accounts;
-        String accountFromExtras = extras.getString(ContentResolver.SYNC_EXTRAS_ACCOUNT);
-        if (!TextUtils.isEmpty(accountFromExtras)) {
-            accounts = new String[]{accountFromExtras};
+        Account[] accounts;
+        if (requestedAccount != null) {
+            accounts = new Account[]{requestedAccount};
         } else {
             // if the accounts aren't configured yet then we can't support an account-less
             // sync request
@@ -560,14 +563,14 @@
         }
 
         final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
-        final boolean force = extras.getBoolean(ContentResolver.SYNC_EXTRAS_FORCE, false);
+        final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
 
         int source;
         if (uploadOnly) {
             source = SyncStorageEngine.SOURCE_LOCAL;
-        } else if (force) {
+        } else if (manualSync) {
             source = SyncStorageEngine.SOURCE_USER;
-        } else if (url == null) {
+        } else if (requestedAuthority == null) {
             source = SyncStorageEngine.SOURCE_POLL;
         } else {
             // this isn't strictly server, since arbitrary callers can (and do) request
@@ -575,20 +578,33 @@
             source = SyncStorageEngine.SOURCE_SERVER;
         }
 
-        List<String> names = new ArrayList<String>();
-        List<ProviderInfo> providers = new ArrayList<ProviderInfo>();
-        populateProvidersList(url, names, providers);
+        // Compile a list of authorities that have sync adapters.
+        // For each authority sync each account that matches a sync adapter.
+        final HashSet<String> syncableAuthorities = new HashSet<String>();
+        for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapter :
+                mSyncAdapters.getAllServices()) {
+            syncableAuthorities.add(syncAdapter.type.authority);
+        }
 
-        final int numProviders = providers.size();
-        for (int i = 0; i < numProviders; i++) {
-            if (!providers.get(i).isSyncable) continue;
-            final String name = names.get(i);
-            for (String account : accounts) {
-                scheduleSyncOperation(new SyncOperation(account, source, name, extras, delay));
-                // TODO: remove this when Calendar supports multiple accounts. Until then
-                // pretend that only the first account exists when syncing calendar.
-                if ("calendar".equals(name)) {
-                    break;
+        // if the url was specified then replace the list of authorities with just this authority
+        // or clear it if this authority isn't syncable
+        if (requestedAuthority != null) {
+            final boolean isSyncable = syncableAuthorities.contains(requestedAuthority);
+            syncableAuthorities.clear();
+            if (isSyncable) syncableAuthorities.add(requestedAuthority);
+        }
+
+        for (String authority : syncableAuthorities) {
+            for (Account account : accounts) {
+                if (mSyncAdapters.getServiceInfo(new SyncAdapterType(authority, account.mType))
+                        != null) {
+                    scheduleSyncOperation(
+                            new SyncOperation(account, source, authority, extras, delay));
+                    // TODO: remove this when Calendar supports multiple accounts. Until then
+                    // pretend that only the first account exists when syncing calendar.
+                    if ("calendar".equals(authority)) {
+                        break;
+                    }
                 }
             }
         }
@@ -598,36 +614,10 @@
         mStatusText = message;
     }
 
-    private void populateProvidersList(Uri url, List<String> names, List<ProviderInfo> providers) {
-        try {
-            final IPackageManager packageManager = getPackageManager();
-            if (url == null) {
-                packageManager.querySyncProviders(names, providers);
-            } else {
-                final String authority = url.getAuthority();
-                ProviderInfo info = packageManager.resolveContentProvider(url.getAuthority(), 0);
-                if (info != null) {
-                    // only set this provider if the requested authority is the primary authority
-                    String[] providerNames = info.authority.split(";");
-                    if (url.getAuthority().equals(providerNames[0])) {
-                        names.add(authority);
-                        providers.add(info);
-                    }
-                }
-            }
-        } catch (RemoteException ex) {
-            // we should really never get this, but if we do then clear the lists, which
-            // will result in the dropping of the sync request
-            Log.e(TAG, "error trying to get the ProviderInfo for " + url, ex);
-            names.clear();
-            providers.clear();
-        }
-    }
-
-    public void scheduleLocalSync(Uri url) {
+    public void scheduleLocalSync(Account account, String authority) {
         final Bundle extras = new Bundle();
         extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, true);
-        scheduleSync(url, extras, LOCAL_SYNC_DELAY);
+        scheduleSync(account, authority, extras, LOCAL_SYNC_DELAY);
     }
 
     private IPackageManager getPackageManager() {
@@ -641,18 +631,16 @@
         return mPackageManager;
     }
 
-    /**
-     * Initiate a sync for this given URL, or pass null for a full sync.
-     *
-     * <p>You'll start getting callbacks after this.
-     *
-     * @param url The Uri of a specific provider to be synced, or
-     *          null to sync all providers.
-     * @param extras a Map of SyncAdapter specific information to control
-     *          syncs of a specific provider. Can be null. Is ignored
-     */
-    public void startSync(Uri url, Bundle extras) {
-        scheduleSync(url, extras, 0 /* no delay */);
+    public SyncAdapterType[] getSyncAdapterTypes() {
+        final Collection<RegisteredServicesCache.ServiceInfo<SyncAdapterType>> serviceInfos =
+                mSyncAdapters.getAllServices();
+        SyncAdapterType[] types = new SyncAdapterType[serviceInfos.size()];
+        int i = 0;
+        for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> serviceInfo : serviceInfos) {
+            types[i] = serviceInfo.type;
+            ++i;
+        }
+        return types;
     }
 
     public void updateHeartbeatTime() {
@@ -721,8 +709,7 @@
         }
 
         // Cap the delay
-        ensureContentResolver();
-        long maxSyncRetryTimeInSeconds = Settings.Gservices.getLong(mContentResolver,
+        long maxSyncRetryTimeInSeconds = Settings.Gservices.getLong(mContext.getContentResolver(),
                 Settings.Gservices.SYNC_MAX_RETRY_DELAY_IN_SECONDS,
                 DEFAULT_MAX_SYNC_RETRY_TIME_IN_SECONDS);
         if (newDelayInMs > maxSyncRetryTimeInSeconds * 1000) {
@@ -736,17 +723,22 @@
     }
 
     /**
-     * Cancel the active sync if it matches the uri. The uri corresponds to the one passed
-     * in to startSync().
-     * @param uri If non-null, the active sync is only canceled if it matches the uri.
-     *   If null, any active sync is canceled.
+     * Cancel the active sync if it matches the authority and account.
+     * @param account limit the cancelations to syncs with this account, if non-null
+     * @param authority limit the cancelations to syncs with this authority, if non-null
      */
-    public void cancelActiveSync(Uri uri) {
+    public void cancelActiveSync(Account account, String authority) {
         ActiveSyncContext activeSyncContext = mActiveSyncContext;
         if (activeSyncContext != null) {
-            // if a Uri was specified then only cancel the sync if it matches the the uri
-            if (uri != null) {
-                if (!uri.getAuthority().equals(activeSyncContext.mSyncOperation.authority)) {
+            // if an authority was specified then only cancel the sync if it matches
+            if (account != null) {
+                if (!account.equals(activeSyncContext.mSyncOperation.account)) {
+                    return;
+                }
+            }
+            // if an account was specified then only cancel the sync if it matches
+            if (authority != null) {
+                if (!authority.equals(activeSyncContext.mSyncOperation.authority)) {
                     return;
                 }
             }
@@ -798,14 +790,13 @@
     }
 
     /**
-     * Remove any scheduled sync operations that match uri. The uri corresponds to the one passed
-     * in to startSync().
-     * @param uri If non-null, only operations that match the uri are cleared.
-     *   If null, all operations are cleared.
+     * Remove scheduled sync operations.
+     * @param account limit the removals to operations with this account, if non-null
+     * @param authority limit the removals to operations with this authority, if non-null
      */
-    public void clearScheduledSyncOperations(Uri uri) {
+    public void clearScheduledSyncOperations(Account account, String authority) {
         synchronized (mSyncQueue) {
-            mSyncQueue.clear(null, uri != null ? uri.getAuthority() : null);
+            mSyncQueue.clear(account, authority);
         }
     }
 
@@ -857,7 +848,7 @@
      * Value type that represents a sync operation.
      */
     static class SyncOperation implements Comparable {
-        final String account;
+        final Account account;
         int syncSource;
         String authority;
         Bundle extras;
@@ -866,7 +857,7 @@
         long delay;
         SyncStorageEngine.PendingOperation pendingOperation;
 
-        SyncOperation(String account, int source, String authority, Bundle extras, long delay) {
+        SyncOperation(Account account, int source, String authority, Bundle extras, long delay) {
             this.account = account;
             this.syncSource = source;
             this.authority = authority;
@@ -937,21 +928,19 @@
     /**
      * @hide
      */
-    class ActiveSyncContext extends ISyncContext.Stub {
+    class ActiveSyncContext extends ISyncContext.Stub implements ServiceConnection {
         final SyncOperation mSyncOperation;
         final long mHistoryRowId;
-        final IContentProvider mContentProvider;
-        final ISyncAdapter mSyncAdapter;
+        ISyncAdapter mSyncAdapter;
         final long mStartTime;
         long mTimeoutStartTime;
 
-        public ActiveSyncContext(SyncOperation syncOperation, IContentProvider contentProvider,
-                ISyncAdapter syncAdapter, long historyRowId) {
+        public ActiveSyncContext(SyncOperation syncOperation,
+                long historyRowId) {
             super();
             mSyncOperation = syncOperation;
             mHistoryRowId = historyRowId;
-            mContentProvider = contentProvider;
-            mSyncAdapter = syncAdapter;
+            mSyncAdapter = null;
             mStartTime = SystemClock.elapsedRealtime();
             mTimeoutStartTime = mStartTime;
         }
@@ -977,6 +966,37 @@
                     .append(", syncOperation ").append(mSyncOperation);
         }
 
+        public void onServiceConnected(ComponentName name, IBinder service) {
+            Message msg = mSyncHandler.obtainMessage();
+            msg.what = SyncHandler.MESSAGE_SERVICE_CONNECTED;
+            msg.obj = new ServiceConnectionData(this, ISyncAdapter.Stub.asInterface(service));
+            mSyncHandler.sendMessage(msg);
+        }
+
+        public void onServiceDisconnected(ComponentName name) {
+            Message msg = mSyncHandler.obtainMessage();
+            msg.what = SyncHandler.MESSAGE_SERVICE_DISCONNECTED;
+            msg.obj = new ServiceConnectionData(this, null);
+            mSyncHandler.sendMessage(msg);
+        }
+
+        boolean bindToSyncAdapter(RegisteredServicesCache.ServiceInfo info) {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.d(TAG, "bindToSyncAdapter: " + info.componentName + ", connection " + this);
+            }
+            Intent intent = new Intent();
+            intent.setAction("android.content.SyncAdapter");
+            intent.setComponent(info.componentName);
+            return mContext.bindService(intent, this, Context.BIND_AUTO_CREATE);
+        }
+
+        void unBindFromSyncAdapter() {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.d(TAG, "unBindFromSyncAdapter: connection " + this);
+            }
+            mContext.unbindService(this);
+        }
+
         @Override
         public String toString() {
             StringBuilder sb = new StringBuilder();
@@ -991,6 +1011,12 @@
         if (isSyncEnabled()) {
             dumpSyncHistory(pw, sb);
         }
+
+        pw.println();
+        pw.println("SyncAdapters:");
+        for (RegisteredServicesCache.ServiceInfo info : mSyncAdapters.getAllServices()) {
+            pw.println("  " + info);
+        }
     }
 
     static String formatTime(long time) {
@@ -1004,7 +1030,7 @@
         pw.print("data connected: "); pw.println(mDataConnectionIsConnected);
         pw.print("memory low: "); pw.println(mStorageIsLow);
 
-        final String[] accounts = mAccounts;
+        final Account[] accounts = mAccounts;
         pw.print("accounts: ");
         if (accounts != null) {
             pw.println(accounts.length);
@@ -1068,7 +1094,8 @@
             for (int i=0; i<N; i++) {
                 SyncStorageEngine.PendingOperation op = ops.get(i);
                 pw.print("  #"); pw.print(i); pw.print(": account=");
-                pw.print(op.account); pw.print(" authority=");
+                pw.print(op.account.mName); pw.print(":");
+                pw.print(op.account.mType); pw.print(" authority=");
                 pw.println(op.authority);
                 if (op.extras != null && op.extras.size() > 0) {
                     sb.setLength(0);
@@ -1078,7 +1105,7 @@
             }
         }
 
-        HashSet<String> processedAccounts = new HashSet<String>();
+        HashSet<Account> processedAccounts = new HashSet<Account>();
         ArrayList<SyncStatusInfo> statuses
                 = mSyncStorageEngine.getSyncStatus();
         if (statuses != null && statuses.size() > 0) {
@@ -1090,7 +1117,7 @@
                 SyncStorageEngine.AuthorityInfo authority
                         = mSyncStorageEngine.getAuthority(status.authorityId);
                 if (authority != null) {
-                    String curAccount = authority.account;
+                    Account curAccount = authority.account;
                     
                     if (processedAccounts.contains(curAccount)) {
                         continue;
@@ -1098,8 +1125,9 @@
                     
                     processedAccounts.add(curAccount);
                     
-                    pw.print("  Account "); pw.print(authority.account);
-                    pw.println(":");
+                    pw.print("  Account "); pw.print(authority.account.mName);
+                            pw.print(" "); pw.print(authority.account.mType);
+                            pw.println(":");
                     for (int j=i; j<N; j++) {
                         status = statuses.get(j);
                         authority = mSyncStorageEngine.getAuthority(status.authorityId);
@@ -1219,9 +1247,15 @@
                 SyncStorageEngine.AuthorityInfo authority
                         = mSyncStorageEngine.getAuthority(item.authorityId);
                 pw.print("  #"); pw.print(i+1); pw.print(": ");
-                        pw.print(authority != null ? authority.account : "<no account>");
-                        pw.print(" ");
-                        pw.print(authority != null ? authority.authority : "<no account>");
+                        if (authority != null) {
+                            pw.print(authority.account.mName);
+                            pw.print(":");
+                            pw.print(authority.account.mType);
+                            pw.print(" ");
+                            pw.print(authority.authority);
+                        } else {
+                            pw.print("<no account>");
+                        }
                 Time time = new Time();
                 time.set(item.eventTime);
                 pw.print(" "); pw.print(SyncStorageEngine.SOURCES[item.source]);
@@ -1278,6 +1312,15 @@
         }
     }
 
+    class ServiceConnectionData {
+        public final ActiveSyncContext activeSyncContext;
+        public final ISyncAdapter syncAdapter;
+        ServiceConnectionData(ActiveSyncContext activeSyncContext, ISyncAdapter syncAdapter) {
+            this.activeSyncContext = activeSyncContext;
+            this.syncAdapter = syncAdapter;
+        }
+    }
+
     /**
      * Handles SyncOperation Messages that are posted to the associated
      * HandlerThread.
@@ -1287,6 +1330,8 @@
         private static final int MESSAGE_SYNC_FINISHED = 1;
         private static final int MESSAGE_SYNC_ALARM = 2;
         private static final int MESSAGE_CHECK_ALARMS = 3;
+        private static final int MESSAGE_SERVICE_CONNECTED = 4;
+        private static final int MESSAGE_SERVICE_DISCONNECTED = 5;
 
         public final SyncNotificationInfo mSyncNotificationInfo = new SyncNotificationInfo();
         private Long mAlarmScheduleTime = null;
@@ -1301,7 +1346,7 @@
          */
         class SyncNotificationInfo {
             // only valid if isActive is true
-            public String account;
+            public Account account;
 
             // only valid if isActive is true
             public String authority;
@@ -1358,6 +1403,53 @@
                         runStateIdle();
                         break;
 
+                    case SyncHandler.MESSAGE_SERVICE_CONNECTED: {
+                        ServiceConnectionData msgData = (ServiceConnectionData)msg.obj;
+                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                            Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_CONNECTED: "
+                                    + msgData.activeSyncContext
+                                    + " active is " + mActiveSyncContext);
+                        }
+                        // check that this isn't an old message
+                        if (mActiveSyncContext == msgData.activeSyncContext) {
+                            runBoundToSyncAdapter(msgData.syncAdapter);
+                        }
+                        break;
+                    }
+
+                    case SyncHandler.MESSAGE_SERVICE_DISCONNECTED: {
+                        ServiceConnectionData msgData = (ServiceConnectionData)msg.obj;
+                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                            Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_DISCONNECTED: "
+                                    + msgData.activeSyncContext
+                                    + " active is " + mActiveSyncContext);
+                        }
+                        // check that this isn't an old message
+                        if (mActiveSyncContext == msgData.activeSyncContext) {
+                            // cancel the sync if we have a syncadapter, which means one is
+                            // outstanding
+                            if (mActiveSyncContext.mSyncAdapter != null) {
+                                try {
+                                    mActiveSyncContext.mSyncAdapter.cancelSync(mActiveSyncContext);
+                                } catch (RemoteException e) {
+                                    // we don't need to retry this in this case
+                                }
+                            }
+
+                            // pretend that the sync failed with an IOException,
+                            // which is a soft error
+                            SyncResult syncResult = new SyncResult();
+                            syncResult.stats.numIoExceptions++;
+                            runSyncFinishedOrCanceled(syncResult);
+
+                            // since we are no longer syncing, check if it is time to start a new
+                            // sync
+                            runStateIdle();
+                        }
+
+                        break;
+                    }
+
                     case SyncHandler.MESSAGE_SYNC_ALARM: {
                         boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
                         if (isLoggable) {
@@ -1456,7 +1548,7 @@
 
             // If the accounts aren't known yet then we aren't ready to run. We will be kicked
             // when the account lookup request does complete.
-            String[] accounts = mAccounts;
+            Account[] accounts = mAccounts;
             if (accounts == null) {
                 if (isLoggable) {
                     Log.v(TAG, "runStateIdle: accounts not known, skipping");
@@ -1468,14 +1560,14 @@
             // Otherwise consume SyncOperations from the head of the SyncQueue until one is
             // found that is runnable (not disabled, etc). If that one is ready to run then
             // start it, otherwise just get out.
-            SyncOperation syncOperation;
+            SyncOperation op;
             final ConnectivityManager connManager = (ConnectivityManager)
                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-            final boolean backgroundDataSetting = connManager.getBackgroundDataSetting();
+            final boolean backgroundDataUsageAllowed = connManager.getBackgroundDataSetting();
             synchronized (mSyncQueue) {
                 while (true) {
-                    syncOperation = mSyncQueue.head();
-                    if (syncOperation == null) {
+                    op = mSyncQueue.head();
+                    if (op == null) {
                         if (isLoggable) {
                             Log.v(TAG, "runStateIdle: no more sync operations, returning");
                         }
@@ -1485,39 +1577,40 @@
                     // Sync is disabled, drop this operation.
                     if (!isSyncEnabled()) {
                         if (isLoggable) {
-                            Log.v(TAG, "runStateIdle: sync disabled, dropping " + syncOperation);
+                            Log.v(TAG, "runStateIdle: sync disabled, dropping " + op);
                         }
                         mSyncQueue.popHead();
                         continue;
                     }
 
-                    // skip the sync if it isn't a force and the settings are off for this provider
-                    final boolean force = syncOperation.extras.getBoolean(
-                            ContentResolver.SYNC_EXTRAS_FORCE, false);
-                    if (!force && (!backgroundDataSetting
-                            || !mSyncStorageEngine.getListenForNetworkTickles()
-                            || !mSyncStorageEngine.getSyncProviderAutomatically(
-                                    null, syncOperation.authority))) {
+                    // skip the sync if it isn't manual and auto sync is disabled
+                    final boolean manualSync = op.extras.getBoolean(
+                            ContentResolver.SYNC_EXTRAS_MANUAL, false);
+                    final boolean syncAutomatically =
+                            mSyncStorageEngine.getSyncAutomatically(op.account, op.authority)
+                                    && mSyncStorageEngine.getMasterSyncAutomatically();
+                    boolean syncAllowed =
+                            manualSync || (backgroundDataUsageAllowed && syncAutomatically);
+                    if (!syncAllowed) {
                         if (isLoggable) {
-                            Log.v(TAG, "runStateIdle: sync off, dropping " + syncOperation);
+                            Log.v(TAG, "runStateIdle: sync off, dropping " + op);
                         }
                         mSyncQueue.popHead();
                         continue;
                     }
 
                     // skip the sync if the account of this operation no longer exists
-                    if (!ArrayUtils.contains(accounts, syncOperation.account)) {
+                    if (!ArrayUtils.contains(accounts, op.account)) {
                         mSyncQueue.popHead();
                         if (isLoggable) {
-                            Log.v(TAG, "runStateIdle: account not present, dropping "
-                                    + syncOperation);
+                            Log.v(TAG, "runStateIdle: account not present, dropping " + op);
                         }
                         continue;
                     }
 
                     // go ahead and try to sync this syncOperation
                     if (isLoggable) {
-                        Log.v(TAG, "runStateIdle: found sync candidate: " + syncOperation);
+                        Log.v(TAG, "runStateIdle: found sync candidate: " + op);
                     }
                     break;
                 }
@@ -1525,11 +1618,10 @@
                 // If the first SyncOperation isn't ready to run schedule a wakeup and
                 // get out.
                 final long now = SystemClock.elapsedRealtime();
-                if (syncOperation.earliestRunTime > now) {
+                if (op.earliestRunTime > now) {
                     if (Log.isLoggable(TAG, Log.DEBUG)) {
                         Log.d(TAG, "runStateIdle: the time is " + now + " yet the next "
-                                + "sync operation is for " + syncOperation.earliestRunTime
-                                + ": " + syncOperation);
+                                + "sync operation is for " + op.earliestRunTime + ": " + op);
                     }
                     return;
                 }
@@ -1537,72 +1629,73 @@
                 // We will do this sync. Remove it from the queue and run it outside of the
                 // synchronized block.
                 if (isLoggable) {
-                    Log.v(TAG, "runStateIdle: we are going to sync " + syncOperation);
+                    Log.v(TAG, "runStateIdle: we are going to sync " + op);
                 }
                 mSyncQueue.popHead();
             }
 
-            String providerName = syncOperation.authority;
-            ensureContentResolver();
-            IContentProvider contentProvider;
-
-            // acquire the provider and update the sync history
-            try {
-                contentProvider = mContentResolver.acquireProvider(providerName);
-                if (contentProvider == null) {
-                    Log.e(TAG, "Provider " + providerName + " doesn't exist");
-                    return;
+            // connect to the sync adapter
+            SyncAdapterType syncAdapterType = new SyncAdapterType(op.authority,
+                    op.account.mType);
+            RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo =
+                    mSyncAdapters.getServiceInfo(syncAdapterType);
+            if (syncAdapterInfo == null) {
+                if (Config.LOGD) {
+                    Log.d(TAG, "can't find a sync adapter for " + syncAdapterType);
                 }
-                if (contentProvider.getSyncAdapter() == null) {
-                    Log.e(TAG, "Provider " + providerName + " isn't syncable, " + contentProvider);
-                    return;
-                }
-            } catch (RemoteException remoteExc) {
-                Log.e(TAG, "Caught a RemoteException while preparing for sync, rescheduling "
-                        + syncOperation, remoteExc);
-                rescheduleWithDelay(syncOperation);
-                return;
-            } catch (RuntimeException exc) {
-                Log.e(TAG, "Caught a RuntimeException while validating sync of " + providerName,
-                        exc);
+                runStateIdle();
                 return;
             }
 
-            final long historyRowId = insertStartSyncEvent(syncOperation);
-
-            try {
-                ISyncAdapter syncAdapter = contentProvider.getSyncAdapter();
-                ActiveSyncContext activeSyncContext = new ActiveSyncContext(syncOperation,
-                        contentProvider, syncAdapter, historyRowId);
-                mSyncWakeLock.acquire();
-                if (Log.isLoggable(TAG, Log.DEBUG)) {
-                    Log.d(TAG, "starting sync of " + syncOperation);
-                }
-                syncAdapter.startSync(activeSyncContext, syncOperation.account,
-                        syncOperation.extras);
-                mActiveSyncContext = activeSyncContext;
+            ActiveSyncContext activeSyncContext =
+                    new ActiveSyncContext(op, insertStartSyncEvent(op));
+            mActiveSyncContext = activeSyncContext;
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Log.v(TAG, "runStateIdle: setting mActiveSyncContext to " + mActiveSyncContext);
+            }
+            mSyncStorageEngine.setActiveSync(mActiveSyncContext);
+            if (!activeSyncContext.bindToSyncAdapter(syncAdapterInfo)) {
+                Log.e(TAG, "Bind attempt failed to " + syncAdapterInfo);
+                mActiveSyncContext = null;
                 mSyncStorageEngine.setActiveSync(mActiveSyncContext);
+                runStateIdle();
+                return;
+            }
+
+            mSyncWakeLock.acquire();
+            // no need to schedule an alarm, as that will be done by our caller.
+
+            // the next step will occur when we get either a timeout or a
+            // MESSAGE_SERVICE_CONNECTED or MESSAGE_SERVICE_DISCONNECTED message
+        }
+
+        private void runBoundToSyncAdapter(ISyncAdapter syncAdapter) {
+            mActiveSyncContext.mSyncAdapter = syncAdapter;
+            final SyncOperation syncOperation = mActiveSyncContext.mSyncOperation;
+            try {
+                syncAdapter.startSync(mActiveSyncContext, syncOperation.authority,
+                        syncOperation.account, syncOperation.extras);
             } catch (RemoteException remoteExc) {
                 if (Config.LOGD) {
                     Log.d(TAG, "runStateIdle: caught a RemoteException, rescheduling", remoteExc);
                 }
+                mActiveSyncContext.unBindFromSyncAdapter();
                 mActiveSyncContext = null;
                 mSyncStorageEngine.setActiveSync(mActiveSyncContext);
                 rescheduleWithDelay(syncOperation);
             } catch (RuntimeException exc) {
+                mActiveSyncContext.unBindFromSyncAdapter();
                 mActiveSyncContext = null;
                 mSyncStorageEngine.setActiveSync(mActiveSyncContext);
                 Log.e(TAG, "Caught a RuntimeException while starting the sync " + syncOperation,
                         exc);
             }
-
-            // no need to schedule an alarm, as that will be done by our caller.
         }
 
         private void runSyncFinishedOrCanceled(SyncResult syncResult) {
             boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
             if (isLoggable) Log.v(TAG, "runSyncFinishedOrCanceled");
-            ActiveSyncContext activeSyncContext = mActiveSyncContext;
+            final ActiveSyncContext activeSyncContext = mActiveSyncContext;
             mActiveSyncContext = null;
             mSyncStorageEngine.setActiveSync(mActiveSyncContext);
 
@@ -1642,10 +1735,12 @@
                     Log.v(TAG, "runSyncFinishedOrCanceled: is a cancel: operation "
                             + syncOperation);
                 }
-                try {
-                    activeSyncContext.mSyncAdapter.cancelSync();
-                } catch (RemoteException e) {
-                    // we don't need to retry this in this case
+                if (activeSyncContext.mSyncAdapter != null) {
+                    try {
+                        activeSyncContext.mSyncAdapter.cancelSync(activeSyncContext);
+                    } catch (RemoteException e) {
+                        // we don't need to retry this in this case
+                    }
                 }
                 historyMessage = SyncStorageEngine.MESG_CANCELED;
                 downstreamActivity = 0;
@@ -1655,7 +1750,7 @@
             stopSyncEvent(activeSyncContext.mHistoryRowId, syncOperation, historyMessage,
                     upstreamActivity, downstreamActivity, elapsedTime);
 
-            mContentResolver.releaseProvider(activeSyncContext.mContentProvider);
+            activeSyncContext.unBindFromSyncAdapter();
 
             if (syncResult != null && syncResult.tooManyDeletions) {
                 installHandleTooManyDeletesNotification(syncOperation.account,
@@ -1683,21 +1778,21 @@
          */
         private int syncResultToErrorNumber(SyncResult syncResult) {
             if (syncResult.syncAlreadyInProgress)
-                return SyncStorageEngine.ERROR_SYNC_ALREADY_IN_PROGRESS;
+                return ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
             if (syncResult.stats.numAuthExceptions > 0)
-                return SyncStorageEngine.ERROR_AUTHENTICATION;
+                return ContentResolver.SYNC_ERROR_AUTHENTICATION;
             if (syncResult.stats.numIoExceptions > 0)
-                return SyncStorageEngine.ERROR_IO;
+                return ContentResolver.SYNC_ERROR_IO;
             if (syncResult.stats.numParseExceptions > 0)
-                return SyncStorageEngine.ERROR_PARSE;
+                return ContentResolver.SYNC_ERROR_PARSE;
             if (syncResult.stats.numConflictDetectedExceptions > 0)
-                return SyncStorageEngine.ERROR_CONFLICT;
+                return ContentResolver.SYNC_ERROR_CONFLICT;
             if (syncResult.tooManyDeletions)
-                return SyncStorageEngine.ERROR_TOO_MANY_DELETIONS;
+                return ContentResolver.SYNC_ERROR_TOO_MANY_DELETIONS;
             if (syncResult.tooManyRetries)
-                return SyncStorageEngine.ERROR_TOO_MANY_RETRIES;
+                return ContentResolver.SYNC_ERROR_TOO_MANY_RETRIES;
             if (syncResult.databaseError)
-                return SyncStorageEngine.ERROR_INTERNAL;
+                return ContentResolver.SYNC_ERROR_INTERNAL;
             throw new IllegalStateException("we are not in an error state, " + syncResult);
         }
 
@@ -1738,9 +1833,10 @@
                 } else {
                     final boolean timeToShowNotification =
                             now > mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY;
-                    final boolean syncIsForced = syncOperation.extras
-                            .getBoolean(ContentResolver.SYNC_EXTRAS_FORCE, false);
-                    shouldInstall = timeToShowNotification || syncIsForced;
+                    // show the notification immediately if this is a manual sync
+                    final boolean manualSync = syncOperation.extras
+                            .getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
+                    shouldInstall = timeToShowNotification || manualSync;
                 }
             }
 
@@ -1860,7 +1956,7 @@
             mContext.sendBroadcast(syncStateIntent);
         }
 
-        private void installHandleTooManyDeletesNotification(String account, String authority,
+        private void installHandleTooManyDeletesNotification(Account account, String authority,
                 long numDeletes) {
             if (mNotificationMgr == null) return;
             Intent clickIntent = new Intent();
@@ -1995,9 +2091,9 @@
             SyncOperation existingOperation = mOpsByKey.get(operationKey);
 
             // if this operation matches an existing operation that is being retried (delay > 0)
-            // and this operation isn't forced, ignore this operation
+            // and this isn't a manual sync operation, ignore this operation
             if (existingOperation != null && existingOperation.delay > 0) {
-                if (!operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_FORCE, false)) {
+                if (!operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false)) {
                     return false;
                 }
             }
@@ -2071,7 +2167,7 @@
             if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
         }
 
-        public void clear(String account, String authority) {
+        public void clear(Account account, String authority) {
             Iterator<Map.Entry<String, SyncOperation>> entries = mOpsByKey.entrySet().iterator();
             while (entries.hasNext()) {
                 Map.Entry<String, SyncOperation> entry = entries.next();
diff --git a/core/java/android/content/SyncStateContentProviderHelper.java b/core/java/android/content/SyncStateContentProviderHelper.java
index f503e6f..dc728ec 100644
--- a/core/java/android/content/SyncStateContentProviderHelper.java
+++ b/core/java/android/content/SyncStateContentProviderHelper.java
@@ -23,6 +23,7 @@
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.net.Uri;
+import android.accounts.Account;
 
 /**
  * Extends the schema of a ContentProvider to include the _sync_state table
@@ -43,14 +44,15 @@
     private static final Uri CONTENT_URI =
             Uri.parse("content://" + SYNC_STATE_AUTHORITY + "/state");
 
-    private static final String ACCOUNT_WHERE = "_sync_account = ?";
+    private static final String ACCOUNT_WHERE = "_sync_account = ? AND _sync_account_type = ?";
 
     private final Provider mInternalProviderInterface;
 
     private static final String SYNC_STATE_TABLE = "_sync_state";
-    private static long DB_VERSION = 2;
+    private static long DB_VERSION = 3;
 
-    private static final String[] ACCOUNT_PROJECTION = new String[]{"_sync_account"};
+    private static final String[] ACCOUNT_PROJECTION =
+            new String[]{"_sync_account", "_sync_account_type"};
 
     static {
         sURIMatcher.addURI(SYNC_STATE_AUTHORITY, "state", STATE);
@@ -70,8 +72,9 @@
         db.execSQL("CREATE TABLE _sync_state (" +
                    "_id INTEGER PRIMARY KEY," +
                    "_sync_account TEXT," +
+                   "_sync_account_type TEXT," +
                    "data TEXT," +
-                   "UNIQUE(_sync_account)" +
+                   "UNIQUE(_sync_account, _sync_account_type)" +
                    ");");
 
         db.execSQL("DROP TABLE IF EXISTS _sync_state_metadata");
@@ -168,15 +171,17 @@
      * @param account the account of the row that should be copied over.
      */
     public void copySyncState(SQLiteDatabase dbSrc, SQLiteDatabase dbDest,
-            String account) {
-        final String[] whereArgs = new String[]{account};
-        Cursor c = dbSrc.query(SYNC_STATE_TABLE, new String[]{"_sync_account", "data"},
+            Account account) {
+        final String[] whereArgs = new String[]{account.mName, account.mType};
+        Cursor c = dbSrc.query(SYNC_STATE_TABLE,
+                new String[]{"_sync_account", "_sync_account_type", "data"},
                 ACCOUNT_WHERE, whereArgs, null, null, null);
         try {
             if (c.moveToNext()) {
                 ContentValues values = new ContentValues();
                 values.put("_sync_account", c.getString(0));
-                values.put("data", c.getBlob(1));
+                values.put("_sync_account_type", c.getString(1));
+                values.put("data", c.getBlob(2));
                 dbDest.replace(SYNC_STATE_TABLE, "_sync_account", values);
             }
         } finally {
@@ -184,14 +189,17 @@
         }
     }
 
-    public void onAccountsChanged(String[] accounts) {
+    public void onAccountsChanged(Account[] accounts) {
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
         Cursor c = db.query(SYNC_STATE_TABLE, ACCOUNT_PROJECTION, null, null, null, null, null);
         try {
             while (c.moveToNext()) {
-                final String account = c.getString(0);
+                final String accountName = c.getString(0);
+                final String accountType = c.getString(1);
+                Account account = new Account(accountName, accountType);
                 if (!ArrayUtils.contains(accounts, account)) {
-                    db.delete(SYNC_STATE_TABLE, ACCOUNT_WHERE, new String[]{account});
+                    db.delete(SYNC_STATE_TABLE, ACCOUNT_WHERE,
+                            new String[]{accountName, accountType});
                 }
             }
         } finally {
@@ -199,9 +207,9 @@
         }
     }
 
-    public void discardSyncData(SQLiteDatabase db, String account) {
+    public void discardSyncData(SQLiteDatabase db, Account account) {
         if (account != null) {
-            db.delete(SYNC_STATE_TABLE, ACCOUNT_WHERE, new String[]{account});
+            db.delete(SYNC_STATE_TABLE, ACCOUNT_WHERE, new String[]{account.mName, account.mType});
         } else {
             db.delete(SYNC_STATE_TABLE, null, null);
         }
@@ -210,9 +218,9 @@
     /**
      * Retrieves the SyncData bytes for the given account. The byte array returned may be null.
      */
-    public byte[] readSyncDataBytes(SQLiteDatabase db, String account) {
+    public byte[] readSyncDataBytes(SQLiteDatabase db, Account account) {
         Cursor c = db.query(SYNC_STATE_TABLE, null, ACCOUNT_WHERE,
-                new String[]{account}, null, null, null);
+                new String[]{account.mName, account.mType}, null, null, null);
         try {
             if (c.moveToFirst()) {
                 return c.getBlob(c.getColumnIndexOrThrow("data"));
@@ -226,9 +234,10 @@
     /**
      * Sets the SyncData bytes for the given account. The bytes array may be null.
      */
-    public void writeSyncDataBytes(SQLiteDatabase db, String account, byte[] data) {
+    public void writeSyncDataBytes(SQLiteDatabase db, Account account, byte[] data) {
         ContentValues values = new ContentValues();
         values.put("data", data);
-        db.update(SYNC_STATE_TABLE, values, ACCOUNT_WHERE, new String[]{account});
+        db.update(SYNC_STATE_TABLE, values, ACCOUNT_WHERE,
+                new String[]{account.mName, account.mType});
     }
 }
diff --git a/include/utils/executablepath.h b/core/java/android/content/SyncStatusObserver.java
similarity index 65%
rename from include/utils/executablepath.h
rename to core/java/android/content/SyncStatusObserver.java
index c979432..663378a 100644
--- a/include/utils/executablepath.h
+++ b/core/java/android/content/SyncStatusObserver.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,15 +14,8 @@
  * limitations under the License.
  */
 
-#ifndef _UTILS_EXECUTABLEPATH_H
-#define _UTILS_EXECUTABLEPATH_H
+package android.content;
 
-#include <limits.h>
-
-// returns the path to this executable
-#if __cplusplus
-extern "C"
-#endif
-void executablepath(char s[PATH_MAX]);
-
-#endif // _UTILS_EXECUTABLEPATH_H
+public interface SyncStatusObserver {
+    void onStatusChanged(int which);
+}
diff --git a/core/java/android/content/SyncStorageEngine.java b/core/java/android/content/SyncStorageEngine.java
index 756f35c..8cc0642 100644
--- a/core/java/android/content/SyncStorageEngine.java
+++ b/core/java/android/content/SyncStorageEngine.java
@@ -24,6 +24,7 @@
 import org.xmlpull.v1.XmlPullParserException;
 import org.xmlpull.v1.XmlSerializer;
 
+import android.accounts.Account;
 import android.backup.IBackupManager;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
@@ -88,6 +89,9 @@
     /** Enum value for a user-initiated sync. */
     public static final int SOURCE_USER = 3;
 
+    private static final Intent SYNC_CONNECTION_SETTING_CHANGED_INTENT =
+            new Intent("com.android.sync.SYNC_CONN_STATUS_CHANGED");
+
     // TODO: i18n -- grab these out of resources.
     /** String names for the sync source types. */
     public static final String[] SOURCES = { "SERVER",
@@ -95,26 +99,10 @@
                                              "POLL",
                                              "USER" };
 
-    // Error types
-    public static final int ERROR_SYNC_ALREADY_IN_PROGRESS = 1;
-    public static final int ERROR_AUTHENTICATION = 2;
-    public static final int ERROR_IO = 3;
-    public static final int ERROR_PARSE = 4;
-    public static final int ERROR_CONFLICT = 5;
-    public static final int ERROR_TOO_MANY_DELETIONS = 6;
-    public static final int ERROR_TOO_MANY_RETRIES = 7;
-    public static final int ERROR_INTERNAL = 8;
-
     // The MESG column will contain one of these or one of the Error types.
     public static final String MESG_SUCCESS = "success";
     public static final String MESG_CANCELED = "canceled";
 
-    public static final int CHANGE_SETTINGS = 1<<0;
-    public static final int CHANGE_PENDING = 1<<1;
-    public static final int CHANGE_ACTIVE = 1<<2;
-    public static final int CHANGE_STATUS = 1<<3;
-    public static final int CHANGE_ALL = 0x7fffffff;
-    
     public static final int MAX_HISTORY = 15;
     
     private static final int MSG_WRITE_STATUS = 1;
@@ -122,9 +110,11 @@
     
     private static final int MSG_WRITE_STATISTICS = 2;
     private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
+
+    private static final boolean SYNC_ENABLED_DEFAULT = false;
     
     public static class PendingOperation {
-        final String account;
+        final Account account;
         final int syncSource;
         final String authority;
         final Bundle extras;        // note: read-only.
@@ -132,7 +122,7 @@
         int authorityId;
         byte[] flatExtras;
         
-        PendingOperation(String account, int source,
+        PendingOperation(Account account, int source,
                 String authority, Bundle extras) {
             this.account = account;
             this.syncSource = source;
@@ -151,26 +141,26 @@
     }
     
     static class AccountInfo {
-        final String account;
+        final Account account;
         final HashMap<String, AuthorityInfo> authorities =
                 new HashMap<String, AuthorityInfo>();
         
-        AccountInfo(String account) {
+        AccountInfo(Account account) {
             this.account = account;
         }
     }
     
     public static class AuthorityInfo {
-        final String account;
+        final Account account;
         final String authority;
         final int ident;
         boolean enabled;
-        
-        AuthorityInfo(String account, String authority, int ident) {
+
+        AuthorityInfo(Account account, String authority, int ident) {
             this.account = account;
             this.authority = authority;
             this.ident = ident;
-            enabled = true;
+            enabled = SYNC_ENABLED_DEFAULT;
         }
     }
     
@@ -202,8 +192,8 @@
     private final SparseArray<AuthorityInfo> mAuthorities =
             new SparseArray<AuthorityInfo>();
     
-    private final HashMap<String, AccountInfo> mAccounts =
-        new HashMap<String, AccountInfo>();
+    private final HashMap<Account, AccountInfo> mAccounts =
+        new HashMap<Account, AccountInfo>();
 
     private final ArrayList<PendingOperation> mPendingOperations =
             new ArrayList<PendingOperation>();
@@ -258,7 +248,7 @@
     private int mNumPendingFinished = 0;
     
     private int mNextHistoryId = 0;
-    private boolean mListenForTickles = true;
+    private boolean mMasterSyncAutomatically = true;
     
     private SyncStorageEngine(Context context) {
         mContext = context;
@@ -366,14 +356,14 @@
         }
     }
 
-    public boolean getSyncProviderAutomatically(String account, String providerName) {
+    public boolean getSyncAutomatically(Account account, String providerName) {
         synchronized (mAuthorities) {
             if (account != null) {
                 AuthorityInfo authority = getAuthorityLocked(account, providerName,
-                        "getSyncProviderAutomatically");
-                return authority != null ? authority.enabled : false;
+                        "getSyncAutomatically");
+                return authority != null && authority.enabled;
             }
-            
+
             int i = mAuthorities.size();
             while (i > 0) {
                 i--;
@@ -387,45 +377,42 @@
         }
     }
 
-    public void setSyncProviderAutomatically(String account, String providerName, boolean sync) {
+    public void setSyncAutomatically(Account account, String providerName, boolean sync) {
+        boolean wasEnabled;
         synchronized (mAuthorities) {
-            if (account != null) {
-                AuthorityInfo authority = getAuthorityLocked(account, providerName,
-                        "setSyncProviderAutomatically");
-                if (authority != null) {
-                    authority.enabled = sync;
-                }
-            } else {
-                int i = mAuthorities.size();
-                while (i > 0) {
-                    i--;
-                    AuthorityInfo authority = mAuthorities.get(i);
-                    if (authority.authority.equals(providerName)) {
-                        authority.enabled = sync;
-                    }
-                }
-            }
+            AuthorityInfo authority = getOrCreateAuthorityLocked(account, providerName, -1, false);
+            wasEnabled = authority.enabled;
+            authority.enabled = sync;
             writeAccountInfoLocked();
         }
-        
-        reportChange(CHANGE_SETTINGS);
+
+        if (!wasEnabled && sync) {
+            mContext.getContentResolver().requestSync(account, providerName, new Bundle());
+        }
+        reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
     }
 
-    public void setListenForNetworkTickles(boolean flag) {
+    public void setMasterSyncAutomatically(boolean flag) {
+        boolean old;
         synchronized (mAuthorities) {
-            mListenForTickles = flag;
+            old = mMasterSyncAutomatically;
+            mMasterSyncAutomatically = flag;
             writeAccountInfoLocked();
         }
-        reportChange(CHANGE_SETTINGS);
+        if (!old && flag) {
+            mContext.getContentResolver().requestSync(null, null, new Bundle());
+        }
+        reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
+        mContext.sendBroadcast(SYNC_CONNECTION_SETTING_CHANGED_INTENT);
     }
 
-    public boolean getListenForNetworkTickles() {
+    public boolean getMasterSyncAutomatically() {
         synchronized (mAuthorities) {
-            return mListenForTickles;
+            return mMasterSyncAutomatically;
         }
     }
     
-    public AuthorityInfo getAuthority(String account, String authority) {
+    public AuthorityInfo getAuthority(Account account, String authority) {
         synchronized (mAuthorities) {
             return getAuthorityLocked(account, authority, null);
         }
@@ -441,7 +428,7 @@
      * Returns true if there is currently a sync operation for the given
      * account or authority in the pending list, or actively being processed.
      */
-    public boolean isSyncActive(String account, String authority) {
+    public boolean isSyncActive(Account account, String authority) {
         synchronized (mAuthorities) {
             int i = mPendingOperations.size();
             while (i > 0) {
@@ -490,7 +477,7 @@
             status.pending = true;
         }
         
-        reportChange(CHANGE_PENDING);
+        reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
         return op;
     }
 
@@ -536,7 +523,7 @@
             }
         }
         
-        reportChange(CHANGE_PENDING);
+        reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
         return res;
     }
 
@@ -552,7 +539,7 @@
             }
             writePendingOperationsLocked();
         }
-        reportChange(CHANGE_PENDING);
+        reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
         return num;
     }
 
@@ -580,7 +567,7 @@
      * Called when the set of account has changed, given the new array of
      * active accounts.
      */
-    public void doDatabaseCleanup(String[] accounts) {
+    public void doDatabaseCleanup(Account[] accounts) {
         synchronized (mAuthorities) {
             if (DEBUG) Log.w(TAG, "Updating for new accounts...");
             SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
@@ -659,20 +646,20 @@
             }
         }
         
-        reportChange(CHANGE_ACTIVE);
+        reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
     }
 
     /**
      * To allow others to send active change reports, to poke clients.
      */
     public void reportActiveChange() {
-        reportChange(CHANGE_ACTIVE);
+        reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
     }
     
     /**
      * Note that sync has started for the given account and authority.
      */
-    public long insertStartSyncEvent(String accountName, String authorityName,
+    public long insertStartSyncEvent(Account accountName, String authorityName,
             long now, int source) {
         long id;
         synchronized (mAuthorities) {
@@ -698,7 +685,7 @@
             if (DEBUG) Log.v(TAG, "returning historyId " + id);
         }
         
-        reportChange(CHANGE_STATUS);
+        reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
         return id;
     }
 
@@ -802,7 +789,7 @@
             }            
         }
         
-        reportChange(CHANGE_STATUS);
+        reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
     }
 
     /**
@@ -860,7 +847,7 @@
     /**
      * Return true if the pending status is true of any matching authorities.
      */
-    public boolean isAuthorityPending(String account, String authority) {
+    public boolean isSyncPending(Account account, String authority) {
         synchronized (mAuthorities) {
             final int N = mSyncStatus.size();
             for (int i=0; i<N; i++) {
@@ -916,7 +903,7 @@
      */
     public long getInitialSyncFailureTime() {
         synchronized (mAuthorities) {
-            if (!mListenForTickles) {
+            if (!mMasterSyncAutomatically) {
                 return 0;
             }
             
@@ -957,7 +944,7 @@
      * @param tag If non-null, this will be used in a log message if the
      * requested authority does not exist.
      */
-    private AuthorityInfo getAuthorityLocked(String accountName, String authorityName,
+    private AuthorityInfo getAuthorityLocked(Account accountName, String authorityName,
             String tag) {
         AccountInfo account = mAccounts.get(accountName);
         if (account == null) {
@@ -977,7 +964,7 @@
         return authority;
     }
     
-    private AuthorityInfo getOrCreateAuthorityLocked(String accountName,
+    private AuthorityInfo getOrCreateAuthorityLocked(Account accountName,
             String authorityName, int ident, boolean doWrite) {
         AccountInfo account = mAccounts.get(accountName);
         if (account == null) {
@@ -1050,7 +1037,7 @@
             if ("accounts".equals(tagName)) {
                 String listen = parser.getAttributeValue(
                         null, "listen-for-tickles");
-                mListenForTickles = listen == null
+                mMasterSyncAutomatically = listen == null
                             || Boolean.parseBoolean(listen);
                 eventType = parser.next();
                 do {
@@ -1068,6 +1055,11 @@
                             if (id >= 0) {
                                 String accountName = parser.getAttributeValue(
                                         null, "account");
+                                String accountType = parser.getAttributeValue(
+                                        null, "type");
+                                if (accountType == null) {
+                                    accountType = "com.google.GAIA";
+                                }
                                 String authorityName = parser.getAttributeValue(
                                         null, "authority");
                                 String enabled = parser.getAttributeValue(
@@ -1079,7 +1071,8 @@
                                 if (authority == null) {
                                     if (DEBUG_FILE) Log.v(TAG, "Creating entry");
                                     authority = getOrCreateAuthorityLocked(
-                                        accountName, authorityName, id, false);
+                                            new Account(accountName, accountType),
+                                            authorityName, id, false);
                                 }
                                 if (authority != null) {
                                     authority.enabled = enabled == null
@@ -1125,7 +1118,7 @@
             out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
             
             out.startTag(null, "accounts");
-            if (!mListenForTickles) {
+            if (!mMasterSyncAutomatically) {
                 out.attribute(null, "listen-for-tickles", "false");
             }
             
@@ -1134,7 +1127,8 @@
                 AuthorityInfo authority = mAuthorities.get(i);
                 out.startTag(null, "authority");
                 out.attribute(null, "id", Integer.toString(authority.ident));
-                out.attribute(null, "account", authority.account);
+                out.attribute(null, "account", authority.account.mName);
+                out.attribute(null, "type", authority.account.mType);
                 out.attribute(null, "authority", authority.authority);
                 if (!authority.enabled) {
                     out.attribute(null, "enabled", "false");
@@ -1183,6 +1177,8 @@
         }
         
         if (db != null) {
+            final boolean hasType = db.getVersion() >= 11;
+            
             // Copy in all of the status information, as well as accounts.
             if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
             SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
@@ -1190,6 +1186,9 @@
             HashMap<String,String> map = new HashMap<String,String>();
             map.put("_id", "status._id as _id");
             map.put("account", "stats.account as account");
+            if (hasType) {
+                map.put("account_type", "stats.account_type as account_type");
+            }
             map.put("authority", "stats.authority as authority");
             map.put("totalElapsedTime", "totalElapsedTime");
             map.put("numSyncs", "numSyncs");
@@ -1208,9 +1207,15 @@
             Cursor c = qb.query(db, null, null, null, null, null, null);
             while (c.moveToNext()) {
                 String accountName = c.getString(c.getColumnIndex("account"));
+                String accountType = hasType
+                        ? c.getString(c.getColumnIndex("account_type")) : null;
+                if (accountType == null) {
+                    accountType = "com.google.GAIA";
+                }
                 String authorityName = c.getString(c.getColumnIndex("authority"));
                 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
-                        accountName, authorityName, -1, false);
+                        new Account(accountName, accountType),
+                        authorityName, -1, false);
                 if (authority != null) {
                     int i = mSyncStatus.size();
                     boolean found = false;
@@ -1253,13 +1258,18 @@
                 String value = c.getString(c.getColumnIndex("value"));
                 if (name == null) continue;
                 if (name.equals("listen_for_tickles")) {
-                    setListenForNetworkTickles(value == null
-                            || Boolean.parseBoolean(value));
+                    setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value));
                 } else if (name.startsWith("sync_provider_")) {
                     String provider = name.substring("sync_provider_".length(),
                             name.length());
-                    setSyncProviderAutomatically(null, provider,
-                            value == null || Boolean.parseBoolean(value));
+                    int i = mAuthorities.size();
+                    while (i > 0) {
+                        i--;
+                        AuthorityInfo authority = mAuthorities.get(i);
+                        if (authority.authority.equals(provider)) {
+                            authority.enabled = value == null || Boolean.parseBoolean(value);
+                        }
+                    }
                 }
             }
             
diff --git a/core/java/android/content/SyncableContentProvider.java b/core/java/android/content/SyncableContentProvider.java
index e0cd786..ab4e91c 100644
--- a/core/java/android/content/SyncableContentProvider.java
+++ b/core/java/android/content/SyncableContentProvider.java
@@ -19,6 +19,7 @@
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.net.Uri;
+import android.accounts.Account;
 
 import java.util.Map;
 
@@ -32,6 +33,16 @@
 public abstract class SyncableContentProvider extends ContentProvider {
     protected abstract boolean isTemporary();
 
+    private volatile TempProviderSyncAdapter mTempProviderSyncAdapter;
+
+    public void setTempProviderSyncAdapter(TempProviderSyncAdapter syncAdapter) {
+        mTempProviderSyncAdapter = syncAdapter;
+    }
+
+    public TempProviderSyncAdapter getTempProviderSyncAdapter() {
+        return mTempProviderSyncAdapter;
+    }
+
     /**
      * Close resources that must be closed. You must call this to properly release
      * the resources used by the SyncableContentProvider.
@@ -110,7 +121,7 @@
      * @param context the sync context for the operation
      * @param account
      */
-    public abstract void onSyncStart(SyncContext context, String account);
+    public abstract void onSyncStart(SyncContext context, Account account);
 
     /**
      * Called right after a sync is completed
@@ -124,7 +135,7 @@
      * The account of the most recent call to onSyncStart()
      * @return the account
      */
-    public abstract String getSyncingAccount();
+    public abstract Account getSyncingAccount();
 
     /**
      * Merge diffs from a sync source with this content provider.
@@ -194,7 +205,7 @@
      * Make sure that there are no entries for accounts that no longer exist
      * @param accountsArray the array of currently-existing accounts
      */
-    protected abstract void onAccountsChanged(String[] accountsArray);
+    protected abstract void onAccountsChanged(Account[] accountsArray);
 
     /**
      * A helper method to delete all rows whose account is not in the accounts
@@ -203,26 +214,24 @@
      *
      * @param accounts a map of existing accounts
      * @param table the table to delete from
-     * @param accountColumnName the name of the column that is expected
-     * to hold the account.
      */
-    protected abstract void deleteRowsForRemovedAccounts(Map<String, Boolean> accounts,
-            String table, String accountColumnName);
+    protected abstract void deleteRowsForRemovedAccounts(Map<Account, Boolean> accounts,
+            String table);
 
     /**
      * Called when the sync system determines that this provider should no longer
      * contain records for the specified account.
      */
-    public abstract void wipeAccount(String account);
+    public abstract void wipeAccount(Account account);
 
     /**
      * Retrieves the SyncData bytes for the given account. The byte array returned may be null.
      */
-    public abstract byte[] readSyncDataBytes(String account);
+    public abstract byte[] readSyncDataBytes(Account account);
 
     /**
      * Sets the SyncData bytes for the given account. The bytes array may be null.
      */
-    public abstract void writeSyncDataBytes(String account, byte[] data);
+    public abstract void writeSyncDataBytes(Account account, byte[] data);
 }
 
diff --git a/core/java/android/content/TempProviderSyncAdapter.java b/core/java/android/content/TempProviderSyncAdapter.java
index eb3a5da..fb05fe7 100644
--- a/core/java/android/content/TempProviderSyncAdapter.java
+++ b/core/java/android/content/TempProviderSyncAdapter.java
@@ -12,6 +12,7 @@
 import android.util.EventLog;
 import android.util.Log;
 import android.util.TimingLogger;
+import android.accounts.Account;
 
 /**
  * @hide
@@ -62,12 +63,10 @@
      *
      * @param context allows you to publish status and interact with the
      * @param account the account to sync
-     * @param forced if true then the sync was forced
+     * @param manualSync true if this sync was requested manually by the user
      * @param result information to track what happened during this sync attempt
-     * @return true, if the sync was successfully started. One reason it can
-     *   fail to start is if there is no user configured on the device.
      */
-    public abstract void onSyncStarting(SyncContext context, String account, boolean forced,
+    public abstract void onSyncStarting(SyncContext context, Account account, boolean manualSync,
             SyncResult result);
 
     /**
@@ -168,12 +167,12 @@
      * exist.
      * @param accounts the list of accounts
      */
-    public abstract void onAccountsChanged(String[] accounts);
+    public abstract void onAccountsChanged(Account[] accounts);
 
     private Context mContext;
 
     private class SyncThread extends Thread {
-        private final String mAccount;
+        private final Account mAccount;
         private final Bundle mExtras;
         private final SyncContext mSyncContext;
         private volatile boolean mIsCanceled = false;
@@ -181,7 +180,7 @@
         private long mInitialRxBytes;
         private final SyncResult mResult;
 
-        SyncThread(SyncContext syncContext, String account, Bundle extras) {
+        SyncThread(SyncContext syncContext, Account account, Bundle extras) {
             super("SyncThread");
             mAccount = account;
             mExtras = extras;
@@ -221,19 +220,19 @@
             }
         }
 
-        private void sync(SyncContext syncContext, String account, Bundle extras) {
+        private void sync(SyncContext syncContext, Account account, Bundle extras) {
             mIsCanceled = false;
 
             mProviderSyncStarted = false;
             mAdapterSyncStarted = false;
             String message = null;
 
-            boolean syncForced = extras.getBoolean(ContentResolver.SYNC_EXTRAS_FORCE, false);
+            boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
 
             try {
                 mProvider.onSyncStart(syncContext, account);
                 mProviderSyncStarted = true;
-                onSyncStarting(syncContext, account, syncForced, mResult);
+                onSyncStarting(syncContext, account, manualSync, mResult);
                 if (mResult.hasError()) {
                     message = "SyncAdapter failed while trying to start sync";
                     return;
@@ -273,7 +272,7 @@
             }
         }
 
-        private void runSyncLoop(SyncContext syncContext, String account, Bundle extras) {
+        private void runSyncLoop(SyncContext syncContext, Account account, Bundle extras) {
             TimingLogger syncTimer = new TimingLogger(TAG + "Profiling", "sync");
             syncTimer.addSplit("start");
             int loopCount = 0;
@@ -518,7 +517,7 @@
         EventLog.writeEvent(SyncAdapter.LOG_SYNC_DETAILS, TAG, bytesSent, bytesReceived, "");
     }
 
-    public void startSync(SyncContext syncContext, String account, Bundle extras) {
+    public void startSync(SyncContext syncContext, Account account, Bundle extras) {
         if (mSyncThread != null) {
             syncContext.onFinished(SyncResult.ALREADY_IN_PROGRESS);
             return;
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index e587ca7..d9f298d 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -121,6 +121,7 @@
      *                 providers that can sync.
      * @param outInfo Filled in with a list of the ProviderInfo for each
      *                name in 'outNames'.
+     * @deprecated
      */
     void querySyncProviders(inout List<String> outNames,
             inout List<ProviderInfo> outInfo);
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 67bd1ac..bca1715 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -1429,8 +1429,6 @@
      * which market the package came from.
      * 
      * @param packageName The name of the package to query
-     *
-     * @hide
      */
     public abstract String getInstallerPackageName(String packageName);
     
diff --git a/core/java/android/content/pm/ProviderInfo.java b/core/java/android/content/pm/ProviderInfo.java
index d01460e..d61e95b 100644
--- a/core/java/android/content/pm/ProviderInfo.java
+++ b/core/java/android/content/pm/ProviderInfo.java
@@ -74,7 +74,11 @@
      *  running in the same process.  Higher goes first. */
     public int initOrder = 0;
     
-    /** Whether or not this provider is syncable. */
+    /**
+     * Whether or not this provider is syncable.
+     * @deprecated This flag is now being ignored. The current way to make a provider
+     * syncable is to provide a SyncAdapter service for a given provider/account type. 
+     */
     public boolean isSyncable = false;
 
     public ProviderInfo() {
diff --git a/core/java/android/content/pm/RegisteredServicesCache.java b/core/java/android/content/pm/RegisteredServicesCache.java
new file mode 100644
index 0000000..342de2b
--- /dev/null
+++ b/core/java/android/content/pm/RegisteredServicesCache.java
@@ -0,0 +1,238 @@
+/*
+ * 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.
+ */
+
+package android.content.pm;
+
+import android.content.Context;
+import android.content.BroadcastReceiver;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.ComponentName;
+import android.content.res.XmlResourceParser;
+import android.util.Log;
+import android.util.AttributeSet;
+import android.util.Xml;
+
+import java.util.Map;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.io.IOException;
+
+import com.google.android.collect.Maps;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlPullParser;
+
+/**
+ * A cache of registered services. This cache
+ * is built by interrogating the {@link PackageManager} and is updated as packages are added,
+ * removed and changed. The services are referred to by type V and
+ * are made available via the {@link #getServiceInfo} method.
+ * @hide
+ */
+public abstract class RegisteredServicesCache<V> {
+    private static final String TAG = "PackageManager";
+
+    public final Context mContext;
+    private final String mInterfaceName;
+    private final String mMetaDataName;
+    private final String mAttributesName;
+
+    // no need to be synchronized since the map is never changed once mService is written
+    private volatile Map<V, ServiceInfo<V>> mServices;
+
+    // synchronized on "this"
+    private BroadcastReceiver mReceiver = null;
+
+    public RegisteredServicesCache(Context context, String interfaceName, String metaDataName,
+            String attributeName) {
+        mContext = context;
+        mInterfaceName = interfaceName;
+        mMetaDataName = metaDataName;
+        mAttributesName = attributeName;
+    }
+
+    public void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
+        getAllServices();
+        Map<V, ServiceInfo<V>> services = mServices;
+        fout.println("RegisteredServicesCache: " + services.size() + " services");
+        for (ServiceInfo info : services.values()) {
+            fout.println("  " + info);
+        }
+    }
+
+    private boolean maybeRegisterForPackageChanges() {
+        synchronized (this) {
+            if (mReceiver == null) {
+                synchronized (this) {
+                    mReceiver = new BroadcastReceiver() {
+                        public void onReceive(Context context, Intent intent) {
+                            mServices = generateServicesMap();
+                        }
+                    };
+                }
+
+                IntentFilter intentFilter = new IntentFilter();
+                intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
+                intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
+                intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+                mContext.registerReceiver(mReceiver, intentFilter);
+                return true;
+            }
+            return false;
+        }
+    }
+
+    private void maybeUnregisterForPackageChanges() {
+        synchronized (this) {
+            if (mReceiver != null) {
+                mContext.unregisterReceiver(mReceiver);
+                mReceiver = null;
+            }
+        }
+    }
+
+    /**
+     * Value type that describes a Service. The information within can be used
+     * to bind to the service.
+     */
+    public static class ServiceInfo<V> {
+        public final V type;
+        public final ComponentName componentName;
+        public final int uid;
+
+        private ServiceInfo(V type, ComponentName componentName, int uid) {
+            this.type = type;
+            this.componentName = componentName;
+            this.uid = uid;
+        }
+
+        public String toString() {
+            return "ServiceInfo: " + type + ", " + componentName;
+        }
+    }
+
+    /**
+     * Accessor for the registered authenticators.
+     * @param type the account type of the authenticator
+     * @return the AuthenticatorInfo that matches the account type or null if none is present
+     */
+    public ServiceInfo<V> getServiceInfo(V type) {
+        if (mServices == null) {
+            maybeRegisterForPackageChanges();
+            mServices = generateServicesMap();
+        }
+        return mServices.get(type);
+    }
+
+    /**
+     * @return a collection of {@link RegisteredServicesCache.ServiceInfo} objects for all
+     * registered authenticators.
+     */
+    public Collection<ServiceInfo<V>> getAllServices() {
+        if (mServices == null) {
+            maybeRegisterForPackageChanges();
+            mServices = generateServicesMap();
+        }
+        return Collections.unmodifiableCollection(mServices.values());
+    }
+
+    /**
+     * Stops the monitoring of package additions, removals and changes.
+     */
+    public void close() {
+        maybeUnregisterForPackageChanges();
+    }
+
+    protected void finalize() throws Throwable {
+        synchronized (this) {
+            if (mReceiver != null) {
+                Log.e(TAG, "RegisteredServicesCache finalized without being closed");
+            }
+        }
+        close();
+        super.finalize();
+    }
+
+    private Map<V, ServiceInfo<V>> generateServicesMap() {
+        Map<V, ServiceInfo<V>> services = Maps.newHashMap();
+        PackageManager pm = mContext.getPackageManager();
+
+        List<ResolveInfo> resolveInfos =
+                pm.queryIntentServices(new Intent(mInterfaceName), PackageManager.GET_META_DATA);
+
+        for (ResolveInfo resolveInfo : resolveInfos) {
+            try {
+                ServiceInfo<V> info = parseServiceInfo(resolveInfo);
+                if (info != null) {
+                    services.put(info.type, info);
+                } else {
+                    Log.w(TAG, "Unable to load input method " + resolveInfo.toString());
+                }
+            } catch (XmlPullParserException e) {
+                Log.w(TAG, "Unable to load input method " + resolveInfo.toString(), e);
+            } catch (IOException e) {
+                Log.w(TAG, "Unable to load input method " + resolveInfo.toString(), e);
+            }
+        }
+
+        return services;
+    }
+
+    private ServiceInfo<V> parseServiceInfo(ResolveInfo service)
+            throws XmlPullParserException, IOException {
+        android.content.pm.ServiceInfo si = service.serviceInfo;
+        ComponentName componentName = new ComponentName(si.packageName, si.name);
+
+        PackageManager pm = mContext.getPackageManager();
+
+        XmlResourceParser parser = null;
+        try {
+            parser = si.loadXmlMetaData(pm, mMetaDataName);
+            if (parser == null) {
+                throw new XmlPullParserException("No " + mMetaDataName + " meta-data");
+            }
+
+            AttributeSet attrs = Xml.asAttributeSet(parser);
+
+            int type;
+            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
+                    && type != XmlPullParser.START_TAG) {
+            }
+
+            String nodeName = parser.getName();
+            if (!mAttributesName.equals(nodeName)) {
+                throw new XmlPullParserException(
+                        "Meta-data does not start with " + mAttributesName +  " tag");
+            }
+
+            V v = parseServiceAttributes(si.packageName, attrs);
+            if (v == null) {
+                return null;
+            }
+            final android.content.pm.ServiceInfo serviceInfo = service.serviceInfo;
+            final ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
+            final int uid = applicationInfo.uid;
+            return new ServiceInfo<V>(v, componentName, uid);
+        } finally {
+            if (parser != null) parser.close();
+        }
+    }
+
+    public abstract V parseServiceAttributes(String packageName, AttributeSet attrs);
+}
diff --git a/core/java/android/content/res/Configuration.java b/core/java/android/content/res/Configuration.java
index 5f44cc9..cbf8410 100644
--- a/core/java/android/content/res/Configuration.java
+++ b/core/java/android/content/res/Configuration.java
@@ -93,7 +93,8 @@
     
     /**
      * The kind of keyboard attached to the device.
-     * One of: {@link #KEYBOARD_QWERTY}, {@link #KEYBOARD_12KEY}.
+     * One of: {@link #KEYBOARD_NOKEYS}, {@link #KEYBOARD_QWERTY},
+     * {@link #KEYBOARD_12KEY}.
      */
     public int keyboard;
     
@@ -132,8 +133,8 @@
     
     /**
      * The kind of navigation method available on the device.
-     * One of: {@link #NAVIGATION_DPAD}, {@link #NAVIGATION_TRACKBALL}, 
-     * {@link #NAVIGATION_WHEEL}. 
+     * One of: {@link #NAVIGATION_NONAV}, {@link #NAVIGATION_DPAD},
+     * {@link #NAVIGATION_TRACKBALL}, {@link #NAVIGATION_WHEEL}.
      */
     public int navigation;
     
diff --git a/core/java/android/database/AbstractWindowedCursor.java b/core/java/android/database/AbstractWindowedCursor.java
index 4ac0aef..27a02e2 100644
--- a/core/java/android/database/AbstractWindowedCursor.java
+++ b/core/java/android/database/AbstractWindowedCursor.java
@@ -166,6 +166,48 @@
         return mWindow.isBlob(mPos, columnIndex);
     }
 
+    public boolean isString(int columnIndex)
+    {
+        checkPosition();
+
+        synchronized(mUpdatedRows) {
+            if (isFieldUpdated(columnIndex)) {
+                Object object = getUpdatedField(columnIndex);
+                return object == null || object instanceof String;
+            }
+        }
+
+        return mWindow.isString(mPos, columnIndex);
+    }
+
+    public boolean isLong(int columnIndex)
+    {
+        checkPosition();
+
+        synchronized(mUpdatedRows) {
+            if (isFieldUpdated(columnIndex)) {
+                Object object = getUpdatedField(columnIndex);
+                return object != null && (object instanceof Integer || object instanceof Long);
+            }
+        }
+
+        return mWindow.isLong(mPos, columnIndex);
+    }
+
+    public boolean isFloat(int columnIndex)
+    {
+        checkPosition();
+
+        synchronized(mUpdatedRows) {
+            if (isFieldUpdated(columnIndex)) {
+                Object object = getUpdatedField(columnIndex);
+                return object != null && (object instanceof Float || object instanceof Double);
+            }
+        }
+
+        return mWindow.isFloat(mPos, columnIndex);
+    }
+
     @Override
     protected void checkPosition()
     {
diff --git a/core/java/android/database/CursorWindow.java b/core/java/android/database/CursorWindow.java
index 8e26730..99db81b 100644
--- a/core/java/android/database/CursorWindow.java
+++ b/core/java/android/database/CursorWindow.java
@@ -263,7 +263,58 @@
         }
     }
 
+    /**
+     * Checks if a field contains a long
+     *
+     * @param row the row to read from, row - getStartPosition() being the actual row in the window
+     * @param col the column to read from
+     * @return {@code true} if given field is a long
+     */
+    public boolean isLong(int row, int col) {
+        acquireReference();
+        try {
+            return isInteger_native(row - mStartPos, col);
+        } finally {
+            releaseReference();
+        }
+    }
+
+    /**
+     * Checks if a field contains a float.
+     *
+     * @param row the row to read from, row - getStartPosition() being the actual row in the window
+     * @param col the column to read from
+     * @return {@code true} if given field is a float
+     */
+    public boolean isFloat(int row, int col) {
+        acquireReference();
+        try {
+            return isFloat_native(row - mStartPos, col);
+        } finally {
+            releaseReference();
+        }
+    }
+
+    /**
+     * Checks if a field contains either a String or is null.
+     *
+     * @param row the row to read from, row - getStartPosition() being the actual row in the window
+     * @param col the column to read from
+     * @return {@code true} if given field is {@code NULL} or a String
+     */
+    public boolean isString(int row, int col) {
+        acquireReference();
+        try {
+            return isString_native(row - mStartPos, col);
+        } finally {
+            releaseReference();
+        }
+    }
+
     private native boolean isBlob_native(int row, int col);
+    private native boolean isString_native(int row, int col);
+    private native boolean isInteger_native(int row, int col);
+    private native boolean isFloat_native(int row, int col);
 
     /**
      * Returns a String for the given field.
diff --git a/core/java/android/database/DatabaseUtils.java b/core/java/android/database/DatabaseUtils.java
index 10f3806..4ca6601 100644
--- a/core/java/android/database/DatabaseUtils.java
+++ b/core/java/android/database/DatabaseUtils.java
@@ -20,6 +20,7 @@
 
 import android.content.ContentValues;
 import android.content.Context;
+import android.content.OperationApplicationException;
 import android.database.sqlite.SQLiteAbortException;
 import android.database.sqlite.SQLiteConstraintException;
 import android.database.sqlite.SQLiteDatabase;
@@ -82,6 +83,8 @@
             code = 8;
         } else if (e instanceof SQLiteException) {
             code = 9;
+        } else if (e instanceof OperationApplicationException) {
+            code = 10;
         } else {
             reply.writeException(e);
             Log.e(TAG, "Writing exception to parcel", e);
@@ -123,6 +126,18 @@
         }
     }
 
+    public static void readExceptionWithOperationApplicationExceptionFromParcel(
+            Parcel reply) throws OperationApplicationException {
+        int code = reply.readInt();
+        if (code == 0) return;
+        String msg = reply.readString();
+        if (code == 10) {
+            throw new OperationApplicationException(msg);
+        } else {
+            DatabaseUtils.readExceptionFromParcel(reply, msg, code);
+        }
+    }
+
     private static final void readExceptionFromParcel(Parcel reply, String msg, int code) {
         switch (code) {
             case 2:
@@ -211,7 +226,7 @@
             sb.append(sqlString);
         sb.append('\'');
     }
-    
+
     /**
      * SQL-escape a string.
      */
@@ -240,7 +255,7 @@
             appendEscapedSQLString(sql, value.toString());
         }
     }
-    
+
     /**
      * Concatenates two SQL WHERE clauses, handling empty or null values.
      * @hide
@@ -252,12 +267,12 @@
         if (TextUtils.isEmpty(b)) {
             return a;
         }
-            
+
         return "(" + a + ") AND (" + b + ")";
     }
-    
+
     /**
-     * return the collation key 
+     * return the collation key
      * @param name
      * @return the collation key
      */
@@ -269,7 +284,7 @@
             return "";
         }
     }
-    
+
     /**
      * return the collation key in hex format
      * @param name
@@ -280,7 +295,7 @@
         char[] keys = Hex.encodeHex(arr);
         return new String(keys, 0, getKeyLen(arr) * 2);
     }
-    
+
     private static int getKeyLen(byte[] arr) {
         if (arr[arr.length - 1] != 0) {
             return arr.length;
@@ -289,16 +304,16 @@
             return arr.length-1;
         }
     }
-    
+
     private static byte[] getCollationKeyInBytes(String name) {
         if (mColl == null) {
             mColl = Collator.getInstance();
             mColl.setStrength(Collator.PRIMARY);
         }
-        return mColl.getCollationKey(name).toByteArray();        
+        return mColl.getCollationKey(name).toByteArray();
     }
-    
-    private static Collator mColl = null;    
+
+    private static Collator mColl = null;
     /**
      * Prints the contents of a Cursor to System.out. The position is restored
      * after printing.
@@ -591,10 +606,12 @@
     public static long queryNumEntries(SQLiteDatabase db, String table) {
         Cursor cursor = db.query(table, countProjection,
                 null, null, null, null, null);
-        cursor.moveToFirst();
-        long count = cursor.getLong(0);
-        cursor.deactivate();
-        return count;
+        try {
+            cursor.moveToFirst();
+            return cursor.getLong(0);
+        } finally {
+            cursor.close();
+        }
     }
 
     /**
diff --git a/core/java/android/database/sqlite/SQLiteQueryBuilder.java b/core/java/android/database/sqlite/SQLiteQueryBuilder.java
index 8a63919..af54a71 100644
--- a/core/java/android/database/sqlite/SQLiteQueryBuilder.java
+++ b/core/java/android/database/sqlite/SQLiteQueryBuilder.java
@@ -355,23 +355,26 @@
             String groupBy, String having, String sortOrder, String limit) {
         String[] projection = computeProjection(projectionIn);
 
+        StringBuilder where = new StringBuilder();
+
         if (mWhereClause.length() > 0) {
-            mWhereClause.append(')');
+            where.append(mWhereClause.toString());
+            where.append(')');
         }
 
         // Tack on the user's selection, if present.
         if (selection != null && selection.length() > 0) {
             if (mWhereClause.length() > 0) {
-                mWhereClause.append(" AND ");
+                where.append(" AND ");
             }
 
-            mWhereClause.append('(');
-            mWhereClause.append(selection);
-            mWhereClause.append(')');
+            where.append('(');
+            where.append(selection);
+            where.append(')');
         }
 
         return buildQueryString(
-                mDistinct, mTables, projection, mWhereClause.toString(),
+                mDistinct, mTables, projection, where.toString(),
                 groupBy, having, sortOrder, limit);
     }
 
diff --git a/core/java/android/hardware/Camera.java b/core/java/android/hardware/Camera.java
index 091bc17..40d2c86 100644
--- a/core/java/android/hardware/Camera.java
+++ b/core/java/android/hardware/Camera.java
@@ -56,7 +56,9 @@
     private PictureCallback mRawImageCallback;
     private PictureCallback mJpegCallback;
     private PreviewCallback mPreviewCallback;
+    private PictureCallback mPostviewCallback;
     private AutoFocusCallback mAutoFocusCallback;
+    private ZoomCallback mZoomCallback;
     private ErrorCallback mErrorCallback;
     private boolean mOneShot;
     
@@ -72,6 +74,8 @@
         mRawImageCallback = null;
         mJpegCallback = null;
         mPreviewCallback = null;
+        mPostviewCallback = null;
+        mZoomCallback = null;
 
         Looper looper;
         if ((looper = Looper.myLooper()) != null) {
@@ -245,13 +249,15 @@
                 return;
 
             case CAMERA_MSG_RAW_IMAGE:
-                if (mRawImageCallback != null)
+                if (mRawImageCallback != null) {
                     mRawImageCallback.onPictureTaken((byte[])msg.obj, mCamera);
+                }
                 return;
 
             case CAMERA_MSG_COMPRESSED_IMAGE:
-                if (mJpegCallback != null)
+                if (mJpegCallback != null) {
                     mJpegCallback.onPictureTaken((byte[])msg.obj, mCamera);
+                }
                 return;
             
             case CAMERA_MSG_PREVIEW_FRAME:
@@ -263,15 +269,29 @@
                 }
                 return;
 
+            case CAMERA_MSG_POSTVIEW_FRAME:
+                if (mPostviewCallback != null) {
+                    mPostviewCallback.onPictureTaken((byte[])msg.obj, mCamera);
+                }
+                return;
+
             case CAMERA_MSG_FOCUS:
-                if (mAutoFocusCallback != null)
+                if (mAutoFocusCallback != null) {
                     mAutoFocusCallback.onAutoFocus(msg.arg1 == 0 ? false : true, mCamera);
+                }
+                return;
+
+            case CAMERA_MSG_ZOOM:
+                if (mZoomCallback != null) {
+                    mZoomCallback.onZoomUpdate(msg.arg1, mCamera);
+                }
                 return;
 
             case CAMERA_MSG_ERROR :
                 Log.e(TAG, "Error " + msg.arg1);
-                if (mErrorCallback != null)
+                if (mErrorCallback != null) {
                     mErrorCallback.onError(msg.arg1, mCamera);
+                }
                 return;
 
             default:
@@ -364,13 +384,63 @@
      */
     public final void takePicture(ShutterCallback shutter, PictureCallback raw,
             PictureCallback jpeg) {
-        mShutterCallback = shutter;
-        mRawImageCallback = raw;
-        mJpegCallback = jpeg;
-        native_takePicture();
+        takePicture(shutter, raw, null, jpeg);
     }
     private native final void native_takePicture();
 
+    /**
+     * Triggers an asynchronous image capture. The camera service
+     * will initiate a series of callbacks to the application as the
+     * image capture progresses. The shutter callback occurs after
+     * the image is captured. This can be used to trigger a sound
+     * to let the user know that image has been captured. The raw
+     * callback occurs when the raw image data is available. The
+     * postview callback occurs when a scaled, fully processed
+     * postview image is available (NOTE: not all hardware supports
+     * this). The jpeg callback occurs when the compressed image is
+     * available. If the application does not need a particular
+     * callback, a null can be passed instead of a callback method.
+     *
+     * @param shutter   callback after the image is captured, may be null
+     * @param raw       callback with raw image data, may be null
+     * @param postview  callback with postview image data, may be null
+     * @param jpeg      callback with jpeg image data, may be null
+     */
+    public final void takePicture(ShutterCallback shutter, PictureCallback raw,
+            PictureCallback postview, PictureCallback jpeg) {
+        mShutterCallback = shutter;
+        mRawImageCallback = raw;
+        mPostviewCallback = postview;
+        mJpegCallback = jpeg;
+        native_takePicture();
+    }
+
+    /**
+     * Handles the zoom callback.
+     */
+    public interface ZoomCallback
+    {
+        /**
+         * Callback for zoom updates
+         * @param zoomLevel   new zoom level in 1/1000 increments,
+         * e.g. a zoom of 3.2x is stored as 3200. Accuracy of the
+         * value is dependent on the hardware implementation. Not
+         * all devices will generate this callback.
+         * @param camera  the Camera service object
+         */
+        void onZoomUpdate(int zoomLevel, Camera camera);
+    };
+
+    /**
+     * Registers a callback to be invoked when the zoom
+     * level is updated by the camera driver.
+     * @param cb the callback to run
+     */
+    public final void setZoomCallback(ZoomCallback cb)
+    {
+        mZoomCallback = cb;
+    }
+    
     // These match the enum in include/ui/Camera.h
     /** Unspecified camerar error.  @see #ErrorCallback */
     public static final int CAMERA_ERROR_UNKNOWN = 1;
diff --git a/core/java/android/inputmethodservice/KeyboardView.java b/core/java/android/inputmethodservice/KeyboardView.java
index 9c9c143..4d6b7be9 100755
--- a/core/java/android/inputmethodservice/KeyboardView.java
+++ b/core/java/android/inputmethodservice/KeyboardView.java
@@ -30,7 +30,6 @@
 import android.inputmethodservice.Keyboard.Key;
 import android.os.Handler;
 import android.os.Message;
-import android.os.SystemClock;
 import android.util.AttributeSet;
 import android.util.TypedValue;
 import android.view.GestureDetector;
@@ -38,6 +37,7 @@
 import android.view.LayoutInflater;
 import android.view.MotionEvent;
 import android.view.View;
+import android.view.ViewConfiguration;
 import android.view.ViewGroup.LayoutParams;
 import android.widget.PopupWindow;
 import android.widget.TextView;
@@ -207,8 +207,7 @@
 
     private static final int REPEAT_INTERVAL = 50; // ~20 keys per second
     private static final int REPEAT_START_DELAY = 400;
-    private static final int LONGPRESS_TIMEOUT = 800;
-    // Deemed to be too short : ViewConfiguration.getLongPressTimeout();
+    private static final int LONGPRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout();
 
     private static int MAX_NEARBY_KEYS = 12;
     private int[] mDistances = new int[MAX_NEARBY_KEYS];
@@ -411,6 +410,9 @@
         invalidateAllKeys();
         computeProximityThreshold(keyboard);
         mMiniKeyboardCache.clear(); // Not really necessary to do every time, but will free up views
+        // Switching to a different keyboard should abort any pending keys so that the key up
+        // doesn't get delivered to the old or new keyboard
+        mAbortKey = true; // Until the next ACTION_DOWN
     }
 
     /**
diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java
index 1153648..a3ae01b 100644
--- a/core/java/android/net/NetworkUtils.java
+++ b/core/java/android/net/NetworkUtils.java
@@ -25,6 +25,9 @@
  * {@hide}
  */
 public class NetworkUtils {
+    /** Bring the named network interface up. */
+    public native static int enableInterface(String interfaceName);
+
     /** Bring the named network interface down. */
     public native static int disableInterface(String interfaceName);
 
diff --git a/core/java/android/net/Uri.java b/core/java/android/net/Uri.java
index 421d013..298be3b 100644
--- a/core/java/android/net/Uri.java
+++ b/core/java/android/net/Uri.java
@@ -374,7 +374,7 @@
     /**
      * Creates a Uri which parses the given encoded URI string.
      *
-     * @param uriString an RFC 3296-compliant, encoded URI
+     * @param uriString an RFC 2396-compliant, encoded URI
      * @throws NullPointerException if uriString is null
      * @return Uri for this given uri string
      */
diff --git a/core/java/android/net/WebAddress.java b/core/java/android/net/WebAddress.java
index f4a2a6a..f6159de 100644
--- a/core/java/android/net/WebAddress.java
+++ b/core/java/android/net/WebAddress.java
@@ -54,7 +54,7 @@
     static Pattern sAddressPattern = Pattern.compile(
             /* scheme    */ "(?:(http|HTTP|https|HTTPS|file|FILE)\\:\\/\\/)?" +
             /* authority */ "(?:([-A-Za-z0-9$_.+!*'(),;?&=]+(?:\\:[-A-Za-z0-9$_.+!*'(),;?&=]+)?)@)?" +
-            /* host      */ "([-A-Za-z0-9%]+(?:\\.[-A-Za-z0-9%]+)*)?" +
+            /* host      */ "([-A-Za-z0-9%_]+(?:\\.[-A-Za-z0-9%_]+)*)?" +
             /* port      */ "(?:\\:([0-9]+))?" +
             /* path      */ "(\\/?.*)?");
 
diff --git a/core/java/android/net/http/ConnectionThread.java b/core/java/android/net/http/ConnectionThread.java
index 8e759e2..0b30e58 100644
--- a/core/java/android/net/http/ConnectionThread.java
+++ b/core/java/android/net/http/ConnectionThread.java
@@ -32,8 +32,8 @@
     static final int WAIT_TICK = 1000;
 
     // Performance probe
-    long mStartThreadTime;
     long mCurrentThreadTime;
+    long mTotalThreadTime;
 
     private boolean mWaiting;
     private volatile boolean mRunning = true;
@@ -69,12 +69,21 @@
      */
     public void run() {
         android.os.Process.setThreadPriority(
+                android.os.Process.THREAD_PRIORITY_DEFAULT +
                 android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
 
-        mStartThreadTime = -1;
-        mCurrentThreadTime = SystemClock.currentThreadTimeMillis();
+        // these are used to get performance data. When it is not in the timing,
+        // mCurrentThreadTime is 0. When it starts timing, mCurrentThreadTime is
+        // first set to -1, it will be set to the current thread time when the
+        // next request starts.
+        mCurrentThreadTime = 0;
+        mTotalThreadTime = 0;
 
         while (mRunning) {
+            if (mCurrentThreadTime == -1) {
+                mCurrentThreadTime = SystemClock.currentThreadTimeMillis();
+            }
+
             Request request;
 
             /* Get a request to process */
@@ -86,14 +95,14 @@
                     if (HttpLog.LOGV) HttpLog.v("ConnectionThread: Waiting for work");
                     mWaiting = true;
                     try {
-                        if (mStartThreadTime != -1) {
-                            mCurrentThreadTime = SystemClock
-                                    .currentThreadTimeMillis();
-                        }
                         mRequestFeeder.wait();
                     } catch (InterruptedException e) {
                     }
                     mWaiting = false;
+                    if (mCurrentThreadTime != 0) {
+                        mCurrentThreadTime = SystemClock
+                                .currentThreadTimeMillis();
+                    }
                 }
             } else {
                 if (HttpLog.LOGV) HttpLog.v("ConnectionThread: new request " +
@@ -123,6 +132,12 @@
                     mConnection.closeConnection();
                 }
                 mConnection = null;
+
+                if (mCurrentThreadTime > 0) {
+                    long start = mCurrentThreadTime;
+                    mCurrentThreadTime = SystemClock.currentThreadTimeMillis();
+                    mTotalThreadTime += mCurrentThreadTime - start;
+                }
             }
 
         }
diff --git a/core/java/android/net/http/Request.java b/core/java/android/net/http/Request.java
index df4fff0..1b6568e 100644
--- a/core/java/android/net/http/Request.java
+++ b/core/java/android/net/http/Request.java
@@ -67,9 +67,6 @@
     /** Set if I'm using a proxy server */
     HttpHost mProxyHost;
 
-    /** True if request is .html, .js, .css */
-    boolean mHighPriority;
-
     /** True if request has been cancelled */
     volatile boolean mCancelled = false;
 
@@ -102,26 +99,29 @@
      * @param eventHandler request will make progress callbacks on
      * this interface
      * @param headers reqeust headers
-     * @param highPriority true for .html, css, .cs
      */
     Request(String method, HttpHost host, HttpHost proxyHost, String path,
             InputStream bodyProvider, int bodyLength,
             EventHandler eventHandler,
-            Map<String, String> headers, boolean highPriority) {
+            Map<String, String> headers) {
         mEventHandler = eventHandler;
         mHost = host;
         mProxyHost = proxyHost;
         mPath = path;
-        mHighPriority = highPriority;
         mBodyProvider = bodyProvider;
         mBodyLength = bodyLength;
 
-        if (bodyProvider == null) {
+        if (bodyProvider == null && !"POST".equalsIgnoreCase(method)) {
             mHttpRequest = new BasicHttpRequest(method, getUri());
         } else {
             mHttpRequest = new BasicHttpEntityEnclosingRequest(
                     method, getUri());
-            setBodyProvider(bodyProvider, bodyLength);
+            // it is ok to have null entity for BasicHttpEntityEnclosingRequest.
+            // By using BasicHttpEntityEnclosingRequest, it will set up the
+            // correct content-length, content-type and content-encoding.
+            if (bodyProvider != null) {
+                setBodyProvider(bodyProvider, bodyLength);
+            }
         }
         addHeader(HOST_HEADER, getHostPort());
 
@@ -255,6 +255,8 @@
             // process gzip content encoding
             Header contentEncoding = entity.getContentEncoding();
             InputStream nis = null;
+            byte[] buf = null;
+            int count = 0;
             try {
                 if (contentEncoding != null &&
                     contentEncoding.getValue().equals("gzip")) {
@@ -265,9 +267,8 @@
 
                 /* accumulate enough data to make it worth pushing it
                  * up the stack */
-                byte[] buf = mConnection.getBuf();
+                buf = mConnection.getBuf();
                 int len = 0;
-                int count = 0;
                 int lowWater = buf.length / 2;
                 while (len != -1) {
                     len = nis.read(buf, count, buf.length - count);
@@ -284,6 +285,10 @@
                 /* InflaterInputStream throws an EOFException when the
                    server truncates gzipped content.  Handle this case
                    as we do truncated non-gzipped content: no error */
+                if (count > 0) {
+                    // if there is uncommited content, we should commit them
+                    mEventHandler.data(buf, count);
+                }
                 if (HttpLog.LOGV) HttpLog.v( "readResponse() handling " + e);
             } catch(IOException e) {
                 // don't throw if we have a non-OK status code
@@ -346,7 +351,7 @@
      * for debugging
      */
     public String toString() {
-        return (mHighPriority ? "P*" : "") + mPath;
+        return mPath;
     }
 
 
@@ -412,8 +417,7 @@
         }
         return status >= HttpStatus.SC_OK
             && status != HttpStatus.SC_NO_CONTENT
-            && status != HttpStatus.SC_NOT_MODIFIED
-            && status != HttpStatus.SC_RESET_CONTENT;
+            && status != HttpStatus.SC_NOT_MODIFIED;
     }
 
     /**
diff --git a/core/java/android/net/http/RequestHandle.java b/core/java/android/net/http/RequestHandle.java
index 6a97951..190ae7a 100644
--- a/core/java/android/net/http/RequestHandle.java
+++ b/core/java/android/net/http/RequestHandle.java
@@ -419,6 +419,6 @@
         mRequest = mRequestQueue.queueRequest(
                 mUrl, mUri, mMethod, mHeaders, mRequest.mEventHandler,
                 mBodyProvider,
-                mBodyLength, mRequest.mHighPriority).mRequest;
+                mBodyLength).mRequest;
     }
 }
diff --git a/core/java/android/net/http/RequestQueue.java b/core/java/android/net/http/RequestQueue.java
index 66d5722..b6f295e 100644
--- a/core/java/android/net/http/RequestQueue.java
+++ b/core/java/android/net/http/RequestQueue.java
@@ -57,9 +57,6 @@
      */
     private LinkedHashMap<HttpHost, LinkedList<Request>> mPending;
 
-    /* Support for notifying a client when queue is empty */
-    private boolean mClientWaiting = false;
-
     /** true if connected */
     boolean mNetworkConnected = true;
 
@@ -245,7 +242,9 @@
 
         public void startTiming() {
             for (int i = 0; i < mConnectionCount; i++) {
-                mThreads[i].mStartThreadTime = mThreads[i].mCurrentThreadTime;
+                ConnectionThread rt = mThreads[i];
+                rt.mCurrentThreadTime = -1;
+                rt.mTotalThreadTime = 0;
             }
             mTotalRequest = 0;
             mTotalConnection = 0;
@@ -255,12 +254,14 @@
             int totalTime = 0;
             for (int i = 0; i < mConnectionCount; i++) {
                 ConnectionThread rt = mThreads[i];
-                totalTime += (rt.mCurrentThreadTime - rt.mStartThreadTime);
-                rt.mStartThreadTime = -1;
+                if (rt.mCurrentThreadTime != -1) {
+                    totalTime += rt.mTotalThreadTime;
+                }
+                rt.mCurrentThreadTime = 0;
             }
             Log.d("Http", "Http thread used " + totalTime + " ms " + " for "
                     + mTotalRequest + " requests and " + mTotalConnection
-                    + " connections");
+                    + " new connections");
         }
 
         void logState() {
@@ -434,16 +435,14 @@
      * data.  Callbacks will be made on the supplied instance.
      * @param bodyProvider InputStream providing HTTP body, null if none
      * @param bodyLength length of body, must be 0 if bodyProvider is null
-     * @param highPriority If true, queues before low priority
-     *     requests if possible
      */
     public RequestHandle queueRequest(
             String url, String method,
             Map<String, String> headers, EventHandler eventHandler,
-            InputStream bodyProvider, int bodyLength, boolean highPriority) {
+            InputStream bodyProvider, int bodyLength) {
         WebAddress uri = new WebAddress(url);
         return queueRequest(url, uri, method, headers, eventHandler,
-                            bodyProvider, bodyLength, highPriority);
+                            bodyProvider, bodyLength);
     }
 
     /**
@@ -456,14 +455,11 @@
      * data.  Callbacks will be made on the supplied instance.
      * @param bodyProvider InputStream providing HTTP body, null if none
      * @param bodyLength length of body, must be 0 if bodyProvider is null
-     * @param highPriority If true, queues before low priority
-     *     requests if possible
      */
     public RequestHandle queueRequest(
             String url, WebAddress uri, String method, Map<String, String> headers,
             EventHandler eventHandler,
-            InputStream bodyProvider, int bodyLength,
-            boolean highPriority) {
+            InputStream bodyProvider, int bodyLength) {
 
         if (HttpLog.LOGV) HttpLog.v("RequestQueue.queueRequest " + uri);
 
@@ -478,9 +474,9 @@
 
         // set up request
         req = new Request(method, httpHost, mProxyHost, uri.mPath, bodyProvider,
-                          bodyLength, eventHandler, headers, highPriority);
+                          bodyLength, eventHandler, headers);
 
-        queueRequest(req, highPriority);
+        queueRequest(req, false);
 
         mActivePool.mTotalRequest++;
 
@@ -565,8 +561,9 @@
 
         if (mNetworkConnected && mPending.containsKey(host)) {
             LinkedList<Request> reqList = mPending.get(host);
-            ret = reqList.removeFirst();
-            if (reqList.isEmpty()) {
+            if (!reqList.isEmpty()) {
+                ret = reqList.removeFirst();
+            } else {
                 mPending.remove(host);
             }
         }
@@ -627,8 +624,9 @@
         if (iter.hasNext()) {
             Map.Entry<HttpHost, LinkedList<Request>> entry = iter.next();
             LinkedList<Request> reqList = entry.getValue();
-            ret = reqList.removeFirst();
-            if (reqList.isEmpty()) {
+            if (!reqList.isEmpty()) {
+                ret = reqList.removeFirst();
+            } else {
                 requestQueue.remove(entry.getKey());
             }
         }
diff --git a/core/java/android/os/Debug.java b/core/java/android/os/Debug.java
index d40ea6b..b0fc78e 100644
--- a/core/java/android/os/Debug.java
+++ b/core/java/android/os/Debug.java
@@ -662,6 +662,25 @@
     public static final native int getBinderDeathObjectCount();
 
     /**
+     * Primes the register map cache.
+     *
+     * Only works for classes in the bootstrap class loader.  Does not
+     * cause classes to be loaded if they're not already present.
+     *
+     * The classAndMethodDesc argument is a concatentation of the VM-internal
+     * class descriptor, method name, and method descriptor.  Examples:
+     *     Landroid/os/Looper;.loop:()V
+     *     Landroid/app/ActivityThread;.main:([Ljava/lang/String;)V
+     *
+     * @param classAndMethodDesc the method to prepare
+     *
+     * @hide
+     */
+    public static final boolean cacheRegisterMap(String classAndMethodDesc) {
+        return VMDebug.cacheRegisterMap(classAndMethodDesc);
+    }
+
+    /**
      * API for gathering and querying instruction counts.
      *
      * Example usage:
diff --git a/core/java/android/os/Exec.java b/core/java/android/os/Exec.java
deleted file mode 100644
index a50d5fe..0000000
--- a/core/java/android/os/Exec.java
+++ /dev/null
@@ -1,63 +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.os;
-
-import java.io.FileDescriptor;
-
-/**
- * @hide
- * Tools for executing commands.  Not for public consumption.
- */
-
-public class Exec
-{
-    /**
-     * @param cmd The command to execute
-     * @param arg0 The first argument to the command, may be null
-     * @param arg1 the second argument to the command, may be null
-     * @return the file descriptor of the started process.
-     * 
-     */
-    public static FileDescriptor createSubprocess(
-        String cmd, String arg0, String arg1) {
-        return createSubprocess(cmd, arg0, arg1, null);
-    }
-    
-    /**
-     * @param cmd The command to execute
-     * @param arg0 The first argument to the command, may be null
-     * @param arg1 the second argument to the command, may be null
-     * @param processId A one-element array to which the process ID of the
-     * started process will be written.
-     * @return the file descriptor of the started process.
-     * 
-     */
-     public static native FileDescriptor createSubprocess(
-        String cmd, String arg0, String arg1, int[] processId);
-    
-     public static native void setPtyWindowSize(FileDescriptor fd,
-       int row, int col, int xpixel, int ypixel);
-    /**
-     * Causes the calling thread to wait for the process associated with the
-     * receiver to finish executing.
-     * 
-     * @return The exit value of the Process being waited on
-     * 
-     */
-    public static native int waitFor(int processId);
-}
-
diff --git a/core/java/android/os/IHardwareService.aidl b/core/java/android/os/IHardwareService.aidl
index fb121bb..aebcb3c 100755
--- a/core/java/android/os/IHardwareService.aidl
+++ b/core/java/android/os/IHardwareService.aidl
@@ -20,9 +20,9 @@
 interface IHardwareService
 {
     // Vibrator support
-    void vibrate(long milliseconds);
+    void vibrate(long milliseconds, IBinder token);
     void vibratePattern(in long[] pattern, int repeat, IBinder token);
-    void cancelVibrate();
+    void cancelVibrate(IBinder token);
     
     // flashlight support
     boolean getFlashlightEnabled();
diff --git a/core/java/android/os/LatencyTimer.java b/core/java/android/os/LatencyTimer.java
new file mode 100644
index 0000000..ed2f0f9
--- /dev/null
+++ b/core/java/android/os/LatencyTimer.java
@@ -0,0 +1,94 @@
+/*
+ * 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.
+ */
+
+package android.os;
+
+import android.util.Log;
+
+import java.util.HashMap;
+
+/**
+ * A class to help with measuring latency in your code.
+ * 
+ * Suggested usage:
+ * 1) Instanciate a LatencyTimer as a class field.
+ *      private [static] LatencyTimer mLt = new LatencyTimer(100, 1000);
+ * 2) At various points in the code call sample with a string and the time delta to some fixed time.
+ *    The string should be unique at each point of the code you are measuring.
+ *      mLt.sample("before processing event", System.nanoTime() - event.getEventTimeNano());
+ *      processEvent(event);
+ *      mLt.sample("after processing event ", System.nanoTime() - event.getEventTimeNano());
+ *
+ * @hide
+ */
+public final class LatencyTimer
+{
+    final String TAG = "LatencyTimer";
+    final int mSampleSize;
+    final int mScaleFactor;
+    volatile HashMap<String, long[]> store = new HashMap<String, long[]>();
+
+    /**
+    * Creates a LatencyTimer object
+    * @param sampleSize number of samples to collect before printing out the average
+    * @param scaleFactor divisor used to make each sample smaller to prevent overflow when
+    *        (sampleSize * average sample value)/scaleFactor > Long.MAX_VALUE
+    */
+    public LatencyTimer(int sampleSize, int scaleFactor) {
+        if (scaleFactor == 0) {
+            scaleFactor = 1;
+        }
+        mScaleFactor = scaleFactor;
+        mSampleSize = sampleSize;
+    }
+
+    /**
+     * Add a sample delay for averaging.
+     * @param tag string used for printing out the result. This should be unique at each point of
+     *  this called.
+     * @param delta time difference from an unique point of reference for a particular iteration
+     */
+    public void sample(String tag, long delta) {
+        long[] array = getArray(tag);
+
+        // array[mSampleSize] holds the number of used entries
+        final int index = (int) array[mSampleSize]++;
+        array[index] = delta;
+        if (array[mSampleSize] == mSampleSize) {
+            long totalDelta = 0;
+            for (long d : array) {
+                totalDelta += d/mScaleFactor;
+            }
+            array[mSampleSize] = 0;
+            Log.i(TAG, tag + " average = " + totalDelta / mSampleSize);
+        }
+    }
+
+    private long[] getArray(String tag) {
+        long[] data = store.get(tag);
+        if (data == null) {
+            synchronized(store) {
+                data = store.get(tag);
+                if (data == null) {
+                    data = new long[mSampleSize + 1];
+                    store.put(tag, data);
+                    data[mSampleSize] = 0;
+                }
+            }
+        }
+        return data;
+    }
+}
diff --git a/core/java/android/os/MemoryFile.java b/core/java/android/os/MemoryFile.java
index c14925c..03542dd 100644
--- a/core/java/android/os/MemoryFile.java
+++ b/core/java/android/os/MemoryFile.java
@@ -52,7 +52,7 @@
     private static native void native_write(FileDescriptor fd, int address, byte[] buffer,
             int srcOffset, int destOffset, int count, boolean isUnpinned) throws IOException;
     private static native void native_pin(FileDescriptor fd, boolean pin) throws IOException;
-    private static native boolean native_is_ashmem_region(FileDescriptor fd) throws IOException;
+    private static native int native_get_mapped_size(FileDescriptor fd) throws IOException;
 
     private FileDescriptor mFD;        // ashmem file descriptor
     private int mAddress;   // address of ashmem memory
@@ -300,7 +300,20 @@
      * @hide
      */
     public static boolean isMemoryFile(FileDescriptor fd) throws IOException {
-        return native_is_ashmem_region(fd);
+        return (native_get_mapped_size(fd) >= 0);
+    }
+
+    /**
+     * Returns the size of the memory file, rounded up to a page boundary, that
+     * the file descriptor refers to, or -1 if the file descriptor does not
+     * refer to a memory file.
+     *
+     * @throws IOException If <code>fd</code> is not a valid file descriptor.
+     *
+     * @hide
+     */
+    public static int getMappedSize(FileDescriptor fd) throws IOException {
+        return native_get_mapped_size(fd);
     }
 
     /**
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 4805193..980cff3 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -739,7 +739,7 @@
     public static final native void sendSignal(int pid, int signal);
     
     /** @hide */
-    public static final native int getFreeMemory();
+    public static final native long getFreeMemory();
     
     /** @hide */
     public static final native void readProcLines(String path,
diff --git a/core/java/android/os/RemoteCallbackList.java b/core/java/android/os/RemoteCallbackList.java
index 584224f..b74af16 100644
--- a/core/java/android/os/RemoteCallbackList.java
+++ b/core/java/android/os/RemoteCallbackList.java
@@ -22,7 +22,7 @@
  * Takes care of the grunt work of maintaining a list of remote interfaces,
  * typically for the use of performing callbacks from a
  * {@link android.app.Service} to its clients.  In particular, this:
- * 
+ *
  * <ul>
  * <li> Keeps track of a set of registered {@link IInterface} callbacks,
  * taking care to identify them through their underlying unique {@link IBinder}
@@ -34,13 +34,13 @@
  * multithreaded incoming calls, and a thread-safe way to iterate over a
  * snapshot of the list without holding its lock.
  * </ul>
- * 
+ *
  * <p>To use this class, simply create a single instance along with your
  * service, and call its {@link #register} and {@link #unregister} methods
  * as client register and unregister with your service.  To call back on to
  * the registered clients, use {@link #beginBroadcast},
  * {@link #getBroadcastItem}, and {@link #finishBroadcast}.
- * 
+ *
  * <p>If a registered callback's process goes away, this class will take
  * care of automatically removing it from the list.  If you want to do
  * additional work in this situation, you can create a subclass that
@@ -52,7 +52,7 @@
     private Object[] mActiveBroadcast;
     private int mBroadcastCount = -1;
     private boolean mKilled = false;
-    
+
     private final class Callback implements IBinder.DeathRecipient {
         final E mCallback;
         final Object mCookie;
@@ -61,7 +61,7 @@
             mCallback = callback;
             mCookie = cookie;
         }
-        
+
         public void binderDied() {
             synchronized (mCallbacks) {
                 mCallbacks.remove(mCallback.asBinder());
@@ -69,7 +69,7 @@
             onCallbackDied(mCallback, mCookie);
         }
     }
-    
+
     /**
      * Simple version of {@link RemoteCallbackList#register(E, Object)}
      * that does not take a cookie object.
@@ -86,19 +86,20 @@
      * object is already in the list), then it will be left as-is.
      * Registrations are not counted; a single call to {@link #unregister}
      * will remove a callback after any number calls to register it.
-     * 
+     *
      * @param callback The callback interface to be added to the list.  Must
      * not be null -- passing null here will cause a NullPointerException.
      * Most services will want to check for null before calling this with
      * an object given from a client, so that clients can't crash the
      * service with bad data.
+     *
      * @param cookie Optional additional data to be associated with this
      * callback.
      * 
      * @return Returns true if the callback was successfully added to the list.
      * Returns false if it was not added, either because {@link #kill} had
      * previously been called or the callback's process has gone away.
-     * 
+     *
      * @see #unregister
      * @see #kill
      * @see #onCallbackDied
@@ -119,7 +120,7 @@
             }
         }
     }
-    
+
     /**
      * Remove from the list a callback that was previously added with
      * {@link #register}.  This uses the
@@ -127,14 +128,14 @@
      * find the previous registration.
      * Registrations are not counted; a single unregister call will remove
      * a callback after any number calls to {@link #register} for it.
-     * 
+     *
      * @param callback The callback to be removed from the list.  Passing
      * null here will cause a NullPointerException, so you will generally want
      * to check for null before calling.
-     * 
+     *
      * @return Returns true if the callback was found and unregistered.  Returns
      * false if the given callback was not found on the list.
-     * 
+     *
      * @see #register
      */
     public boolean unregister(E callback) {
@@ -147,13 +148,13 @@
             return false;
         }
     }
-    
+
     /**
      * Disable this callback list.  All registered callbacks are unregistered,
      * and the list is disabled so that future calls to {@link #register} will
      * fail.  This should be used when a Service is stopping, to prevent clients
      * from registering callbacks after it is stopped.
-     * 
+     *
      * @see #register
      */
     public void kill() {
@@ -165,7 +166,7 @@
             mKilled = true;
         }
     }
-    
+
     /**
      * Old version of {@link #onCallbackDied(E, Object)} that
      * does not provide a cookie.
@@ -190,7 +191,7 @@
     public void onCallbackDied(E callback, Object cookie) {
         onCallbackDied(callback);
     }
-    
+
     /**
      * Prepare to start making calls to the currently registered callbacks.
      * This creates a copy of the callback list, which you can retrieve items
@@ -199,12 +200,12 @@
      * same thread (usually by scheduling with {@link Handler}) or
      * do your own synchronization.  You must call {@link #finishBroadcast}
      * when done.
-     * 
+     *
      * <p>A typical loop delivering a broadcast looks like this:
-     * 
+     *
      * <pre>
      * int i = callbacks.beginBroadcast();
-     * while (i > 0) {
+     * while (i &gt; 0) {
      *     i--;
      *     try {
      *         callbacks.getBroadcastItem(i).somethingHappened();
@@ -214,11 +215,11 @@
      *     }
      * }
      * callbacks.finishBroadcast();</pre>
-     * 
+     *
      * @return Returns the number of callbacks in the broadcast, to be used
      * with {@link #getBroadcastItem} to determine the range of indices you
      * can supply.
-     * 
+     *
      * @see #getBroadcastItem
      * @see #finishBroadcast
      */
@@ -244,26 +245,26 @@
             return i;
         }
     }
-    
+
     /**
      * Retrieve an item in the active broadcast that was previously started
      * with {@link #beginBroadcast}.  This can <em>only</em> be called after
      * the broadcast is started, and its data is no longer valid after
      * calling {@link #finishBroadcast}.
-     * 
+     *
      * <p>Note that it is possible for the process of one of the returned
      * callbacks to go away before you call it, so you will need to catch
      * {@link RemoteException} when calling on to the returned object.
      * The callback list itself, however, will take care of unregistering
      * these objects once it detects that it is no longer valid, so you can
      * handle such an exception by simply ignoring it.
-     * 
+     *
      * @param index Which of the registered callbacks you would like to
      * retrieve.  Ranges from 0 to 1-{@link #beginBroadcast}.
-     * 
+     *
      * @return Returns the callback interface that you can call.  This will
      * always be non-null.
-     * 
+     *
      * @see #beginBroadcast
      */
     public E getBroadcastItem(int index) {
@@ -279,12 +280,12 @@
     public Object getBroadcastCookie(int index) {
         return ((Callback)mActiveBroadcast[index]).mCookie;
     }
-    
+
     /**
      * Clean up the state of a broadcast previously initiated by calling
      * {@link #beginBroadcast}.  This must always be called when you are done
      * with a broadcast.
-     * 
+     *
      * @see #beginBroadcast
      */
     public void finishBroadcast() {
diff --git a/core/java/android/os/Vibrator.java b/core/java/android/os/Vibrator.java
index 0f75289..51dcff1 100644
--- a/core/java/android/os/Vibrator.java
+++ b/core/java/android/os/Vibrator.java
@@ -24,6 +24,7 @@
 public class Vibrator
 {
     IHardwareService mService;
+    private final Binder mToken = new Binder();
 
     /** @hide */
     public Vibrator()
@@ -40,7 +41,7 @@
     public void vibrate(long milliseconds)
     {
         try {
-            mService.vibrate(milliseconds);
+            mService.vibrate(milliseconds, mToken);
         } catch (RemoteException e) {
         }
     }
@@ -65,7 +66,7 @@
         // anyway
         if (repeat < pattern.length) {
             try {
-                mService.vibratePattern(pattern, repeat, new Binder());
+                mService.vibratePattern(pattern, repeat, mToken);
             } catch (RemoteException e) {
             }
         } else {
@@ -79,7 +80,7 @@
     public void cancel()
     {
         try {
-            mService.cancelVibrate();
+            mService.cancelVibrate(mToken);
         } catch (RemoteException e) {
         }
     }
diff --git a/core/java/android/pim/RecurrenceSet.java b/core/java/android/pim/RecurrenceSet.java
index 1a287c8..7920543 100644
--- a/core/java/android/pim/RecurrenceSet.java
+++ b/core/java/android/pim/RecurrenceSet.java
@@ -223,6 +223,7 @@
         return true;
     }
 
+    // This can be removed when the old CalendarSyncAdapter is removed.
     public static boolean populateComponent(Cursor cursor,
                                             ICalendar.Component component) {
         
@@ -292,6 +293,64 @@
         return true;
     }
 
+public static boolean populateComponent(ContentValues values,
+                                            ICalendar.Component component) {
+        long dtstart = -1;
+        if (values.containsKey(Calendar.Events.DTSTART)) {
+            dtstart = values.getAsLong(Calendar.Events.DTSTART);
+        }
+        String duration = values.getAsString(Calendar.Events.DURATION);
+        String tzid = values.getAsString(Calendar.Events.EVENT_TIMEZONE);
+        String rruleStr = values.getAsString(Calendar.Events.RRULE);
+        String rdateStr = values.getAsString(Calendar.Events.RDATE);
+        String exruleStr = values.getAsString(Calendar.Events.EXRULE);
+        String exdateStr = values.getAsString(Calendar.Events.EXDATE);
+        boolean allDay = values.getAsInteger(Calendar.Events.ALL_DAY) == 1;
+
+        if ((dtstart == -1) ||
+            (TextUtils.isEmpty(duration))||
+            ((TextUtils.isEmpty(rruleStr))&&
+                (TextUtils.isEmpty(rdateStr)))) {
+                // no recurrence.
+                return false;
+        }
+
+        ICalendar.Property dtstartProp = new ICalendar.Property("DTSTART");
+        Time dtstartTime = null;
+        if (!TextUtils.isEmpty(tzid)) {
+            if (!allDay) {
+                dtstartProp.addParameter(new ICalendar.Parameter("TZID", tzid));
+            }
+            dtstartTime = new Time(tzid);
+        } else {
+            // use the "floating" timezone
+            dtstartTime = new Time(Time.TIMEZONE_UTC);
+        }
+
+        dtstartTime.set(dtstart);
+        // make sure the time is printed just as a date, if all day.
+        // TODO: android.pim.Time really should take care of this for us.
+        if (allDay) {
+            dtstartProp.addParameter(new ICalendar.Parameter("VALUE", "DATE"));
+            dtstartTime.allDay = true;
+            dtstartTime.hour = 0;
+            dtstartTime.minute = 0;
+            dtstartTime.second = 0;
+        }
+
+        dtstartProp.setValue(dtstartTime.format2445());
+        component.addProperty(dtstartProp);
+        ICalendar.Property durationProp = new ICalendar.Property("DURATION");
+        durationProp.setValue(duration);
+        component.addProperty(durationProp);
+
+        addPropertiesForRuleStr(component, "RRULE", rruleStr);
+        addPropertyForDateStr(component, "RDATE", rdateStr);
+        addPropertiesForRuleStr(component, "EXRULE", exruleStr);
+        addPropertyForDateStr(component, "EXDATE", exdateStr);
+        return true;
+    }
+
     private static void addPropertiesForRuleStr(ICalendar.Component component,
                                                 String propertyName,
                                                 String ruleStr) {
diff --git a/core/java/android/pim/vcard/ContactStruct.java b/core/java/android/pim/vcard/ContactStruct.java
new file mode 100644
index 0000000..46725d3
--- /dev/null
+++ b/core/java/android/pim/vcard/ContactStruct.java
@@ -0,0 +1,1244 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+import android.content.AbstractSyncableContentProvider;
+import android.content.ContentResolver;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.net.Uri;
+import android.provider.Contacts;
+import android.provider.Contacts.ContactMethods;
+import android.provider.Contacts.Extensions;
+import android.provider.Contacts.GroupMembership;
+import android.provider.Contacts.Organizations;
+import android.provider.Contacts.People;
+import android.provider.Contacts.Phones;
+import android.provider.Contacts.Photos;
+import android.telephony.PhoneNumberUtils;
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * This class bridges between data structure of Contact app and VCard data.
+ */
+public class ContactStruct {
+    private static final String LOG_TAG = "ContactStruct";
+    
+    /**
+     * @hide only for testing
+     */
+    static public class PhoneData {
+        public final int type;
+        public final String data;
+        public final String label;
+        // isPrimary is changable only when there's no appropriate one existing in
+        // the original VCard.
+        public boolean isPrimary;
+        public PhoneData(int type, String data, String label, boolean isPrimary) {
+            this.type = type;
+            this.data = data;
+            this.label = label;
+            this.isPrimary = isPrimary;
+        }
+        
+        @Override
+        public boolean equals(Object obj) {
+            if (obj instanceof PhoneData) {
+                return false;
+            }
+            PhoneData phoneData = (PhoneData)obj;
+            return (type == phoneData.type && data.equals(phoneData.data) &&
+                    label.equals(phoneData.label) && isPrimary == phoneData.isPrimary);
+        }
+        
+        @Override
+        public String toString() {
+            return String.format("type: %d, data: %s, label: %s, isPrimary: %s",
+                    type, data, label, isPrimary);
+        }
+    }
+
+    /**
+     * @hide only for testing
+     */
+    static public class ContactMethod {
+        // Contacts.KIND_EMAIL, Contacts.KIND_POSTAL
+        public final int kind;
+        // e.g. Contacts.ContactMethods.TYPE_HOME, Contacts.PhoneColumns.TYPE_HOME
+        // If type == Contacts.PhoneColumns.TYPE_CUSTOM, label is used.
+        public final int type;
+        public final String data;
+        // Used only when TYPE is TYPE_CUSTOM.
+        public final String label;
+        // isPrimary is changable only when there's no appropriate one existing in
+        // the original VCard.
+        public boolean isPrimary;
+        public ContactMethod(int kind, int type, String data, String label,
+                boolean isPrimary) {
+            this.kind = kind;
+            this.type = type;
+            this.data = data;
+            this.label = data;
+            this.isPrimary = isPrimary;
+        }
+        
+        @Override
+        public boolean equals(Object obj) {
+            if (obj instanceof ContactMethod) {
+                return false;
+            }
+            ContactMethod contactMethod = (ContactMethod)obj;
+            return (kind == contactMethod.kind && type == contactMethod.type &&
+                    data.equals(contactMethod.data) && label.equals(contactMethod.label) &&
+                    isPrimary == contactMethod.isPrimary);
+        }
+        
+        @Override
+        public String toString() {
+            return String.format("kind: %d, type: %d, data: %s, label: %s, isPrimary: %s",
+                    kind, type, data, label, isPrimary);
+        }
+    }
+    
+    /**
+     * @hide only for testing
+     */
+    static public class OrganizationData {
+        public final int type;
+        public final String companyName;
+        // can be changed in some VCard format. 
+        public String positionName;
+        // isPrimary is changable only when there's no appropriate one existing in
+        // the original VCard.
+        public boolean isPrimary;
+        public OrganizationData(int type, String companyName, String positionName,
+                boolean isPrimary) {
+            this.type = type;
+            this.companyName = companyName;
+            this.positionName = positionName;
+            this.isPrimary = isPrimary;
+        }
+        
+        @Override
+        public boolean equals(Object obj) {
+            if (obj instanceof OrganizationData) {
+                return false;
+            }
+            OrganizationData organization = (OrganizationData)obj;
+            return (type == organization.type && companyName.equals(organization.companyName) &&
+                    positionName.equals(organization.positionName) &&
+                    isPrimary == organization.isPrimary);
+        }
+        
+        @Override
+        public String toString() {
+            return String.format("type: %d, company: %s, position: %s, isPrimary: %s",
+                    type, companyName, positionName, isPrimary);
+        }
+    }
+    
+    static class Property {
+        private String mPropertyName;
+        private Map<String, Collection<String>> mParameterMap =
+            new HashMap<String, Collection<String>>();
+        private List<String> mPropertyValueList = new ArrayList<String>();
+        private byte[] mPropertyBytes;
+        
+        public Property() {
+            clear();
+        }
+        
+        public void setPropertyName(final String propertyName) {
+            mPropertyName = propertyName;
+        }
+        
+        public void addParameter(final String paramName, final String paramValue) {
+            Collection<String> values;
+            if (mParameterMap.containsKey(paramName)) {
+                if (paramName.equals("TYPE")) {
+                    values = new HashSet<String>();
+                } else {
+                    values = new ArrayList<String>();
+                }
+                mParameterMap.put(paramName, values);
+            } else {
+                values = mParameterMap.get(paramName);
+            }
+        }
+        
+        public void addToPropertyValueList(final String propertyValue) {
+            mPropertyValueList.add(propertyValue);
+        }
+        
+        public void setPropertyBytes(final byte[] propertyBytes) {
+            mPropertyBytes = propertyBytes;
+        }
+
+        public final Collection<String> getParameters(String type) {
+            return mParameterMap.get(type);
+        }
+        
+        public final List<String> getPropertyValueList() {
+            return mPropertyValueList;
+        }
+        
+        public void clear() {
+            mPropertyName = null;
+            mParameterMap.clear();
+            mPropertyValueList.clear();
+        }
+    }
+    
+    private String mName;
+    private String mPhoneticName;
+    // private String mPhotoType;
+    private byte[] mPhotoBytes;
+    private List<String> mNotes;
+    private List<PhoneData> mPhoneList;
+    private List<ContactMethod> mContactMethodList;
+    private List<OrganizationData> mOrganizationList;
+    private Map<String, List<String>> mExtensionMap;
+
+    private int mNameOrderType;
+    
+    /* private variables bellow is for temporary use. */
+    
+    // For name, there are three fields in vCard: FN, N, NAME.
+    // We prefer FN, which is a required field in vCard 3.0 , but not in vCard 2.1.
+    // Next, we prefer NAME, which is defined only in vCard 3.0.
+    // Finally, we use N, which is a little difficult to parse.
+    private String mTmpFullName;
+    private String mTmpNameFromNProperty;
+
+    // Some vCard has "X-PHONETIC-FIRST-NAME", "X-PHONETIC-MIDDLE-NAME", and
+    // "X-PHONETIC-LAST-NAME"
+    private String mTmpXPhoneticFirstName;
+    private String mTmpXPhoneticMiddleName;
+    private String mTmpXPhoneticLastName;
+    
+    // Each Column of four properties has ISPRIMARY field
+    // (See android.provider.Contacts)
+    // If false even after the following loop, we choose the first
+    // entry as a "primary" entry.
+    private boolean mPrefIsSet_Address;
+    private boolean mPrefIsSet_Phone;
+    private boolean mPrefIsSet_Email;
+    private boolean mPrefIsSet_Organization;
+
+    public ContactStruct() {
+        mNameOrderType = VCardConfig.NAME_ORDER_TYPE_DEFAULT;
+    }
+    
+    public ContactStruct(int nameOrderType) {
+        mNameOrderType = nameOrderType; 
+    }
+    
+    /**
+     * @hide only for test
+     */
+    public ContactStruct(String name,
+            String phoneticName,
+            byte[] photoBytes,
+            List<String> notes,
+            List<PhoneData> phoneList, 
+            List<ContactMethod> contactMethodList,
+            List<OrganizationData> organizationList,
+            Map<String, List<String>> extensionMap) {
+        mName = name;
+        mPhoneticName = phoneticName;
+        mPhotoBytes = photoBytes;
+        mContactMethodList = contactMethodList;
+        mOrganizationList = organizationList;
+        mExtensionMap = extensionMap;
+    }
+    
+    /**
+     * @hide only for test
+     */
+    public String getName() {
+        return mName;
+    }
+    
+    /**
+     * @hide only for test
+     */
+    public String getPhoneticName() {
+        return mPhoneticName;
+    }
+
+    /**
+     * @hide only for test
+     */
+    public final byte[] getPhotoBytes() {
+        return mPhotoBytes;
+    }
+    
+    /**
+     * @hide only for test
+     */
+    public final List<String> getNotes() {
+        return mNotes;
+    }
+    
+    /**
+     * @hide only for test
+     */
+    public final List<PhoneData> getPhoneList() {
+        return mPhoneList;
+    }
+    
+    /**
+     * @hide only for test
+     */
+    public final List<ContactMethod> getContactMethodList() {
+        return mContactMethodList;
+    }
+    
+    /**
+     * @hide only for test
+     */
+    public final List<OrganizationData> getOrganizationList() {
+        return mOrganizationList;
+    }
+
+    /**
+     * @hide only for test
+     */
+    public final Map<String, List<String>> getExtensionMap() {
+        return mExtensionMap;
+    }
+    
+    /**
+     * Add a phone info to phoneList.
+     * @param data phone number
+     * @param type type col of content://contacts/phones
+     * @param label lable col of content://contacts/phones
+     */
+    private void addPhone(int type, String data, String label, boolean isPrimary){
+        if (mPhoneList == null) {
+            mPhoneList = new ArrayList<PhoneData>();
+        }
+        StringBuilder builder = new StringBuilder();
+        String trimed = data.trim();
+        int length = trimed.length();
+        for (int i = 0; i < length; i++) {
+            char ch = trimed.charAt(i);
+            if (('0' <= ch && ch <= '9') || (i == 0 && ch == '+')) {
+                builder.append(ch);
+            }
+        }
+
+        PhoneData phoneData = new PhoneData(type,
+                PhoneNumberUtils.formatNumber(builder.toString()),
+                label, isPrimary);
+
+        mPhoneList.add(phoneData);
+    }
+
+    /**
+     * Add a contactmethod info to contactmethodList.
+     * @param kind integer value defined in Contacts.java
+     * (e.g. Contacts.KIND_EMAIL)
+     * @param type type col of content://contacts/contact_methods
+     * @param data contact data
+     * @param label extra string used only when kind is Contacts.KIND_CUSTOM.
+     */
+    private void addContactmethod(int kind, int type, String data,
+            String label, boolean isPrimary){
+        if (mContactMethodList == null) {
+            mContactMethodList = new ArrayList<ContactMethod>();
+        }
+        mContactMethodList.add(new ContactMethod(kind, type, data, label, isPrimary));
+    }
+    
+    /**
+     * Add a Organization info to organizationList.
+     */
+    private void addOrganization(int type, String companyName, String positionName,
+            boolean isPrimary) {
+        if (mOrganizationList == null) {
+            mOrganizationList = new ArrayList<OrganizationData>();
+        }
+        mOrganizationList.add(new OrganizationData(type, companyName, positionName, isPrimary));
+    }
+
+    /**
+     * Set "position" value to the appropriate data. If there's more than one
+     * OrganizationData objects, the value is set to the last one. If there's no
+     * OrganizationData object, a new OrganizationData is created, whose company name is
+     * empty.  
+     * 
+     * TODO: incomplete logic. fix this:
+     * 
+     * e.g. This assumes ORG comes earlier, but TITLE may come earlier like this, though we do not
+     * know how to handle it in general cases...
+     * ----
+     * TITLE:Software Engineer
+     * ORG:Google
+     * ----
+     */
+    private void setPosition(String positionValue) {
+        if (mOrganizationList == null) {
+            mOrganizationList = new ArrayList<OrganizationData>();
+        }
+        int size = mOrganizationList.size();
+        if (size == 0) {
+            addOrganization(Contacts.OrganizationColumns.TYPE_OTHER, "", null, false);
+            size = 1;
+        }
+        OrganizationData lastData = mOrganizationList.get(size - 1);
+        lastData.positionName = positionValue;
+    }
+ 
+    private void addExtension(String propName, Map<String, Collection<String>> paramMap,
+            List<String> propValueList) {
+        if (propValueList.size() == 0) {
+            return;
+        }
+        // Now store the string into extensionMap.
+        List<String> list;
+        if (mExtensionMap == null) {
+            mExtensionMap = new HashMap<String, List<String>>();
+        }
+        if (!mExtensionMap.containsKey(propName)){
+            list = new ArrayList<String>();
+            mExtensionMap.put(propName, list);
+        } else {
+            list = mExtensionMap.get(propName);
+        }        
+        
+        list.add(encodeProperty(propName, paramMap, propValueList));
+    }
+
+    private String encodeProperty(String propName, Map<String, Collection<String>> paramMap,
+            List<String> propValueList) {
+        // PropertyNode#toString() is for reading, not for parsing in the future.
+        // We construct appropriate String here.
+        StringBuilder builder = new StringBuilder();
+        if (propName.length() > 0) {
+            builder.append("propName:[");
+            builder.append(propName);
+            builder.append("],");
+        }
+
+        if (paramMap.size() > 0) {
+            builder.append("paramMap:[");
+            int size = paramMap.size(); 
+            int i = 0;
+            for (Map.Entry<String, Collection<String>> entry : paramMap.entrySet()) {
+                String key = entry.getKey();
+                for (String value : entry.getValue()) {
+                    // Assuming param-key does not contain NON-ASCII nor symbols.
+                    // TODO: check it.
+                    //
+                    // According to vCard 3.0:
+                    // param-name   = iana-token / x-name
+                    builder.append(key);
+
+                    // param-value may contain any value including NON-ASCIIs.
+                    // We use the following replacing rule.
+                    // \ -> \\
+                    // , -> \,
+                    // In String#replaceAll(), "\\\\" means a single backslash.
+                    builder.append("=");
+
+                    // TODO: fix this.
+                    builder.append(value.replaceAll("\\\\", "\\\\\\\\").replaceAll(",", "\\\\,"));
+                    if (i < size -1) {
+                        builder.append(",");
+                    }
+                    i++;
+                }
+            }
+
+            builder.append("],");
+        }
+
+        int size = propValueList.size();
+        if (size > 0) {
+            builder.append("propValue:[");
+            List<String> list = propValueList;
+            for (int i = 0; i < size; i++) {
+                // TODO: fix this.
+                builder.append(list.get(i).replaceAll("\\\\", "\\\\\\\\").replaceAll(",", "\\\\,"));
+                if (i < size -1) {
+                    builder.append(",");
+                }
+            }
+            builder.append("],");
+        }
+
+        return builder.toString();
+    }
+    
+    private static String getNameFromNProperty(List<String> elems, int nameOrderType) {
+        // Family, Given, Middle, Prefix, Suffix. (1 - 5)
+        int size = elems.size();
+        if (size > 1) {
+            StringBuilder builder = new StringBuilder();
+            boolean builderIsEmpty = true;
+            // Prefix
+            if (size > 3 && elems.get(3).length() > 0) {
+                builder.append(elems.get(3));
+                builderIsEmpty = false;
+            }
+            String first, second;
+            if (nameOrderType == VCardConfig.NAME_ORDER_TYPE_JAPANESE) {
+                first = elems.get(0);
+                second = elems.get(1);
+            } else {
+                first = elems.get(1);
+                second = elems.get(0);
+            }
+            if (first.length() > 0) {
+                if (!builderIsEmpty) {
+                    builder.append(' ');
+                }
+                builder.append(first);
+                builderIsEmpty = false;
+            }
+            // Middle name
+            if (size > 2 && elems.get(2).length() > 0) {
+                if (!builderIsEmpty) {
+                    builder.append(' ');
+                }
+                builder.append(elems.get(2));
+                builderIsEmpty = false;
+            }
+            if (second.length() > 0) {
+                if (!builderIsEmpty) {
+                    builder.append(' ');
+                }
+                builder.append(second);
+                builderIsEmpty = false;
+            }
+            // Suffix
+            if (size > 4 && elems.get(4).length() > 0) {
+                if (!builderIsEmpty) {
+                    builder.append(' ');
+                }
+                builder.append(elems.get(4));
+                builderIsEmpty = false;
+            }
+            return builder.toString();
+        } else if (size == 1) {
+            return elems.get(0);
+        } else {
+            return "";
+        }
+    }
+
+    public void addProperty(Property property) {
+        String propName = property.mPropertyName;
+        final Map<String, Collection<String>> paramMap = property.mParameterMap;
+        final List<String> propValueList = property.mPropertyValueList;
+        byte[] propBytes = property.mPropertyBytes;
+        
+        if (propValueList.size() == 0) {
+            return;
+        }
+
+        String propValue = listToString(propValueList);
+
+        if (propName.equals("VERSION")) {
+            // vCard version. Ignore this.
+        } else if (propName.equals("FN")) {
+            mTmpFullName = propValue;
+        } else if (propName.equals("NAME") && mTmpFullName == null) {
+            // Only in vCard 3.0. Use this if FN does not exist.
+            // Though, note that vCard 3.0 requires FN.
+            mTmpFullName = propValue;
+        } else if (propName.equals("N")) {
+            mTmpNameFromNProperty = getNameFromNProperty(propValueList, mNameOrderType);
+        } else if (propName.equals("SORT-STRING")) {
+            mPhoneticName = propValue;
+        } else if (propName.equals("SOUND")) {
+            if ("X-IRMC-N".equals(paramMap.get("TYPE")) && mPhoneticName == null) {
+                // Some Japanese mobile phones use this field for phonetic name,
+                // since vCard 2.1 does not have "SORT-STRING" type.
+                // Also, in some cases, the field has some ';'s in it.
+                // We remove them.
+                StringBuilder builder = new StringBuilder();
+                String value = propValue;
+                int length = value.length();
+                for (int i = 0; i < length; i++) {
+                    char ch = value.charAt(i);
+                    if (ch != ';') {
+                        builder.append(ch);
+                    }
+                }
+                if (builder.length() > 0) {
+                    mPhoneticName = builder.toString();
+                }
+            } else {
+                addExtension(propName, paramMap, propValueList);
+            }
+        } else if (propName.equals("ADR")) {
+            boolean valuesAreAllEmpty = true;
+            for (String value : propValueList) {
+                if (value.length() > 0) {
+                    valuesAreAllEmpty = false;
+                    break;
+                }
+            }
+            if (valuesAreAllEmpty) {
+                return;
+            }
+
+            int kind = Contacts.KIND_POSTAL;
+            int type = -1;
+            String label = "";
+            boolean isPrimary = false;
+            Collection<String> typeCollection = paramMap.get("TYPE");
+            if (typeCollection != null) {
+                for (String typeString : typeCollection) {
+                    if (typeString.equals("PREF") && !mPrefIsSet_Address) {
+                        // Only first "PREF" is considered.
+                        mPrefIsSet_Address = true;
+                        isPrimary = true;
+                    } else if (typeString.equalsIgnoreCase("HOME")) {
+                        type = Contacts.ContactMethodsColumns.TYPE_HOME;
+                        label = "";
+                    } else if (typeString.equalsIgnoreCase("WORK") || 
+                            typeString.equalsIgnoreCase("COMPANY")) {
+                        // "COMPANY" seems emitted by Windows Mobile, which is not
+                        // specifically supported by vCard 2.1. We assume this is same
+                        // as "WORK".
+                        type = Contacts.ContactMethodsColumns.TYPE_WORK;
+                        label = "";
+                    } else if (typeString.equalsIgnoreCase("POSTAL")) {
+                        kind = Contacts.KIND_POSTAL;
+                    } else if (typeString.equalsIgnoreCase("PARCEL") || 
+                            typeString.equalsIgnoreCase("DOM") ||
+                            typeString.equalsIgnoreCase("INTL")) {
+                        // We do not have a kind or type matching these.
+                        // TODO: fix this. We may need to split entries into two.
+                        // (e.g. entries for KIND_POSTAL and KIND_PERCEL)
+                    } else if (typeString.toUpperCase().startsWith("X-") &&
+                            type < 0) {
+                        type = Contacts.ContactMethodsColumns.TYPE_CUSTOM;
+                        label = typeString.substring(2);
+                    } else if (type < 0) {
+                        // vCard 3.0 allows iana-token. Also some vCard 2.1 exporters
+                        // emit non-standard types. We do not handle their values now.
+                        type = Contacts.ContactMethodsColumns.TYPE_CUSTOM;
+                        label = typeString;
+                    }
+                }
+            }
+            // We use "HOME" as default
+            if (type < 0) {
+                type = Contacts.ContactMethodsColumns.TYPE_HOME;
+            }
+                            
+            // adr-value    = 0*6(text-value ";") text-value
+            //              ; PO Box, Extended Address, Street, Locality, Region, Postal
+            //              ; Code, Country Name
+            String address;
+            int size = propValueList.size();
+            if (size > 1) {
+                StringBuilder builder = new StringBuilder();
+                boolean builderIsEmpty = true;
+                if (Locale.getDefault().getCountry().equals(Locale.JAPAN.getCountry())) {
+                    // In Japan, the order is reversed.
+                    for (int i = size - 1; i >= 0; i--) {
+                        String addressPart = propValueList.get(i);
+                        if (addressPart.length() > 0) {
+                            if (!builderIsEmpty) {
+                                builder.append(' ');
+                            }
+                            builder.append(addressPart);
+                            builderIsEmpty = false;
+                        }
+                    }
+                } else {
+                    for (int i = 0; i < size; i++) {
+                        String addressPart = propValueList.get(i);
+                        if (addressPart.length() > 0) {
+                            if (!builderIsEmpty) {
+                                builder.append(' ');
+                            }
+                            builder.append(addressPart);
+                            builderIsEmpty = false;
+                        }
+                    }
+                }
+                address = builder.toString().trim();
+            } else {
+                address = propValue; 
+            }
+            addContactmethod(kind, type, address, label, isPrimary);
+        } else if (propName.equals("ORG")) {
+            // vCard specification does not specify other types.
+            int type = Contacts.OrganizationColumns.TYPE_WORK;
+            boolean isPrimary = false;
+            
+            Collection<String> typeCollection = paramMap.get("TYPE");
+            if (typeCollection != null) {
+                for (String typeString : typeCollection) {
+                    if (typeString.equals("PREF") && !mPrefIsSet_Organization) {
+                        // vCard specification officially does not have PREF in ORG.
+                        // This is just for safety.
+                        mPrefIsSet_Organization = true;
+                        isPrimary = true;
+                    }
+                    // XXX: Should we cope with X- words?
+                }
+            }
+
+            int size = propValueList.size();
+            StringBuilder builder = new StringBuilder();
+            for (Iterator<String> iter = propValueList.iterator(); iter.hasNext();) {
+                builder.append(iter.next());
+                if (iter.hasNext()) {
+                    builder.append(' ');
+                }
+            }
+
+            addOrganization(type, builder.toString(), "", isPrimary);
+        } else if (propName.equals("TITLE")) {
+            setPosition(propValue);
+        } else if (propName.equals("ROLE")) {
+            setPosition(propValue);
+        } else if ((propName.equals("PHOTO") || (propName.equals("LOGO")) && mPhotoBytes == null)) {
+            // We prefer PHOTO to LOGO.
+            Collection<String> paramMapValue = paramMap.get("VALUE");
+            if (paramMapValue != null && paramMapValue.contains("URL")) {
+                // TODO: do something.
+            } else {
+                // Assume PHOTO is stored in BASE64. In that case,
+                // data is already stored in propValue_bytes in binary form.
+                // It should be automatically done by VBuilder (VDataBuilder/VCardDatabuilder) 
+                mPhotoBytes = propBytes;
+                /*
+                Collection<String> typeCollection = paramMap.get("TYPE");
+                if (typeCollection != null) {
+                    if (typeCollection.size() > 1) {
+                        StringBuilder builder = new StringBuilder();
+                        int size = typeCollection.size(); 
+                        int i = 0;
+                        for (String type : typeCollection) {
+                            builder.append(type);
+                            if (i < size - 1) {
+                                builder.append(',');
+                            }
+                            i++;
+                        }
+                        Log.w(LOG_TAG, "There is more than TYPE: " + builder.toString());
+                    }
+                    mPhotoType = typeCollection.iterator().next();
+                }*/
+            }
+        } else if (propName.equals("EMAIL")) {
+            int type = -1;
+            String label = null;
+            boolean isPrimary = false;
+            Collection<String> typeCollection = paramMap.get("TYPE");
+            if (typeCollection != null) {
+                for (String typeString : typeCollection) {
+                    if (typeString.equals("PREF") && !mPrefIsSet_Email) {
+                        // Only first "PREF" is considered.
+                        mPrefIsSet_Email = true;
+                        isPrimary = true;
+                    } else if (typeString.equalsIgnoreCase("HOME")) {
+                        type = Contacts.ContactMethodsColumns.TYPE_HOME;
+                    } else if (typeString.equalsIgnoreCase("WORK")) {
+                        type = Contacts.ContactMethodsColumns.TYPE_WORK;
+                    } else if (typeString.equalsIgnoreCase("CELL")) {
+                        // We do not have Contacts.ContactMethodsColumns.TYPE_MOBILE yet.
+                        type = Contacts.ContactMethodsColumns.TYPE_CUSTOM;
+                        label = Contacts.ContactMethodsColumns.MOBILE_EMAIL_TYPE_NAME;
+                    } else if (typeString.toUpperCase().startsWith("X-") &&
+                            type < 0) {
+                        type = Contacts.ContactMethodsColumns.TYPE_CUSTOM;
+                        label = typeString.substring(2);
+                    } else if (type < 0) {
+                        // vCard 3.0 allows iana-token.
+                        // We may have INTERNET (specified in vCard spec),
+                        // SCHOOL, etc.
+                        type = Contacts.ContactMethodsColumns.TYPE_CUSTOM;
+                        label = typeString;
+                    }
+                }
+            }
+            if (type < 0) {
+                type = Contacts.ContactMethodsColumns.TYPE_OTHER;
+            }
+            addContactmethod(Contacts.KIND_EMAIL, type, propValue,label, isPrimary);
+        } else if (propName.equals("TEL")) {
+            int type = -1;
+            String label = null;
+            boolean isPrimary = false;
+            boolean isFax = false;
+            Collection<String> typeCollection = paramMap.get("TYPE");
+            if (typeCollection != null) {
+                for (String typeString : typeCollection) {
+                    if (typeString.equals("PREF") && !mPrefIsSet_Phone) {
+                        // Only first "PREF" is considered.
+                        mPrefIsSet_Phone = true;
+                        isPrimary = true;
+                    } else if (typeString.equalsIgnoreCase("HOME")) {
+                        type = Contacts.PhonesColumns.TYPE_HOME;
+                    } else if (typeString.equalsIgnoreCase("WORK")) {
+                        type = Contacts.PhonesColumns.TYPE_WORK;
+                    } else if (typeString.equalsIgnoreCase("CELL")) {
+                        type = Contacts.PhonesColumns.TYPE_MOBILE;
+                    } else if (typeString.equalsIgnoreCase("PAGER")) {
+                        type = Contacts.PhonesColumns.TYPE_PAGER;
+                    } else if (typeString.equalsIgnoreCase("FAX")) {
+                        isFax = true;
+                    } else if (typeString.equalsIgnoreCase("VOICE") ||
+                            typeString.equalsIgnoreCase("MSG")) {
+                        // Defined in vCard 3.0. Ignore these because they
+                        // conflict with "HOME", "WORK", etc.
+                        // XXX: do something?
+                    } else if (typeString.toUpperCase().startsWith("X-") &&
+                            type < 0) {
+                        type = Contacts.PhonesColumns.TYPE_CUSTOM;
+                        label = typeString.substring(2);
+                    } else if (type < 0){
+                        // We may have MODEM, CAR, ISDN, etc...
+                        type = Contacts.PhonesColumns.TYPE_CUSTOM;
+                        label = typeString;
+                    }
+                }
+            }
+            if (type < 0) {
+                type = Contacts.PhonesColumns.TYPE_HOME;
+            }
+            if (isFax) {
+                if (type == Contacts.PhonesColumns.TYPE_HOME) {
+                    type = Contacts.PhonesColumns.TYPE_FAX_HOME; 
+                } else if (type == Contacts.PhonesColumns.TYPE_WORK) {
+                    type = Contacts.PhonesColumns.TYPE_FAX_WORK; 
+                }
+            }
+
+            addPhone(type, propValue, label, isPrimary);
+        } else if (propName.equals("NOTE")) {
+            if (mNotes == null) {
+                mNotes = new ArrayList<String>(1);
+            }
+            mNotes.add(propValue);
+        } else if (propName.equals("BDAY")) {
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("URL")) {
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("REV")) {                
+            // Revision of this VCard entry. I think we can ignore this.
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("UID")) {
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("KEY")) {
+            // Type is X509 or PGP? I don't know how to handle this...
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("MAILER")) {
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("TZ")) {
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("GEO")) {
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("NICKNAME")) {
+            // vCard 3.0 only.
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("CLASS")) {
+            // vCard 3.0 only.
+            // e.g. CLASS:CONFIDENTIAL
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("PROFILE")) {
+            // VCard 3.0 only. Must be "VCARD". I think we can ignore this.
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("CATEGORIES")) {
+            // VCard 3.0 only.
+            // e.g. CATEGORIES:INTERNET,IETF,INDUSTRY,INFORMATION TECHNOLOGY
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("SOURCE")) {
+            // VCard 3.0 only.
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("PRODID")) {
+            // VCard 3.0 only.
+            // To specify the identifier for the product that created
+            // the vCard object.
+            addExtension(propName, paramMap, propValueList);
+        } else if (propName.equals("X-PHONETIC-FIRST-NAME")) {
+            mTmpXPhoneticFirstName = propValue;
+        } else if (propName.equals("X-PHONETIC-MIDDLE-NAME")) {
+            mTmpXPhoneticMiddleName = propValue;
+        } else if (propName.equals("X-PHONETIC-LAST-NAME")) {
+            mTmpXPhoneticLastName = propValue;
+        } else {
+            // Unknown X- words and IANA token.
+            addExtension(propName, paramMap, propValueList);
+        }
+    }
+    
+    public String displayString() {
+        if (mName.length() > 0) {
+            return mName;
+        }
+        if (mContactMethodList != null && mContactMethodList.size() > 0) {
+            for (ContactMethod contactMethod : mContactMethodList) {
+                if (contactMethod.kind == Contacts.KIND_EMAIL && contactMethod.isPrimary) {
+                    return contactMethod.data;
+                }
+            }
+        }
+        if (mPhoneList != null && mPhoneList.size() > 0) {
+            for (PhoneData phoneData : mPhoneList) {
+                if (phoneData.isPrimary) {
+                    return phoneData.data;
+                }
+            }
+        }
+        return "";
+    }
+
+    /**
+     * Consolidate several fielsds (like mName) using name candidates, 
+     */
+    public void consolidateFields() {
+        if (mTmpFullName != null) {
+            mName = mTmpFullName;
+        } else if(mTmpNameFromNProperty != null) {
+            mName = mTmpNameFromNProperty;
+        } else {
+            mName = "";
+        }
+
+        if (mPhoneticName == null &&
+                (mTmpXPhoneticFirstName != null || mTmpXPhoneticMiddleName != null ||
+                        mTmpXPhoneticLastName != null)) {
+            // Note: In Europe, this order should be "LAST FIRST MIDDLE". See the comment around
+            //       NAME_ORDER_TYPE_* for more detail.
+            String first;
+            String second;
+            if (mNameOrderType == VCardConfig.NAME_ORDER_TYPE_JAPANESE) {
+                first = mTmpXPhoneticLastName;
+                second = mTmpXPhoneticFirstName;
+            } else {
+                first = mTmpXPhoneticFirstName;
+                second = mTmpXPhoneticLastName;
+            }
+            StringBuilder builder = new StringBuilder();
+            if (first != null) {
+                builder.append(first);
+            }
+            if (mTmpXPhoneticMiddleName != null) {
+                builder.append(mTmpXPhoneticMiddleName);
+            }
+            if (second != null) {
+                builder.append(second);
+            }
+            mPhoneticName = builder.toString();
+        }
+        
+        // Remove unnecessary white spaces.
+        // It is found that some mobile phone emits  phonetic name with just one white space
+        // when a user does not specify one.
+        // This logic is effective toward such kind of weird data.
+        if (mPhoneticName != null) {
+            mPhoneticName = mPhoneticName.trim();
+        }
+
+        // If there is no "PREF", we choose the first entries as primary.
+        if (!mPrefIsSet_Phone && mPhoneList != null && mPhoneList.size() > 0) {
+            mPhoneList.get(0).isPrimary = true;
+        }
+
+        if (!mPrefIsSet_Address && mContactMethodList != null) {
+            for (ContactMethod contactMethod : mContactMethodList) {
+                if (contactMethod.kind == Contacts.KIND_POSTAL) {
+                    contactMethod.isPrimary = true;
+                    break;
+                }
+            }
+        }
+        if (!mPrefIsSet_Email && mContactMethodList != null) {
+            for (ContactMethod contactMethod : mContactMethodList) {
+                if (contactMethod.kind == Contacts.KIND_EMAIL) {
+                    contactMethod.isPrimary = true;
+                    break;
+                }
+            }
+        }
+        if (!mPrefIsSet_Organization && mOrganizationList != null && mOrganizationList.size() > 0) {
+            mOrganizationList.get(0).isPrimary = true;
+        }
+        
+    }
+    
+    private void pushIntoContentProviderOrResolver(Object contentSomething,
+            long myContactsGroupId) {
+        ContentResolver resolver = null;
+        AbstractSyncableContentProvider provider = null;
+        if (contentSomething instanceof ContentResolver) {
+            resolver = (ContentResolver)contentSomething;
+        } else if (contentSomething instanceof AbstractSyncableContentProvider) {
+            provider = (AbstractSyncableContentProvider)contentSomething;
+        } else {
+            Log.e(LOG_TAG, "Unsupported object came.");
+            return;
+        }
+        
+        ContentValues contentValues = new ContentValues();
+        contentValues.put(People.NAME, mName);
+        contentValues.put(People.PHONETIC_NAME, mPhoneticName);
+        
+        if (mNotes != null && mNotes.size() > 0) {
+            if (mNotes.size() > 1) {
+                StringBuilder builder = new StringBuilder();
+                for (String note : mNotes) {
+                    builder.append(note);
+                    builder.append("\n");
+                }
+                contentValues.put(People.NOTES, builder.toString());
+            } else {
+                contentValues.put(People.NOTES, mNotes.get(0));
+            }
+        }
+
+        Uri personUri;
+        long personId = 0;
+        if (resolver != null) {
+            personUri = Contacts.People.createPersonInMyContactsGroup(resolver, contentValues);
+            if (personUri != null) {
+                personId = ContentUris.parseId(personUri);
+            }
+        } else {
+            personUri = provider.insert(People.CONTENT_URI, contentValues);
+            if (personUri != null) {
+                personId = ContentUris.parseId(personUri);
+                ContentValues values = new ContentValues();
+                values.put(GroupMembership.PERSON_ID, personId);
+                values.put(GroupMembership.GROUP_ID, myContactsGroupId);
+                Uri resultUri = provider.insert(GroupMembership.CONTENT_URI, values);
+                if (resultUri == null) {
+                    Log.e(LOG_TAG, "Faild to insert the person to MyContact.");
+                    provider.delete(personUri, null, null);
+                    personUri = null;
+                }
+            }
+        }
+
+        if (personUri == null) {
+            Log.e(LOG_TAG, "Failed to create the contact.");
+            return;
+        }
+        
+        if (mPhotoBytes != null) {
+            if (resolver != null) {
+                People.setPhotoData(resolver, personUri, mPhotoBytes);
+            } else {
+                Uri photoUri = Uri.withAppendedPath(personUri, Contacts.Photos.CONTENT_DIRECTORY);
+                ContentValues values = new ContentValues();
+                values.put(Photos.DATA, mPhotoBytes);
+                provider.update(photoUri, values, null, null);
+            }
+        }
+        
+        long primaryPhoneId = -1;
+        if (mPhoneList != null && mPhoneList.size() > 0) {
+            for (PhoneData phoneData : mPhoneList) {
+                ContentValues values = new ContentValues();
+                values.put(Contacts.PhonesColumns.TYPE, phoneData.type);
+                if (phoneData.type == Contacts.PhonesColumns.TYPE_CUSTOM) {
+                    values.put(Contacts.PhonesColumns.LABEL, phoneData.label);
+                }
+                // Already formatted.
+                values.put(Contacts.PhonesColumns.NUMBER, phoneData.data);
+                
+                // Not sure about Contacts.PhonesColumns.NUMBER_KEY ...
+                values.put(Contacts.PhonesColumns.ISPRIMARY, 1);
+                values.put(Contacts.Phones.PERSON_ID, personId);
+                Uri phoneUri;
+                if (resolver != null) {
+                    phoneUri = resolver.insert(Phones.CONTENT_URI, values);
+                } else {
+                    phoneUri = provider.insert(Phones.CONTENT_URI, values);
+                }
+                if (phoneData.isPrimary) {
+                    primaryPhoneId = Long.parseLong(phoneUri.getLastPathSegment());
+                }
+            }
+        }
+        
+        long primaryOrganizationId = -1;
+        if (mOrganizationList != null && mOrganizationList.size() > 0) {
+            for (OrganizationData organizationData : mOrganizationList) {
+                ContentValues values = new ContentValues();
+                // Currently, we do not use TYPE_CUSTOM.
+                values.put(Contacts.OrganizationColumns.TYPE,
+                        organizationData.type);
+                values.put(Contacts.OrganizationColumns.COMPANY,
+                        organizationData.companyName);
+                values.put(Contacts.OrganizationColumns.TITLE,
+                        organizationData.positionName);
+                values.put(Contacts.OrganizationColumns.ISPRIMARY, 1);
+                values.put(Contacts.OrganizationColumns.PERSON_ID, personId);
+                
+                Uri organizationUri;
+                if (resolver != null) {
+                    organizationUri = resolver.insert(Organizations.CONTENT_URI, values);
+                } else {
+                    organizationUri = provider.insert(Organizations.CONTENT_URI, values);
+                }
+                if (organizationData.isPrimary) {
+                    primaryOrganizationId = Long.parseLong(organizationUri.getLastPathSegment());
+                }
+            }
+        }
+        
+        long primaryEmailId = -1;
+        if (mContactMethodList != null && mContactMethodList.size() > 0) {
+            for (ContactMethod contactMethod : mContactMethodList) {
+                ContentValues values = new ContentValues();
+                values.put(Contacts.ContactMethodsColumns.KIND, contactMethod.kind);
+                values.put(Contacts.ContactMethodsColumns.TYPE, contactMethod.type);
+                if (contactMethod.type == Contacts.ContactMethodsColumns.TYPE_CUSTOM) {
+                    values.put(Contacts.ContactMethodsColumns.LABEL, contactMethod.label);
+                }
+                values.put(Contacts.ContactMethodsColumns.DATA, contactMethod.data);
+                values.put(Contacts.ContactMethodsColumns.ISPRIMARY, 1);
+                values.put(Contacts.ContactMethods.PERSON_ID, personId);
+                
+                if (contactMethod.kind == Contacts.KIND_EMAIL) {
+                    Uri emailUri;
+                    if (resolver != null) {
+                        emailUri = resolver.insert(ContactMethods.CONTENT_URI, values);
+                    } else {
+                        emailUri = provider.insert(ContactMethods.CONTENT_URI, values);
+                    }
+                    if (contactMethod.isPrimary) {
+                        primaryEmailId = Long.parseLong(emailUri.getLastPathSegment());
+                    }
+                } else {  // probably KIND_POSTAL
+                    if (resolver != null) {
+                        resolver.insert(ContactMethods.CONTENT_URI, values);
+                    } else {
+                        provider.insert(ContactMethods.CONTENT_URI, values);
+                    }
+                }
+            }
+        }
+        
+        if (mExtensionMap != null && mExtensionMap.size() > 0) {
+            ArrayList<ContentValues> contentValuesArray;
+            if (resolver != null) {
+                contentValuesArray = new ArrayList<ContentValues>();
+            } else {
+                contentValuesArray = null;
+            }
+            for (Entry<String, List<String>> entry : mExtensionMap.entrySet()) {
+                String key = entry.getKey();
+                List<String> list = entry.getValue();
+                for (String value : list) {
+                    ContentValues values = new ContentValues();
+                    values.put(Extensions.NAME, key);
+                    values.put(Extensions.VALUE, value);
+                    values.put(Extensions.PERSON_ID, personId);
+                    if (resolver != null) {
+                        contentValuesArray.add(values);
+                    } else {
+                        provider.insert(Extensions.CONTENT_URI, values);
+                    }
+                }
+            }
+            if (resolver != null) {
+                resolver.bulkInsert(Extensions.CONTENT_URI,
+                        contentValuesArray.toArray(new ContentValues[0]));
+            }
+        }
+        
+        if (primaryPhoneId >= 0 || primaryOrganizationId >= 0 || primaryEmailId >= 0) {
+            ContentValues values = new ContentValues();
+            if (primaryPhoneId >= 0) {
+                values.put(People.PRIMARY_PHONE_ID, primaryPhoneId);
+            }
+            if (primaryOrganizationId >= 0) {
+                values.put(People.PRIMARY_ORGANIZATION_ID, primaryOrganizationId);
+            }
+            if (primaryEmailId >= 0) {
+                values.put(People.PRIMARY_EMAIL_ID, primaryEmailId);
+            }
+            if (resolver != null) {
+                resolver.update(personUri, values, null, null);
+            } else {
+                provider.update(personUri, values, null, null);
+            }
+        }
+    }
+
+    /**
+     * Push this object into database in the resolver.
+     */
+    public void pushIntoContentResolver(ContentResolver resolver) {
+        pushIntoContentProviderOrResolver(resolver, 0);
+    }
+    
+    /**
+     * Push this object into AbstractSyncableContentProvider object.
+     * {@link #consolidateFields() must be called before this method is called}
+     * @hide
+     */
+    public void pushIntoAbstractSyncableContentProvider(
+            AbstractSyncableContentProvider provider, long myContactsGroupId) {
+        boolean successful = false;
+        provider.beginBatch();
+        try {
+            pushIntoContentProviderOrResolver(provider, myContactsGroupId);
+            successful = true;
+        } finally {
+            provider.endBatch(successful);
+        }
+    }
+    
+    public boolean isIgnorable() {
+        return TextUtils.isEmpty(mName) &&
+                TextUtils.isEmpty(mPhoneticName) &&
+                (mPhoneList == null || mPhoneList.size() == 0) &&
+                (mContactMethodList == null || mContactMethodList.size() == 0);
+    }
+    
+    private String listToString(List<String> list){
+        final int size = list.size();
+        if (size > 1) {
+            StringBuilder builder = new StringBuilder();
+            int i = 0;
+            for (String type : list) {
+                builder.append(type);
+                if (i < size - 1) {
+                    builder.append(";");
+                }
+            }
+            return builder.toString();
+        } else if (size == 1) {
+            return list.get(0);
+        } else {
+            return "";
+        }
+    }
+}
diff --git a/core/java/android/pim/vcard/EntryCommitter.java b/core/java/android/pim/vcard/EntryCommitter.java
new file mode 100644
index 0000000..e26fac5
--- /dev/null
+++ b/core/java/android/pim/vcard/EntryCommitter.java
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+import android.content.AbstractSyncableContentProvider;
+import android.content.ContentProvider;
+import android.content.ContentResolver;
+import android.content.IContentProvider;
+import android.provider.Contacts;
+import android.util.Log;
+
+/**
+ * EntryHandler implementation which commits the entry to Contacts Provider 
+ */
+public class EntryCommitter implements EntryHandler {
+    public static String LOG_TAG = "vcard.EntryComitter";
+    
+    private ContentResolver mContentResolver;
+    
+    // Ideally, this should be ContactsProvider but it seems Class loader cannot find it,
+    // even when it is subclass of ContactsProvider...
+    private AbstractSyncableContentProvider mProvider;
+    private long mMyContactsGroupId;
+    
+    private long mTimeToCommit;
+    
+    public EntryCommitter(ContentResolver resolver) {
+        mContentResolver = resolver;
+        
+        tryGetOriginalProvider();
+    }
+    
+    public void onFinal() {
+        if (VCardConfig.showPerformanceLog()) {
+            Log.d(LOG_TAG,
+                    String.format("time to commit entries: %ld ms", mTimeToCommit));
+        }
+    }
+    
+    private void tryGetOriginalProvider() {
+        final ContentResolver resolver = mContentResolver;
+        
+        if ((mMyContactsGroupId = Contacts.People.tryGetMyContactsGroupId(resolver)) == 0) {
+            Log.e(LOG_TAG, "Could not get group id of MyContact");
+            return;
+        }
+
+        IContentProvider iProviderForName = resolver.acquireProvider(Contacts.CONTENT_URI);
+        ContentProvider contentProvider =
+            ContentProvider.coerceToLocalContentProvider(iProviderForName);
+        if (contentProvider == null) {
+            Log.e(LOG_TAG, "Fail to get ContentProvider object.");
+            return;
+        }
+        
+        if (!(contentProvider instanceof AbstractSyncableContentProvider)) {
+            Log.e(LOG_TAG,
+                    "Acquired ContentProvider object is not AbstractSyncableContentProvider.");
+            return;
+        }
+        
+        mProvider = (AbstractSyncableContentProvider)contentProvider; 
+    }
+    
+    public void onEntryCreated(final ContactStruct contactStruct) {
+        long start = System.currentTimeMillis();
+        if (mProvider != null) {
+            contactStruct.pushIntoAbstractSyncableContentProvider(
+                    mProvider, mMyContactsGroupId);
+        } else {
+            contactStruct.pushIntoContentResolver(mContentResolver);
+        }
+        mTimeToCommit += System.currentTimeMillis() - start;
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/pim/vcard/EntryHandler.java b/core/java/android/pim/vcard/EntryHandler.java
new file mode 100644
index 0000000..4015cb5
--- /dev/null
+++ b/core/java/android/pim/vcard/EntryHandler.java
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+/**
+ * Unlike VCardBuilderBase, this (and VCardDataBuilder) assumes
+ * "each VCard entry should be correctly parsed and passed to each EntryHandler object",
+ */
+public interface EntryHandler {
+    /**
+     * Able to be use this method for showing performance log, etc.
+     * TODO: better name?
+     */
+    public void onFinal();
+
+    /**
+     * The method called when one VCard entry is successfully created
+     */
+    public void onEntryCreated(final ContactStruct entry);
+}
diff --git a/core/java/android/pim/vcard/VCardBuilder.java b/core/java/android/pim/vcard/VCardBuilder.java
new file mode 100644
index 0000000..e1c4b33
--- /dev/null
+++ b/core/java/android/pim/vcard/VCardBuilder.java
@@ -0,0 +1,64 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+import java.util.List;
+
+public interface VCardBuilder {
+    void start();
+
+    void end();
+
+    /** 
+     * BEGIN:VCARD
+     */
+    void startRecord(String type);
+
+    /** END:VXX */
+    void endRecord();
+
+    void startProperty();
+
+    void endProperty();
+
+    /**
+     * @param group 
+     */
+    void propertyGroup(String group);
+    
+    /**
+     * @param name
+     *            N <br>
+     *            N
+     */
+    void propertyName(String name);
+
+    /**
+     * @param type
+     *            LANGUAGE \ ENCODING <br>
+     *            ;LANGUage= \ ;ENCODING=
+     */
+    void propertyParamType(String type);
+
+    /**
+     * @param value
+     *            FR-EN \ GBK <br>
+     *            FR-EN \ GBK
+     */
+    void propertyParamValue(String value);
+
+    void propertyValues(List<String> values);
+}
diff --git a/core/java/android/pim/vcard/VCardBuilderCollection.java b/core/java/android/pim/vcard/VCardBuilderCollection.java
new file mode 100644
index 0000000..e3985b6
--- /dev/null
+++ b/core/java/android/pim/vcard/VCardBuilderCollection.java
@@ -0,0 +1,99 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+import java.util.Collection;
+import java.util.List;
+
+public class VCardBuilderCollection implements VCardBuilder {
+
+    private final Collection<VCardBuilder> mVCardBuilderCollection;
+    
+    public VCardBuilderCollection(Collection<VCardBuilder> vBuilderCollection) {
+        mVCardBuilderCollection = vBuilderCollection; 
+    }
+    
+    public Collection<VCardBuilder> getVCardBuilderBaseCollection() {
+        return mVCardBuilderCollection;
+    }
+    
+    public void start() {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.start();
+        }
+    }
+    
+    public void end() {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.end();
+        }
+    }
+
+    public void startRecord(String type) {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.startRecord(type);
+        }
+    }
+    
+    public void endRecord() {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.endRecord();
+        }
+    }
+
+    public void startProperty() {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.startProperty();
+        }
+    }
+
+    
+    public void endProperty() {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.endProperty();
+        }
+    }
+
+    public void propertyGroup(String group) {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.propertyGroup(group);
+        }
+    }
+
+    public void propertyName(String name) {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.propertyName(name);
+        }
+    }
+
+    public void propertyParamType(String type) {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.propertyParamType(type);
+        }
+    }
+
+    public void propertyParamValue(String value) {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.propertyParamValue(value);
+        }
+    }
+
+    public void propertyValues(List<String> values) {
+        for (VCardBuilder builder : mVCardBuilderCollection) {
+            builder.propertyValues(values);
+        }
+    }
+}
diff --git a/core/java/android/pim/vcard/VCardConfig.java b/core/java/android/pim/vcard/VCardConfig.java
new file mode 100644
index 0000000..fef9dba
--- /dev/null
+++ b/core/java/android/pim/vcard/VCardConfig.java
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+/**
+ * The class representing VCard related configurations  
+ */
+public class VCardConfig {
+    static final int LOG_LEVEL_NONE = 0;
+    static final int LOG_LEVEL_PERFORMANCE_MEASUREMENT = 0x1;
+    static final int LOG_LEVEL_SHOW_WARNING = 0x2;
+    static final int LOG_LEVEL_VERBOSE =
+        LOG_LEVEL_PERFORMANCE_MEASUREMENT | LOG_LEVEL_SHOW_WARNING;
+    
+    // Assumes that "iso-8859-1" is able to map "all" 8bit characters to some unicode and
+    // decode the unicode to the original charset. If not, this setting will cause some bug. 
+    public static final String DEFAULT_CHARSET = "iso-8859-1";
+    
+    // TODO: use this flag
+    public static boolean IGNORE_CASE_EXCEPT_VALUE = true;
+    
+    protected static final int LOG_LEVEL = LOG_LEVEL_PERFORMANCE_MEASUREMENT;
+    
+    // Note: phonetic name probably should be "LAST FIRST MIDDLE" for European languages, and
+    //       space should be added between each element while it should not be in Japanese.
+    //       But unfortunately, we currently do not have the data and are not sure whether we should
+    //       support European version of name ordering.
+    //
+    // TODO: Implement the logic described above if we really need European version of
+    //        phonetic name handling. Also, adding the appropriate test case of vCard would be
+    //        highly appreciated.
+    public static final int NAME_ORDER_TYPE_ENGLISH = 0;
+    public static final int NAME_ORDER_TYPE_JAPANESE = 1;
+    
+    public static final int NAME_ORDER_TYPE_DEFAULT = NAME_ORDER_TYPE_ENGLISH; 
+    
+    /**
+     * @hide temporal. may be deleted
+     */
+    public static boolean showPerformanceLog() {
+        return (LOG_LEVEL & LOG_LEVEL_PERFORMANCE_MEASUREMENT) != 0;
+    }
+    
+    private VCardConfig() {
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/pim/vcard/VCardDataBuilder.java b/core/java/android/pim/vcard/VCardDataBuilder.java
new file mode 100644
index 0000000..4025f6c
--- /dev/null
+++ b/core/java/android/pim/vcard/VCardDataBuilder.java
@@ -0,0 +1,319 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+import android.util.CharsetUtils;
+import android.util.Log;
+
+import org.apache.commons.codec.DecoderException;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.codec.net.QuotedPrintableCodec;
+
+import java.io.UnsupportedEncodingException;
+import java.nio.ByteBuffer;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * VBuilder for VCard. VCard may contain big photo images encoded by BASE64,
+ * If we store all VNode entries in memory like VDataBuilder.java,
+ * OutOfMemoryError may be thrown. Thus, this class push each VCard entry into
+ * ContentResolver immediately.
+ */
+public class VCardDataBuilder implements VCardBuilder {
+    static private String LOG_TAG = "VCardDataBuilder"; 
+    
+    /**
+     * If there's no other information available, this class uses this charset for encoding
+     * byte arrays.
+     */
+    static public String TARGET_CHARSET = "UTF-8"; 
+    
+    private ContactStruct.Property mCurrentProperty = new ContactStruct.Property();
+    private ContactStruct mCurrentContactStruct;
+    private String mParamType;
+    
+    /**
+     * The charset using which VParser parses the text.
+     */
+    private String mSourceCharset;
+    
+    /**
+     * The charset with which byte array is encoded to String.
+     */
+    private String mTargetCharset;
+    private boolean mStrictLineBreakParsing;
+    
+    private int mNameOrderType;
+    
+    // Just for testing.
+    private long mTimePushIntoContentResolver;
+    
+    private List<EntryHandler> mEntryHandlers = new ArrayList<EntryHandler>();
+    
+    public VCardDataBuilder() {
+        this(null, null, false, VCardConfig.NAME_ORDER_TYPE_DEFAULT);
+    }
+
+    /**
+     * @hide 
+     */
+    public VCardDataBuilder(int nameOrderType) {
+        this(null, null, false, nameOrderType);
+    }
+    
+    /**
+     * @hide 
+     */
+    public VCardDataBuilder(String charset,
+            boolean strictLineBreakParsing,
+            int nameOrderType) {
+        this(null, charset, strictLineBreakParsing, nameOrderType);
+    }
+    
+    /**
+     * @hide
+     */
+    public VCardDataBuilder(String sourceCharset,
+            String targetCharset,
+            boolean strictLineBreakParsing,
+            int nameOrderType) {
+        if (sourceCharset != null) {
+            mSourceCharset = sourceCharset;
+        } else {
+            mSourceCharset = VCardConfig.DEFAULT_CHARSET;
+        }
+        if (targetCharset != null) {
+            mTargetCharset = targetCharset;
+        } else {
+            mTargetCharset = TARGET_CHARSET;
+        }
+        mStrictLineBreakParsing = strictLineBreakParsing;
+        mNameOrderType = nameOrderType;
+    }
+    
+    public void addEntryHandler(EntryHandler entryHandler) {
+        mEntryHandlers.add(entryHandler);
+    }
+    
+    public void start() {
+    }
+
+    public void end() {
+        for (EntryHandler entryHandler : mEntryHandlers) {
+            entryHandler.onFinal();
+        }
+    }
+
+    /**
+     * Assume that VCard is not nested. In other words, this code does not accept 
+     */
+    public void startRecord(String type) {
+        // TODO: add the method clear() instead of using null for reducing GC?
+        if (mCurrentContactStruct != null) {
+            // This means startRecord() is called inside startRecord() - endRecord() block.
+            // TODO: should throw some Exception
+            Log.e(LOG_TAG, "Nested VCard code is not supported now.");
+        }
+        if (!type.equalsIgnoreCase("VCARD")) {
+            // TODO: add test case for this
+            Log.e(LOG_TAG, "This is not VCARD!");
+        }
+
+        mCurrentContactStruct = new ContactStruct(mNameOrderType);
+    }
+
+    public void endRecord() {
+        mCurrentContactStruct.consolidateFields();
+        for (EntryHandler entryHandler : mEntryHandlers) {
+            entryHandler.onEntryCreated(mCurrentContactStruct);
+        }
+        mCurrentContactStruct = null;
+    }
+
+    public void startProperty() {
+        mCurrentProperty.clear();
+    }
+
+    public void endProperty() {
+        mCurrentContactStruct.addProperty(mCurrentProperty);
+    }
+    
+    public void propertyName(String name) {
+        mCurrentProperty.setPropertyName(name);
+    }
+
+    public void propertyGroup(String group) {
+        // ContactStruct does not support Group.
+    }
+    
+    public void propertyParamType(String type) {
+        if (mParamType != null) {
+            Log.e(LOG_TAG,
+                    "propertyParamType() is called more than once " +
+                    "before propertyParamValue() is called");
+        }
+        mParamType = type;
+    }
+
+    public void propertyParamValue(String value) {
+        if (mParamType == null) {
+            mParamType = "TYPE";
+        }
+        mCurrentProperty.addParameter(mParamType, value);
+        mParamType = null;
+    }
+    
+    private String encodeString(String originalString, String targetCharset) {
+        if (mSourceCharset.equalsIgnoreCase(targetCharset)) {
+            return originalString;
+        }
+        Charset charset = Charset.forName(mSourceCharset);
+        ByteBuffer byteBuffer = charset.encode(originalString);
+        // byteBuffer.array() "may" return byte array which is larger than
+        // byteBuffer.remaining(). Here, we keep on the safe side.
+        byte[] bytes = new byte[byteBuffer.remaining()];
+        byteBuffer.get(bytes);
+        try {
+            return new String(bytes, targetCharset);
+        } catch (UnsupportedEncodingException e) {
+            Log.e(LOG_TAG, "Failed to encode: charset=" + targetCharset);
+            return null;
+        }
+    }
+    
+    private String handleOneValue(String value, String targetCharset, String encoding) {
+        if (encoding != null) {
+            if (encoding.equals("BASE64") || encoding.equals("B")) {
+                mCurrentProperty.setPropertyBytes(Base64.decodeBase64(value.getBytes()));
+                return value;
+            } else if (encoding.equals("QUOTED-PRINTABLE")) {
+                // "= " -> " ", "=\t" -> "\t".
+                // Previous code had done this replacement. Keep on the safe side.
+                StringBuilder builder = new StringBuilder();
+                int length = value.length();
+                for (int i = 0; i < length; i++) {
+                    char ch = value.charAt(i);
+                    if (ch == '=' && i < length - 1) {
+                        char nextCh = value.charAt(i + 1);
+                        if (nextCh == ' ' || nextCh == '\t') {
+
+                            builder.append(nextCh);
+                            i++;
+                            continue;
+                        }
+                    }
+                    builder.append(ch);
+                }
+                String quotedPrintable = builder.toString();
+                
+                String[] lines;
+                if (mStrictLineBreakParsing) {
+                    lines = quotedPrintable.split("\r\n");
+                } else {
+                    builder = new StringBuilder();
+                    length = quotedPrintable.length();
+                    ArrayList<String> list = new ArrayList<String>();
+                    for (int i = 0; i < length; i++) {
+                        char ch = quotedPrintable.charAt(i);
+                        if (ch == '\n') {
+                            list.add(builder.toString());
+                            builder = new StringBuilder();
+                        } else if (ch == '\r') {
+                            list.add(builder.toString());
+                            builder = new StringBuilder();
+                            if (i < length - 1) {
+                                char nextCh = quotedPrintable.charAt(i + 1);
+                                if (nextCh == '\n') {
+                                    i++;
+                                }
+                            }
+                        } else {
+                            builder.append(ch);
+                        }
+                    }
+                    String finalLine = builder.toString();
+                    if (finalLine.length() > 0) {
+                        list.add(finalLine);
+                    }
+                    lines = list.toArray(new String[0]);
+                }
+                
+                builder = new StringBuilder();
+                for (String line : lines) {
+                    if (line.endsWith("=")) {
+                        line = line.substring(0, line.length() - 1);
+                    }
+                    builder.append(line);
+                }
+                byte[] bytes;
+                try {
+                    bytes = builder.toString().getBytes(mSourceCharset);
+                } catch (UnsupportedEncodingException e1) {
+                    Log.e(LOG_TAG, "Failed to encode: charset=" + mSourceCharset);
+                    bytes = builder.toString().getBytes();
+                }
+                
+                try {
+                    bytes = QuotedPrintableCodec.decodeQuotedPrintable(bytes);
+                } catch (DecoderException e) {
+                    Log.e(LOG_TAG, "Failed to decode quoted-printable: " + e);
+                    return "";
+                }
+
+                try {
+                    return new String(bytes, targetCharset);
+                } catch (UnsupportedEncodingException e) {
+                    Log.e(LOG_TAG, "Failed to encode: charset=" + targetCharset);
+                    return new String(bytes);
+                }
+            }
+            // Unknown encoding. Fall back to default.
+        }
+        return encodeString(value, targetCharset);
+    }
+    
+    public void propertyValues(List<String> values) {
+        if (values == null || values.size() == 0) {
+            return;
+        }
+
+        final Collection<String> charsetCollection = mCurrentProperty.getParameters("CHARSET");
+        String charset =
+            ((charsetCollection != null) ? charsetCollection.iterator().next() : null);
+        String targetCharset = CharsetUtils.nameForDefaultVendor(charset); 
+
+        final Collection<String> encodingCollection = mCurrentProperty.getParameters("ENCODING");
+        String encoding =
+            ((encodingCollection != null) ? encodingCollection.iterator().next() : null);
+        
+        if (targetCharset == null || targetCharset.length() == 0) {
+            targetCharset = mTargetCharset;
+        }
+        
+        for (String value : values) {
+            mCurrentProperty.addToPropertyValueList(
+                    handleOneValue(value, targetCharset, encoding));
+        }
+    }
+
+    public void showPerformanceInfo() {
+        Log.d(LOG_TAG, "time for insert ContactStruct to database: " + 
+                mTimePushIntoContentResolver + " ms");
+    }
+}
diff --git a/core/java/android/pim/vcard/VCardEntryCounter.java b/core/java/android/pim/vcard/VCardEntryCounter.java
new file mode 100644
index 0000000..f99b46c
--- /dev/null
+++ b/core/java/android/pim/vcard/VCardEntryCounter.java
@@ -0,0 +1,60 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+import java.util.List;
+
+public class VCardEntryCounter implements VCardBuilder {
+    private int mCount;
+    
+    public int getCount() {
+        return mCount;
+    }
+    
+    public void start() {
+    }
+    
+    public void end() {
+    }
+
+    public void startRecord(String type) {
+    }
+
+    public void endRecord() {
+        mCount++;
+    }
+    
+    public void startProperty() {
+    }
+    
+    public void endProperty() {
+    }
+
+    public void propertyGroup(String group) {
+    }
+
+    public void propertyName(String name) {
+    }
+
+    public void propertyParamType(String type) {
+    }
+
+    public void propertyParamValue(String value) {
+    }
+
+    public void propertyValues(List<String> values) {
+    }    
+}
\ No newline at end of file
diff --git a/core/java/android/pim/vcard/VCardParser.java b/core/java/android/pim/vcard/VCardParser.java
new file mode 100644
index 0000000..b5e5049
--- /dev/null
+++ b/core/java/android/pim/vcard/VCardParser.java
@@ -0,0 +1,90 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+import android.pim.vcard.exception.VCardException;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+public abstract class VCardParser {
+
+    protected boolean mCanceled;
+    
+    /**
+     * Parses the given stream and send the VCard data into VCardBuilderBase object.
+     * 
+     * Note that vCard 2.1 specification allows "CHARSET" parameter, and some career sets
+     * local encoding to it. For example, Japanese phone career uses Shift_JIS, which is
+     * formally allowed in VCard 2.1, but not recommended in VCard 3.0. In VCard 2.1,
+     * In some exreme case, some VCard may have different charsets in one VCard (though
+     * we do not see any device which emits such kind of malicious data)
+     * 
+     * In order to avoid "misunderstanding" charset as much as possible, this method
+     * use "ISO-8859-1" for reading the stream. When charset is specified in some property
+     * (with "CHARSET=..." attribute), the string is decoded to raw bytes and encoded to
+     * the charset. This method assumes that "ISO-8859-1" has 1 to 1 mapping in all 8bit
+     * characters, which is not completely sure. In some cases, this "decoding-encoding"
+     * scheme may fail. To avoid the case,
+     * 
+     * We recommend you to use VCardSourceDetector and detect which kind of source the
+     * VCard comes from and explicitly specify a charset using the result.
+     *       
+     * @param is The source to parse.
+     * @param builder The VCardBuilderBase object which used to construct data. If you want to
+     * include multiple VCardBuilderBase objects in this field, consider using
+     * {#link VCardBuilderCollection} class.
+     * @return Returns true for success. Otherwise returns false.
+     * @throws IOException, VCardException
+     */
+    public abstract boolean parse(InputStream is, VCardBuilder builder)
+            throws IOException, VCardException;
+    
+    /**
+     * The method variants which accept charset.
+     * 
+     * RFC 2426 "recommends" (not forces) to use UTF-8, so it may be OK to use
+     * UTF-8 as an encoding when parsing vCard 3.0. But note that some Japanese
+     * phone uses Shift_JIS as a charset (e.g. W61SH), and another uses
+     * "CHARSET=SHIFT_JIS", which is explicitly prohibited in vCard 3.0 specification
+     * (e.g. W53K).
+     *  
+     * @param is The source to parse.
+     * @param charset Charset to be used.
+     * @param builder The VCardBuilderBase object.
+     * @return Returns true when successful. Otherwise returns false.
+     * @throws IOException, VCardException
+     */
+    public abstract boolean parse(InputStream is, String charset, VCardBuilder builder)
+            throws IOException, VCardException;
+    
+    /**
+     * The method variants which tells this object the operation is already canceled.
+     * XXX: Is this really necessary?
+     * @hide 
+     */
+    public abstract void parse(InputStream is, String charset,
+            VCardBuilder builder, boolean canceled)
+        throws IOException, VCardException;
+    
+    /**
+     * Cancel parsing.
+     * Actual cancel is done after the end of the current one vcard entry parsing.
+     */
+    public void cancel() {
+        mCanceled = true;
+    }
+}
diff --git a/core/java/android/pim/vcard/VCardParser_V21.java b/core/java/android/pim/vcard/VCardParser_V21.java
new file mode 100644
index 0000000..17a138f
--- /dev/null
+++ b/core/java/android/pim/vcard/VCardParser_V21.java
@@ -0,0 +1,948 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+import android.pim.vcard.exception.VCardException;
+import android.pim.vcard.exception.VCardNestedException;
+import android.pim.vcard.exception.VCardNotSupportedException;
+import android.pim.vcard.exception.VCardVersionException;
+import android.util.Log;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+
+/**
+ * This class is used to parse vcard. Please refer to vCard Specification 2.1.
+ */
+public class VCardParser_V21 extends VCardParser {
+    private static final String LOG_TAG = "VCardParser_V21";
+    
+    /** Store the known-type */
+    private static final HashSet<String> sKnownTypeSet = new HashSet<String>(
+            Arrays.asList("DOM", "INTL", "POSTAL", "PARCEL", "HOME", "WORK",
+                    "PREF", "VOICE", "FAX", "MSG", "CELL", "PAGER", "BBS",
+                    "MODEM", "CAR", "ISDN", "VIDEO", "AOL", "APPLELINK",
+                    "ATTMAIL", "CIS", "EWORLD", "INTERNET", "IBMMAIL",
+                    "MCIMAIL", "POWERSHARE", "PRODIGY", "TLX", "X400", "GIF",
+                    "CGM", "WMF", "BMP", "MET", "PMB", "DIB", "PICT", "TIFF",
+                    "PDF", "PS", "JPEG", "QTIME", "MPEG", "MPEG2", "AVI",
+                    "WAVE", "AIFF", "PCM", "X509", "PGP"));
+
+    /** Store the known-value */
+    private static final HashSet<String> sKnownValueSet = new HashSet<String>(
+            Arrays.asList("INLINE", "URL", "CONTENT-ID", "CID"));
+        
+    /** Store the property names available in vCard 2.1 */
+    private static final HashSet<String> sAvailablePropertyNameV21 =
+        new HashSet<String>(Arrays.asList(
+                "BEGIN", "LOGO", "PHOTO", "LABEL", "FN", "TITLE", "SOUND",
+                "VERSION", "TEL", "EMAIL", "TZ", "GEO", "NOTE", "URL",
+                "BDAY", "ROLE", "REV", "UID", "KEY", "MAILER"));
+
+    // Though vCard 2.1 specification does not allow "B" encoding, some data may have it.
+    // We allow it for safety...
+    private static final HashSet<String> sAvailableEncodingV21 =
+        new HashSet<String>(Arrays.asList(
+                "7BIT", "8BIT", "QUOTED-PRINTABLE", "BASE64", "B"));
+    
+    // Used only for parsing END:VCARD.
+    private String mPreviousLine;
+    
+    /** The builder to build parsed data */
+    protected VCardBuilder mBuilder = null;
+
+    /** The encoding type */
+    protected String mEncoding = null;
+    
+    protected final String sDefaultEncoding = "8BIT";
+    
+    // Should not directly read a line from this. Use getLine() instead.
+    protected BufferedReader mReader;
+    
+    // In some cases, vCard is nested. Currently, we only consider the most interior vCard data.
+    // See v21_foma_1.vcf in test directory for more information.
+    private int mNestCount;
+    
+    // In order to reduce warning message as much as possible, we hold the value which made Logger
+    // emit a warning message.
+    protected HashSet<String> mWarningValueMap = new HashSet<String>();
+    
+    // Just for debugging
+    private long mTimeTotal;
+    private long mTimeStartRecord;
+    private long mTimeEndRecord;
+    private long mTimeStartProperty;
+    private long mTimeEndProperty;
+    private long mTimeParseItems;
+    private long mTimeParseItem1;
+    private long mTimeParseItem2;
+    private long mTimeParseItem3;
+    private long mTimeHandlePropertyValue1;
+    private long mTimeHandlePropertyValue2;
+    private long mTimeHandlePropertyValue3;
+    
+    /**
+     * Create a new VCard parser.
+     */
+    public VCardParser_V21() {
+        super();
+    }
+
+    public VCardParser_V21(VCardSourceDetector detector) {
+        super();
+        if (detector != null && detector.getType() == VCardSourceDetector.TYPE_FOMA) {
+            mNestCount = 1;
+        }
+    }
+    
+    /**
+     * Parse the file at the given position
+     * vcard_file = [wsls] vcard [wsls]
+     */
+    protected void parseVCardFile() throws IOException, VCardException {
+        boolean firstReading = true;
+        while (true) {
+            if (mCanceled) {
+                break;
+            }
+            if (!parseOneVCard(firstReading)) {
+                break;
+            }
+            firstReading = false;
+        }
+
+        if (mNestCount > 0) {
+            boolean useCache = true;
+            for (int i = 0; i < mNestCount; i++) {
+                readEndVCard(useCache, true);
+                useCache = false;
+            }
+        }
+    }
+
+    protected String getVersion() {
+        return "2.1";
+    }
+    
+    /**
+     * @return true when the propertyName is a valid property name.
+     */
+    protected boolean isValidPropertyName(String propertyName) {
+        if (!(sAvailablePropertyNameV21.contains(propertyName.toUpperCase()) ||
+                propertyName.startsWith("X-")) && 
+                !mWarningValueMap.contains(propertyName)) {
+            mWarningValueMap.add(propertyName);
+            Log.w(LOG_TAG, "Property name unsupported by vCard 2.1: " + propertyName);
+        }
+        return true;
+    }
+
+    /**
+     * @return true when the encoding is a valid encoding.
+     */
+    protected boolean isValidEncoding(String encoding) {
+        return sAvailableEncodingV21.contains(encoding.toUpperCase());
+    }
+    
+    /**
+     * @return String. It may be null, or its length may be 0
+     * @throws IOException
+     */
+    protected String getLine() throws IOException {
+        return mReader.readLine();
+    }
+    
+    /**
+     * @return String with it's length > 0
+     * @throws IOException
+     * @throws VCardException when the stream reached end of line
+     */
+    protected String getNonEmptyLine() throws IOException, VCardException {
+        String line;
+        while (true) {
+            line = getLine();
+            if (line == null) {
+                throw new VCardException("Reached end of buffer.");
+            } else if (line.trim().length() > 0) {                
+                return line;
+            }
+        }
+    }
+    
+    /**
+     *  vcard        = "BEGIN" [ws] ":" [ws] "VCARD" [ws] 1*CRLF
+     *                 items *CRLF
+     *                 "END" [ws] ":" [ws] "VCARD"
+     */
+    private boolean parseOneVCard(boolean firstReading) throws IOException, VCardException {
+        boolean allowGarbage = false;
+        if (firstReading) {
+            if (mNestCount > 0) {
+                for (int i = 0; i < mNestCount; i++) {
+                    if (!readBeginVCard(allowGarbage)) {
+                        return false;
+                    }
+                    allowGarbage = true;
+                }
+            }
+        }
+
+        if (!readBeginVCard(allowGarbage)) {
+            return false;
+        }
+        long start;
+        if (mBuilder != null) {
+            start = System.currentTimeMillis();
+            mBuilder.startRecord("VCARD");
+            mTimeStartRecord += System.currentTimeMillis() - start;
+        }
+        start = System.currentTimeMillis();
+        parseItems();
+        mTimeParseItems += System.currentTimeMillis() - start;
+        readEndVCard(true, false);
+        if (mBuilder != null) {
+            start = System.currentTimeMillis();
+            mBuilder.endRecord();
+            mTimeEndRecord += System.currentTimeMillis() - start;
+        }
+        return true;
+    }
+    
+    /**
+     * @return True when successful. False when reaching the end of line  
+     * @throws IOException
+     * @throws VCardException
+     */
+    protected boolean readBeginVCard(boolean allowGarbage)
+            throws IOException, VCardException {
+        String line;
+        do {
+            while (true) {
+                line = getLine();
+                if (line == null) {
+                    return false;
+                } else if (line.trim().length() > 0) {
+                    break;
+                }
+            }
+            String[] strArray = line.split(":", 2);
+            int length = strArray.length;
+
+            // Though vCard 2.1/3.0 specification does not allow lower cases,
+            // some data may have them, so we allow it (Actually, previous code
+            // had explicitly allowed "BEGIN:vCard" though there's no example).
+            //
+            // TODO: ignore non vCard entry (e.g. vcalendar).
+            // XXX: Not sure, but according to VDataBuilder.java, vcalendar
+            // entry
+            // may be nested. Just seeking "END:SOMETHING" may not be enough.
+            // e.g.
+            // BEGIN:VCARD
+            // ... (Valid. Must parse this)
+            // END:VCARD
+            // BEGIN:VSOMETHING
+            // ... (Must ignore this)
+            // BEGIN:VSOMETHING2
+            // ... (Must ignore this)
+            // END:VSOMETHING2
+            // ... (Must ignore this!)
+            // END:VSOMETHING
+            // BEGIN:VCARD
+            // ... (Valid. Must parse this)
+            // END:VCARD
+            // INVALID_STRING (VCardException should be thrown)
+            if (length == 2 &&
+                    strArray[0].trim().equalsIgnoreCase("BEGIN") &&
+                    strArray[1].trim().equalsIgnoreCase("VCARD")) {
+                return true;
+            } else if (!allowGarbage) {
+                if (mNestCount > 0) {
+                    mPreviousLine = line;
+                    return false;
+                } else {
+                    throw new VCardException(
+                            "Expected String \"BEGIN:VCARD\" did not come "
+                            + "(Instead, \"" + line + "\" came)");
+                }
+            }
+        } while(allowGarbage);
+
+        throw new VCardException("Reached where must not be reached.");
+    }
+
+    /**
+     * The arguments useCache and allowGarbase are usually true and false accordingly when
+     * this function is called outside this function itself. 
+     * 
+     * @param useCache When true, line is obtained from mPreviousline. Otherwise, getLine()
+     * is used.
+     * @param allowGarbage When true, ignore non "END:VCARD" line.
+     * @throws IOException
+     * @throws VCardException
+     */
+    protected void readEndVCard(boolean useCache, boolean allowGarbage)
+            throws IOException, VCardException {
+        String line;
+        do {
+            if (useCache) {
+                // Though vCard specification does not allow lower cases,
+                // some data may have them, so we allow it.
+                line = mPreviousLine;
+            } else {
+                while (true) {
+                    line = getLine();
+                    if (line == null) {
+                        throw new VCardException("Expected END:VCARD was not found.");
+                    } else if (line.trim().length() > 0) {
+                        break;
+                    }
+                }
+            }
+
+            String[] strArray = line.split(":", 2);
+            if (strArray.length == 2 &&
+                    strArray[0].trim().equalsIgnoreCase("END") &&
+                    strArray[1].trim().equalsIgnoreCase("VCARD")) {
+                return;
+            } else if (!allowGarbage) {
+                throw new VCardException("END:VCARD != \"" + mPreviousLine + "\"");
+            }
+            useCache = false;
+        } while (allowGarbage);
+    }
+    
+    /**
+     * items = *CRLF item 
+     *       / item
+     */
+    protected void parseItems() throws IOException, VCardException {
+        /* items *CRLF item / item */
+        boolean ended = false;
+        
+        if (mBuilder != null) {
+            long start = System.currentTimeMillis();
+            mBuilder.startProperty();
+            mTimeStartProperty += System.currentTimeMillis() - start;
+        }
+        ended = parseItem();
+        if (mBuilder != null && !ended) {
+            long start = System.currentTimeMillis();
+            mBuilder.endProperty();
+            mTimeEndProperty += System.currentTimeMillis() - start;
+        }
+
+        while (!ended) {
+            // follow VCARD ,it wont reach endProperty
+            if (mBuilder != null) {
+                long start = System.currentTimeMillis();
+                mBuilder.startProperty();
+                mTimeStartProperty += System.currentTimeMillis() - start;
+            }
+            ended = parseItem();
+            if (mBuilder != null && !ended) {
+                long start = System.currentTimeMillis();
+                mBuilder.endProperty();
+                mTimeEndProperty += System.currentTimeMillis() - start;
+            }
+        }
+    }
+    
+    /**
+     * item      = [groups "."] name    [params] ":" value CRLF
+     *           / [groups "."] "ADR"   [params] ":" addressparts CRLF
+     *           / [groups "."] "ORG"   [params] ":" orgparts CRLF
+     *           / [groups "."] "N"     [params] ":" nameparts CRLF
+     *           / [groups "."] "AGENT" [params] ":" vcard CRLF 
+     */
+    protected boolean parseItem() throws IOException, VCardException {
+        mEncoding = sDefaultEncoding;
+
+        String line = getNonEmptyLine();
+        long start = System.currentTimeMillis();
+
+        String[] propertyNameAndValue = separateLineAndHandleGroup(line);
+        if (propertyNameAndValue == null) {
+            return true;
+        }
+        if (propertyNameAndValue.length != 2) {
+            throw new VCardException("Invalid line \"" + line + "\""); 
+        }
+        String propertyName = propertyNameAndValue[0].toUpperCase();
+        String propertyValue = propertyNameAndValue[1];
+
+        mTimeParseItem1 += System.currentTimeMillis() - start;
+
+        if (propertyName.equals("ADR") ||
+                propertyName.equals("ORG") ||
+                propertyName.equals("N")) {
+            start = System.currentTimeMillis();
+            handleMultiplePropertyValue(propertyName, propertyValue);
+            mTimeParseItem3 += System.currentTimeMillis() - start;
+            return false;
+        } else if (propertyName.equals("AGENT")) {
+            handleAgent(propertyValue);
+            return false;
+        } else if (isValidPropertyName(propertyName)) {
+            if (propertyName.equals("BEGIN")) {
+                if (propertyValue.equals("VCARD")) {
+                    throw new VCardNestedException("This vCard has nested vCard data in it.");
+                } else {
+                    throw new VCardException("Unknown BEGIN type: " + propertyValue);
+                }
+            } else if (propertyName.equals("VERSION") &&
+                    !propertyValue.equals(getVersion())) {
+                throw new VCardVersionException("Incompatible version: " + 
+                        propertyValue + " != " + getVersion());
+            }
+            start = System.currentTimeMillis();
+            handlePropertyValue(propertyName, propertyValue);
+            mTimeParseItem2 += System.currentTimeMillis() - start;
+            return false;
+        }
+        
+        throw new VCardException("Unknown property name: \"" + 
+                propertyName + "\"");
+    }
+
+    static private final int STATE_GROUP_OR_PROPNAME = 0;
+    static private final int STATE_PARAMS = 1;
+    // vCard 3.1 specification allows double-quoted param-value, while vCard 2.1 does not.
+    // This is just for safety.
+    static private final int STATE_PARAMS_IN_DQUOTE = 2;
+    
+    protected String[] separateLineAndHandleGroup(String line) throws VCardException {
+        int length = line.length();
+        int state = STATE_GROUP_OR_PROPNAME;
+        int nameIndex = 0;
+
+        String[] propertyNameAndValue = new String[2];
+        
+        for (int i = 0; i < length; i++) {
+            char ch = line.charAt(i); 
+            switch (state) {
+            case STATE_GROUP_OR_PROPNAME:
+                if (ch == ':') { 
+                    String propertyName = line.substring(nameIndex, i);
+                    if (propertyName.equalsIgnoreCase("END")) {
+                        mPreviousLine = line;
+                        return null;
+                    }
+                    if (mBuilder != null) {
+                        mBuilder.propertyName(propertyName);
+                    }
+                    propertyNameAndValue[0] = propertyName; 
+                    if (i < length - 1) {
+                        propertyNameAndValue[1] = line.substring(i + 1); 
+                    } else {
+                        propertyNameAndValue[1] = "";
+                    }
+                    return propertyNameAndValue;
+                } else if (ch == '.') {
+                    String groupName = line.substring(nameIndex, i);
+                    if (mBuilder != null) {
+                        mBuilder.propertyGroup(groupName);
+                    }
+                    nameIndex = i + 1;
+                } else if (ch == ';') {
+                    String propertyName = line.substring(nameIndex, i);
+                    if (propertyName.equalsIgnoreCase("END")) {
+                        mPreviousLine = line;
+                        return null;
+                    }
+                    if (mBuilder != null) {
+                        mBuilder.propertyName(propertyName);
+                    }
+                    propertyNameAndValue[0] = propertyName;
+                    nameIndex = i + 1;
+                    state = STATE_PARAMS;
+                }
+                break;
+            case STATE_PARAMS:
+                if (ch == '"') {
+                    state = STATE_PARAMS_IN_DQUOTE;
+                } else if (ch == ';') { 
+                    handleParams(line.substring(nameIndex, i));
+                    nameIndex = i + 1;
+                } else if (ch == ':') {
+                    handleParams(line.substring(nameIndex, i));
+                    if (i < length - 1) {
+                        propertyNameAndValue[1] = line.substring(i + 1);
+                    } else {
+                        propertyNameAndValue[1] = "";
+                    }
+                    return propertyNameAndValue;
+                }
+                break;
+            case STATE_PARAMS_IN_DQUOTE:
+                if (ch == '"') {
+                    state = STATE_PARAMS;
+                }
+                break;
+            }
+        }
+        
+        throw new VCardException("Invalid line: \"" + line + "\"");
+    }
+    
+    
+    /**
+     * params      = ";" [ws] paramlist
+     * paramlist   = paramlist [ws] ";" [ws] param
+     *             / param
+     * param       = "TYPE" [ws] "=" [ws] ptypeval
+     *             / "VALUE" [ws] "=" [ws] pvalueval
+     *             / "ENCODING" [ws] "=" [ws] pencodingval
+     *             / "CHARSET" [ws] "=" [ws] charsetval
+     *             / "LANGUAGE" [ws] "=" [ws] langval
+     *             / "X-" word [ws] "=" [ws] word
+     *             / knowntype
+     */
+    protected void handleParams(String params) throws VCardException {
+        String[] strArray = params.split("=", 2);
+        if (strArray.length == 2) {
+            String paramName = strArray[0].trim();
+            String paramValue = strArray[1].trim();
+            if (paramName.equals("TYPE")) {
+                handleType(paramValue);
+            } else if (paramName.equals("VALUE")) {
+                handleValue(paramValue);
+            } else if (paramName.equals("ENCODING")) {
+                handleEncoding(paramValue);
+            } else if (paramName.equals("CHARSET")) {
+                handleCharset(paramValue);
+            } else if (paramName.equals("LANGUAGE")) {
+                handleLanguage(paramValue);
+            } else if (paramName.startsWith("X-")) {
+                handleAnyParam(paramName, paramValue);
+            } else {
+                throw new VCardException("Unknown type \"" + paramName + "\"");
+            }
+        } else {
+            handleType(strArray[0]);
+        }
+    }
+    
+    /**
+     * ptypeval  = knowntype / "X-" word
+     */
+    protected void handleType(String ptypeval) {
+        String upperTypeValue = ptypeval;
+        if (!(sKnownTypeSet.contains(upperTypeValue) || upperTypeValue.startsWith("X-")) && 
+                !mWarningValueMap.contains(ptypeval)) {
+            mWarningValueMap.add(ptypeval);
+            Log.w(LOG_TAG, "Type unsupported by vCard 2.1: " + ptypeval);
+        }
+        if (mBuilder != null) {
+            mBuilder.propertyParamType("TYPE");
+            mBuilder.propertyParamValue(upperTypeValue);
+        }
+    }
+    
+    /**
+     * pvalueval = "INLINE" / "URL" / "CONTENT-ID" / "CID" / "X-" word
+     */
+    protected void handleValue(String pvalueval) throws VCardException {
+        if (sKnownValueSet.contains(pvalueval.toUpperCase()) ||
+                pvalueval.startsWith("X-")) {
+            if (mBuilder != null) {
+                mBuilder.propertyParamType("VALUE");
+                mBuilder.propertyParamValue(pvalueval);
+            }
+        } else {
+            throw new VCardException("Unknown value \"" + pvalueval + "\"");
+        }
+    }
+    
+    /**
+     * pencodingval = "7BIT" / "8BIT" / "QUOTED-PRINTABLE" / "BASE64" / "X-" word
+     */
+    protected void handleEncoding(String pencodingval) throws VCardException {
+        if (isValidEncoding(pencodingval) ||
+                pencodingval.startsWith("X-")) {
+            if (mBuilder != null) {
+                mBuilder.propertyParamType("ENCODING");
+                mBuilder.propertyParamValue(pencodingval);
+            }
+            mEncoding = pencodingval;
+        } else {
+            throw new VCardException("Unknown encoding \"" + pencodingval + "\"");
+        }
+    }
+    
+    /**
+     * vCard specification only allows us-ascii and iso-8859-xxx (See RFC 1521),
+     * but some vCard contains other charset, so we allow them. 
+     */
+    protected void handleCharset(String charsetval) {
+        if (mBuilder != null) {
+            mBuilder.propertyParamType("CHARSET");
+            mBuilder.propertyParamValue(charsetval);
+        }
+    }
+    
+    /**
+     * See also Section 7.1 of RFC 1521
+     */
+    protected void handleLanguage(String langval) throws VCardException {
+        String[] strArray = langval.split("-");
+        if (strArray.length != 2) {
+            throw new VCardException("Invalid Language: \"" + langval + "\"");
+        }
+        String tmp = strArray[0];
+        int length = tmp.length();
+        for (int i = 0; i < length; i++) {
+            if (!isLetter(tmp.charAt(i))) {
+                throw new VCardException("Invalid Language: \"" + langval + "\"");
+            }
+        }
+        tmp = strArray[1];
+        length = tmp.length();
+        for (int i = 0; i < length; i++) {
+            if (!isLetter(tmp.charAt(i))) {
+                throw new VCardException("Invalid Language: \"" + langval + "\"");
+            }
+        }
+        if (mBuilder != null) {
+            mBuilder.propertyParamType("LANGUAGE");
+            mBuilder.propertyParamValue(langval);
+        }
+    }
+
+    /**
+     * Mainly for "X-" type. This accepts any kind of type without check.
+     */
+    protected void handleAnyParam(String paramName, String paramValue) {
+        if (mBuilder != null) {
+            mBuilder.propertyParamType(paramName);
+            mBuilder.propertyParamValue(paramValue);
+        }
+    }
+    
+    protected void handlePropertyValue(
+            String propertyName, String propertyValue) throws
+            IOException, VCardException {
+        if (mEncoding.equalsIgnoreCase("QUOTED-PRINTABLE")) {
+            long start = System.currentTimeMillis();
+            String result = getQuotedPrintable(propertyValue);
+            if (mBuilder != null) {
+                ArrayList<String> v = new ArrayList<String>();
+                v.add(result);
+                mBuilder.propertyValues(v);
+            }
+            mTimeHandlePropertyValue2 += System.currentTimeMillis() - start;
+        } else if (mEncoding.equalsIgnoreCase("BASE64") ||
+                mEncoding.equalsIgnoreCase("B")) {
+            long start = System.currentTimeMillis();
+            // It is very rare, but some BASE64 data may be so big that
+            // OutOfMemoryError occurs. To ignore such cases, use try-catch.
+            try {
+                String result = getBase64(propertyValue);
+                if (mBuilder != null) {
+                    ArrayList<String> v = new ArrayList<String>();
+                    v.add(result);
+                    mBuilder.propertyValues(v);
+                }
+            } catch (OutOfMemoryError error) {
+                Log.e(LOG_TAG, "OutOfMemoryError happened during parsing BASE64 data!");
+                if (mBuilder != null) {
+                    mBuilder.propertyValues(null);
+                }
+            }
+            mTimeHandlePropertyValue3 += System.currentTimeMillis() - start;
+        } else {
+            if (!(mEncoding == null || mEncoding.equalsIgnoreCase("7BIT")
+                    || mEncoding.equalsIgnoreCase("8BIT")
+                    || mEncoding.toUpperCase().startsWith("X-"))) {
+                Log.w(LOG_TAG, "The encoding unsupported by vCard spec: \"" + mEncoding + "\".");
+            }
+
+            long start = System.currentTimeMillis();
+            if (mBuilder != null) {
+                ArrayList<String> v = new ArrayList<String>();
+                v.add(maybeUnescapeText(propertyValue));
+                mBuilder.propertyValues(v);
+            }
+            mTimeHandlePropertyValue1 += System.currentTimeMillis() - start;
+        }
+    }
+    
+    protected String getQuotedPrintable(String firstString) throws IOException, VCardException {
+        // Specifically, there may be some padding between = and CRLF.
+        // See the following:
+        //
+        // qp-line := *(qp-segment transport-padding CRLF)
+        //            qp-part transport-padding
+        // qp-segment := qp-section *(SPACE / TAB) "="
+        //             ; Maximum length of 76 characters
+        //
+        // e.g. (from RFC 2045)
+        // Now's the time =
+        // for all folk to come=
+        //  to the aid of their country.
+        if (firstString.trim().endsWith("=")) {
+            // remove "transport-padding"
+            int pos = firstString.length() - 1;
+            while(firstString.charAt(pos) != '=') {
+            }
+            StringBuilder builder = new StringBuilder();
+            builder.append(firstString.substring(0, pos + 1));
+            builder.append("\r\n");
+            String line;
+            while (true) {
+                line = getLine();
+                if (line == null) {
+                    throw new VCardException(
+                            "File ended during parsing quoted-printable String");
+                }
+                if (line.trim().endsWith("=")) {
+                    // remove "transport-padding"
+                    pos = line.length() - 1;
+                    while(line.charAt(pos) != '=') {
+                    }
+                    builder.append(line.substring(0, pos + 1));
+                    builder.append("\r\n");
+                } else {
+                    builder.append(line);
+                    break;
+                }
+            }
+            return builder.toString(); 
+        } else {
+            return firstString;
+        }
+    }
+    
+    protected String getBase64(String firstString) throws IOException, VCardException {
+        StringBuilder builder = new StringBuilder();
+        builder.append(firstString);
+        
+        while (true) {
+            String line = getLine();
+            if (line == null) {
+                throw new VCardException(
+                        "File ended during parsing BASE64 binary");
+            }
+            if (line.length() == 0) {
+                break;
+            }
+            builder.append(line);
+        }
+        
+        return builder.toString();
+    }
+    
+    /**
+     * Mainly for "ADR", "ORG", and "N"
+     * We do not care the number of strnosemi here.
+     * 
+     * addressparts = 0*6(strnosemi ";") strnosemi
+     *              ; PO Box, Extended Addr, Street, Locality, Region,
+     *                Postal Code, Country Name
+     * orgparts     = *(strnosemi ";") strnosemi
+     *              ; First is Organization Name,
+     *                remainder are Organization Units.
+     * nameparts    = 0*4(strnosemi ";") strnosemi
+     *              ; Family, Given, Middle, Prefix, Suffix.
+     *              ; Example:Public;John;Q.;Reverend Dr.;III, Esq.
+     * strnosemi    = *(*nonsemi ("\;" / "\" CRLF)) *nonsemi
+     *              ; To include a semicolon in this string, it must be escaped
+     *              ; with a "\" character.
+     *              
+     * We are not sure whether we should add "\" CRLF to each value.
+     * For now, we exclude them.               
+     */
+    protected void handleMultiplePropertyValue(
+            String propertyName, String propertyValue) throws IOException, VCardException {
+        // vCard 2.1 does not allow QUOTED-PRINTABLE here, but some data have it.
+        if (mEncoding.equalsIgnoreCase("QUOTED-PRINTABLE")) {
+            propertyValue = getQuotedPrintable(propertyValue);
+        }
+
+        if (mBuilder != null) {
+            // TODO: limit should be set in accordance with propertyName?
+            StringBuilder builder = new StringBuilder();
+            ArrayList<String> list = new ArrayList<String>();
+            int length = propertyValue.length();
+            for (int i = 0; i < length; i++) {
+                char ch = propertyValue.charAt(i);
+                if (ch == '\\' && i < length - 1) {
+                    char nextCh = propertyValue.charAt(i + 1);
+                    String unescapedString = maybeUnescape(nextCh); 
+                    if (unescapedString != null) {
+                        builder.append(unescapedString);
+                        i++;
+                    } else {
+                        builder.append(ch);
+                    }
+                } else if (ch == ';') {
+                    list.add(builder.toString());
+                    builder = new StringBuilder();
+                } else {
+                    builder.append(ch);
+                }
+            }
+            list.add(builder.toString());
+            mBuilder.propertyValues(list);
+        }
+    }
+    
+    /**
+     * vCard 2.1 specifies AGENT allows one vcard entry. It is not encoded at all.
+     * 
+     * item     = ...
+     *          / [groups "."] "AGENT"
+     *            [params] ":" vcard CRLF
+     * vcard    = "BEGIN" [ws] ":" [ws] "VCARD" [ws] 1*CRLF
+     *            items *CRLF "END" [ws] ":" [ws] "VCARD"
+     * 
+     */
+    protected void handleAgent(String propertyValue) throws VCardException {
+        throw new VCardNotSupportedException("AGENT Property is not supported now.");
+        /* This is insufficient support. Also, AGENT Property is very rare.
+           Ignore it for now.
+           TODO: fix this.
+
+        String[] strArray = propertyValue.split(":", 2);
+        if (!(strArray.length == 2 ||
+                strArray[0].trim().equalsIgnoreCase("BEGIN") && 
+                strArray[1].trim().equalsIgnoreCase("VCARD"))) {
+            throw new VCardException("BEGIN:VCARD != \"" + propertyValue + "\"");
+        }
+        parseItems();
+        readEndVCard();
+        */
+    }
+    
+    /**
+     * For vCard 3.0.
+     */
+    protected String maybeUnescapeText(String text) {
+        return text;
+    }
+    
+    /**
+     * Returns unescaped String if the character should be unescaped. Return null otherwise.
+     * e.g. In vCard 2.1, "\;" should be unescaped into ";" while "\x" should not be.
+     */
+    protected String maybeUnescape(char ch) {
+        // Original vCard 2.1 specification does not allow transformation
+        // "\:" -> ":", "\," -> ",", and "\\" -> "\", but previous implementation of
+        // this class allowed them, so keep it as is.
+        if (ch == '\\' || ch == ';' || ch == ':' || ch == ',') {
+            return String.valueOf(ch);
+        } else {
+            return null;
+        }
+    }
+    
+    @Override
+    public boolean parse(InputStream is, VCardBuilder builder)
+            throws IOException, VCardException {
+        return parse(is, VCardConfig.DEFAULT_CHARSET, builder);
+    }
+    
+    @Override
+    public boolean parse(InputStream is, String charset, VCardBuilder builder)
+            throws IOException, VCardException {
+        // TODO: make this count error entries instead of just throwing VCardException.
+        
+        {
+            // TODO: If we really need to allow only CRLF as line break,
+            // we will have to develop our own BufferedReader().
+            final InputStreamReader tmpReader = new InputStreamReader(is, charset);
+            if (VCardConfig.showPerformanceLog()) {
+                mReader = new CustomBufferedReader(tmpReader);
+            } else {
+                mReader = new BufferedReader(tmpReader);
+            }
+        }
+        
+        mBuilder = builder;
+
+        long start = System.currentTimeMillis();
+        if (mBuilder != null) {
+            mBuilder.start();
+        }
+        parseVCardFile();
+        if (mBuilder != null) {
+            mBuilder.end();
+        }
+        mTimeTotal += System.currentTimeMillis() - start;
+        
+        if (VCardConfig.showPerformanceLog()) {
+            showPerformanceInfo();
+        }
+        
+        return true;
+    }
+    
+    @Override
+    public void parse(InputStream is, String charset, VCardBuilder builder, boolean canceled)
+            throws IOException, VCardException {
+        mCanceled = canceled;
+        parse(is, charset, builder);
+    }
+        
+    private void showPerformanceInfo() {
+        Log.d(LOG_TAG, "total parsing time:  " + mTimeTotal + " ms");
+        if (mReader instanceof CustomBufferedReader) {
+            Log.d(LOG_TAG, "total readLine time: " +
+                    ((CustomBufferedReader)mReader).getTotalmillisecond() + " ms");
+        }
+        Log.d(LOG_TAG, "mTimeStartRecord: " + mTimeStartRecord + " ms");
+        Log.d(LOG_TAG, "mTimeEndRecord: " + mTimeEndRecord + " ms");
+        Log.d(LOG_TAG, "mTimeParseItem1: " + mTimeParseItem1 + " ms");
+        Log.d(LOG_TAG, "mTimeParseItem2: " + mTimeParseItem2 + " ms");
+        Log.d(LOG_TAG, "mTimeParseItem3: " + mTimeParseItem3 + " ms");
+        Log.d(LOG_TAG, "mTimeHandlePropertyValue1: " + mTimeHandlePropertyValue1 + " ms");
+        Log.d(LOG_TAG, "mTimeHandlePropertyValue2: " + mTimeHandlePropertyValue2 + " ms");
+        Log.d(LOG_TAG, "mTimeHandlePropertyValue3: " + mTimeHandlePropertyValue3 + " ms");
+    }
+    
+    private boolean isLetter(char ch) {
+        if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
+            return true;
+        }
+        return false;
+    }
+}
+
+class CustomBufferedReader extends BufferedReader {
+    private long mTime;
+    
+    public CustomBufferedReader(Reader in) {
+        super(in);
+    }
+    
+    @Override
+    public String readLine() throws IOException {
+        long start = System.currentTimeMillis();
+        String ret = super.readLine();
+        long end = System.currentTimeMillis();
+        mTime += end - start;
+        return ret;
+    }
+    
+    public long getTotalmillisecond() {
+        return mTime;
+    }
+}
diff --git a/core/java/android/pim/vcard/VCardParser_V30.java b/core/java/android/pim/vcard/VCardParser_V30.java
new file mode 100644
index 0000000..634d9f5
--- /dev/null
+++ b/core/java/android/pim/vcard/VCardParser_V30.java
@@ -0,0 +1,306 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+import android.pim.vcard.exception.VCardException;
+import android.util.Log;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashSet;
+
+/**
+ * This class is used to parse vcard3.0. <br>
+ * Please refer to vCard Specification 3.0 (http://tools.ietf.org/html/rfc2426)
+ */
+public class VCardParser_V30 extends VCardParser_V21 {
+    private static final String LOG_TAG = "VCardParser_V30";
+    
+    private static final HashSet<String> sAcceptablePropsWithParam = new HashSet<String>(
+            Arrays.asList(
+                    "BEGIN", "LOGO", "PHOTO", "LABEL", "FN", "TITLE", "SOUND", 
+                    "VERSION", "TEL", "EMAIL", "TZ", "GEO", "NOTE", "URL",
+                    "BDAY", "ROLE", "REV", "UID", "KEY", "MAILER", // 2.1
+                    "NAME", "PROFILE", "SOURCE", "NICKNAME", "CLASS",
+                    "SORT-STRING", "CATEGORIES", "PRODID")); // 3.0
+    
+    // Although "7bit" and "BASE64" is not allowed in vCard 3.0, we allow it for safety.
+    private static final HashSet<String> sAcceptableEncodingV30 = new HashSet<String>(
+            Arrays.asList("7BIT", "8BIT", "BASE64", "B"));
+    
+    // Although RFC 2426 specifies some property must not have parameters, we allow it, 
+    // since there may be some careers which violates the RFC...
+    private static final HashSet<String> acceptablePropsWithoutParam = new HashSet<String>();
+
+    private String mPreviousLine;
+    
+    @Override
+    protected String getVersion() {
+        return "3.0";
+    }
+    
+    @Override
+    protected boolean isValidPropertyName(String propertyName) {
+        if (!(sAcceptablePropsWithParam.contains(propertyName) ||
+                acceptablePropsWithoutParam.contains(propertyName) ||
+                propertyName.startsWith("X-")) &&
+                !mWarningValueMap.contains(propertyName)) {
+            mWarningValueMap.add(propertyName);
+            Log.w(LOG_TAG, "Property name unsupported by vCard 3.0: " + propertyName);
+        }
+        return true;
+    }
+    
+    @Override
+    protected boolean isValidEncoding(String encoding) {
+        return sAcceptableEncodingV30.contains(encoding.toUpperCase());
+    }
+    
+    @Override
+    protected String getLine() throws IOException {
+        if (mPreviousLine != null) {
+            String ret = mPreviousLine;
+            mPreviousLine = null;
+            return ret;
+        } else {
+            return mReader.readLine();
+        }
+    }
+    
+    /**
+     * vCard 3.0 requires that the line with space at the beginning of the line
+     * must be combined with previous line. 
+     */
+    @Override
+    protected String getNonEmptyLine() throws IOException, VCardException {
+        String line;
+        StringBuilder builder = null;
+        while (true) {
+            line = mReader.readLine();
+            if (line == null) {
+                if (builder != null) {
+                    return builder.toString();
+                } else if (mPreviousLine != null) {
+                    String ret = mPreviousLine;
+                    mPreviousLine = null;
+                    return ret;
+                }
+                throw new VCardException("Reached end of buffer.");
+            } else if (line.length() == 0) {
+                if (builder != null) {
+                    return builder.toString();
+                } else if (mPreviousLine != null) {
+                    String ret = mPreviousLine;
+                    mPreviousLine = null;
+                    return ret;
+                }
+            } else if (line.charAt(0) == ' ' || line.charAt(0) == '\t') {
+                if (builder != null) {
+                    // See Section 5.8.1 of RFC 2425 (MIME-DIR document).
+                    // Following is the excerpts from it.  
+                    //
+                    // DESCRIPTION:This is a long description that exists on a long line.
+                    // 
+                    // Can be represented as:
+                    //
+                    // DESCRIPTION:This is a long description
+                    //  that exists on a long line.
+                    //
+                    // It could also be represented as:
+                    //
+                    // DESCRIPTION:This is a long descrip
+                    //  tion that exists o
+                    //  n a long line.
+                    builder.append(line.substring(1));
+                } else if (mPreviousLine != null) {
+                    builder = new StringBuilder();
+                    builder.append(mPreviousLine);
+                    mPreviousLine = null;
+                    builder.append(line.substring(1));
+                } else {
+                    throw new VCardException("Space exists at the beginning of the line");
+                }
+            } else {
+                if (mPreviousLine == null) {
+                    mPreviousLine = line;
+                    if (builder != null) {
+                        return builder.toString();
+                    }
+                } else {
+                    String ret = mPreviousLine;
+                    mPreviousLine = line;
+                    return ret;
+                }
+            }
+        }
+    }
+    
+    
+    /**
+     * vcard = [group "."] "BEGIN" ":" "VCARD" 1*CRLF
+     *         1*(contentline)
+     *         ;A vCard object MUST include the VERSION, FN and N types.
+     *         [group "."] "END" ":" "VCARD" 1*CRLF
+     */
+    @Override
+    protected boolean readBeginVCard(boolean allowGarbage) throws IOException, VCardException {
+        // TODO: vCard 3.0 supports group.
+        return super.readBeginVCard(allowGarbage);
+    }
+    
+    @Override
+    protected void readEndVCard(boolean useCache, boolean allowGarbage)
+            throws IOException, VCardException {
+        // TODO: vCard 3.0 supports group.
+        super.readEndVCard(useCache, allowGarbage);
+    }
+
+    /**
+     * vCard 3.0 allows iana-token as paramType, while vCard 2.1 does not.
+     */
+    @Override
+    protected void handleParams(String params) throws VCardException {
+        try {
+            super.handleParams(params);
+        } catch (VCardException e) {
+            // maybe IANA type
+            String[] strArray = params.split("=", 2);
+            if (strArray.length == 2) {
+                handleAnyParam(strArray[0], strArray[1]);
+            } else {
+                // Must not come here in the current implementation.
+                throw new VCardException(
+                        "Unknown params value: " + params);
+            }
+        }
+    }
+    
+    @Override
+    protected void handleAnyParam(String paramName, String paramValue) {
+        // vCard 3.0 accept comma-separated multiple values, but
+        // current PropertyNode does not accept it.
+        // For now, we do not split the values.
+        //
+        // TODO: fix this.
+        super.handleAnyParam(paramName, paramValue);
+    }
+    
+    /**
+     *  vCard 3.0 defines
+     *  
+     *  param         = param-name "=" param-value *("," param-value)
+     *  param-name    = iana-token / x-name
+     *  param-value   = ptext / quoted-string
+     *  quoted-string = DQUOTE QSAFE-CHAR DQUOTE
+     */
+    @Override
+    protected void handleType(String ptypevalues) {
+        String[] ptypeArray = ptypevalues.split(",");
+        mBuilder.propertyParamType("TYPE");
+        for (String value : ptypeArray) {
+            int length = value.length();
+            if (length >= 2 && value.startsWith("\"") && value.endsWith("\"")) {
+                mBuilder.propertyParamValue(value.substring(1, value.length() - 1));
+            } else {
+                mBuilder.propertyParamValue(value);
+            }
+        }
+    }
+
+    @Override
+    protected void handleAgent(String propertyValue) throws VCardException {
+        // The way how vCard 3.0 supports "AGENT" is completely different from vCard 2.0.
+        //
+        // e.g.
+        // AGENT:BEGIN:VCARD\nFN:Joe Friday\nTEL:+1-919-555-7878\n
+        //  TITLE:Area Administrator\, Assistant\n EMAIL\;TYPE=INTERN\n
+        //  ET:jfriday@host.com\nEND:VCARD\n
+        //
+        // TODO: fix this.
+        //
+        // issue:
+        //  vCard 3.0 also allows this as an example.
+        //
+        // AGENT;VALUE=uri:
+        //  CID:JQPUBLIC.part3.960129T083020.xyzMail@host3.com
+        //
+        // This is not VCARD. Should we support this?
+        throw new VCardException("AGENT in vCard 3.0 is not supported yet.");
+    }
+    
+    /**
+     * vCard 3.0 does not require two CRLF at the last of BASE64 data.
+     * It only requires that data should be MIME-encoded.
+     */
+    @Override
+    protected String getBase64(String firstString) throws IOException, VCardException {
+        StringBuilder builder = new StringBuilder();
+        builder.append(firstString);
+        
+        while (true) {
+            String line = getLine();
+            if (line == null) {
+                throw new VCardException(
+                        "File ended during parsing BASE64 binary");
+            }
+            if (line.length() == 0) {
+                break;
+            } else if (!line.startsWith(" ") && !line.startsWith("\t")) {
+                mPreviousLine = line;
+                break;
+            }
+            builder.append(line);
+        }
+        
+        return builder.toString();
+    }
+    
+    /**
+     * ESCAPED-CHAR = "\\" / "\;" / "\," / "\n" / "\N")
+     *              ; \\ encodes \, \n or \N encodes newline
+     *              ; \; encodes ;, \, encodes ,
+     *              
+     * Note: Apple escape ':' into '\:' while does not escape '\'
+     */ 
+    @Override
+    protected String maybeUnescapeText(String text) {
+        StringBuilder builder = new StringBuilder();
+        int length = text.length();
+        for (int i = 0; i < length; i++) {
+            char ch = text.charAt(i);
+            if (ch == '\\' && i < length - 1) {
+                char next_ch = text.charAt(++i); 
+                if (next_ch == 'n' || next_ch == 'N') {
+                    builder.append("\r\n");
+                } else {
+                    builder.append(next_ch);
+                }
+            } else {
+                builder.append(ch);
+            }
+        }
+        return builder.toString();
+    }
+    
+    @Override
+    protected String maybeUnescape(char ch) {
+        if (ch == 'n' || ch == 'N') {
+            return "\r\n";
+        } else {
+            return String.valueOf(ch);
+        }
+    }
+}
diff --git a/core/java/android/pim/vcard/VCardSourceDetector.java b/core/java/android/pim/vcard/VCardSourceDetector.java
new file mode 100644
index 0000000..7e2be2b
--- /dev/null
+++ b/core/java/android/pim/vcard/VCardSourceDetector.java
@@ -0,0 +1,137 @@
+/*
+ * 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.
+ */
+package android.pim.vcard;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Class which tries to detects the source of the vCard from its properties.
+ * Currently this implementation is very premature.
+ * @hide
+ */
+public class VCardSourceDetector implements VCardBuilder {
+    // Should only be used in package. 
+    static final int TYPE_UNKNOWN = 0;
+    static final int TYPE_APPLE = 1;
+    static final int TYPE_JAPANESE_MOBILE_PHONE = 2;  // Used in Japanese mobile phones.
+    static final int TYPE_FOMA = 3;  // Used in some Japanese FOMA mobile phones.
+    static final int TYPE_WINDOWS_MOBILE_JP = 4;
+    // TODO: Excel, etc.
+
+    private static Set<String> APPLE_SIGNS = new HashSet<String>(Arrays.asList(
+            "X-PHONETIC-FIRST-NAME", "X-PHONETIC-MIDDLE-NAME", "X-PHONETIC-LAST-NAME",
+            "X-ABADR", "X-ABUID"));
+    
+    private static Set<String> JAPANESE_MOBILE_PHONE_SIGNS = new HashSet<String>(Arrays.asList(
+            "X-GNO", "X-GN", "X-REDUCTION"));
+    
+    private static Set<String> WINDOWS_MOBILE_PHONE_SIGNS = new HashSet<String>(Arrays.asList(
+            "X-MICROSOFT-ASST_TEL", "X-MICROSOFT-ASSISTANT", "X-MICROSOFT-OFFICELOC"));
+    
+    // Note: these signes appears before the signs of the other type (e.g. "X-GN").
+    // In other words, Japanese FOMA mobile phones are detected as FOMA, not JAPANESE_MOBILE_PHONES.
+    private static Set<String> FOMA_SIGNS = new HashSet<String>(Arrays.asList(
+            "X-SD-VERN", "X-SD-FORMAT_VER", "X-SD-CATEGORIES", "X-SD-CLASS", "X-SD-DCREATED",
+            "X-SD-DESCRIPTION"));
+    private static String TYPE_FOMA_CHARSET_SIGN = "X-SD-CHAR_CODE";
+    
+    private int mType = TYPE_UNKNOWN;
+    // Some mobile phones (like FOMA) tells us the charset of the data.
+    private boolean mNeedParseSpecifiedCharset;
+    private String mSpecifiedCharset;
+    
+    public void start() {
+    }
+    
+    public void end() {
+    }
+
+    public void startRecord(String type) {
+    }    
+
+    public void startProperty() {
+        mNeedParseSpecifiedCharset = false;
+    }
+    
+    public void endProperty() {
+    }
+
+    public void endRecord() {
+    }
+
+    public void propertyGroup(String group) {
+    }
+    
+    public void propertyName(String name) {
+        if (name.equalsIgnoreCase(TYPE_FOMA_CHARSET_SIGN)) {
+            mType = TYPE_FOMA;
+            mNeedParseSpecifiedCharset = true;
+            return;
+        }
+        if (mType != TYPE_UNKNOWN) {
+            return;
+        }
+        if (WINDOWS_MOBILE_PHONE_SIGNS.contains(name)) {
+            mType = TYPE_WINDOWS_MOBILE_JP;
+        } else if (FOMA_SIGNS.contains(name)) {
+            mType = TYPE_FOMA;
+        } else if (JAPANESE_MOBILE_PHONE_SIGNS.contains(name)) {
+            mType = TYPE_JAPANESE_MOBILE_PHONE;
+        } else if (APPLE_SIGNS.contains(name)) {
+            mType = TYPE_APPLE;
+        }
+    }
+
+    public void propertyParamType(String type) {
+    }
+
+    public void propertyParamValue(String value) {
+    }
+
+    public void propertyValues(List<String> values) {
+        if (mNeedParseSpecifiedCharset && values.size() > 0) {
+            mSpecifiedCharset = values.get(0);
+        }
+    }
+
+    int getType() {
+        return mType;
+    }
+    
+    /**
+     * Return charset String guessed from the source's properties.
+     * This method must be called after parsing target file(s).
+     * @return Charset String. Null is returned if guessing the source fails.
+     */
+    public String getEstimatedCharset() {
+        if (mSpecifiedCharset != null) {
+            return mSpecifiedCharset;
+        }
+        switch (mType) {
+        case TYPE_WINDOWS_MOBILE_JP:
+        case TYPE_FOMA:
+        case TYPE_JAPANESE_MOBILE_PHONE:
+            return "SHIFT_JIS";
+        case TYPE_APPLE:
+            return "UTF-8";
+        default:
+            return null;
+        }
+    }
+}
diff --git a/core/java/android/pim/vcard/exception/VCardException.java b/core/java/android/pim/vcard/exception/VCardException.java
new file mode 100644
index 0000000..e557219
--- /dev/null
+++ b/core/java/android/pim/vcard/exception/VCardException.java
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+package android.pim.vcard.exception;
+
+public class VCardException extends java.lang.Exception {
+    /**
+     * Constructs a VCardException object
+     */
+    public VCardException() {
+        super();
+    }
+
+    /**
+     * Constructs a VCardException object
+     *
+     * @param message the error message
+     */
+    public VCardException(String message) {
+        super(message);
+    }
+
+}
diff --git a/core/java/android/pim/vcard/exception/VCardNestedException.java b/core/java/android/pim/vcard/exception/VCardNestedException.java
new file mode 100644
index 0000000..503c2fb
--- /dev/null
+++ b/core/java/android/pim/vcard/exception/VCardNestedException.java
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+
+package android.pim.vcard.exception;
+
+/**
+ * VCardException thrown when VCard is nested without VCardParser's being notified.
+ */
+public class VCardNestedException extends VCardNotSupportedException {
+    public VCardNestedException() {
+        super();
+    }
+    public VCardNestedException(String message) {
+        super(message);
+    }
+}
diff --git a/core/java/android/pim/vcard/exception/VCardNotSupportedException.java b/core/java/android/pim/vcard/exception/VCardNotSupportedException.java
new file mode 100644
index 0000000..616aa7763
--- /dev/null
+++ b/core/java/android/pim/vcard/exception/VCardNotSupportedException.java
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+package android.pim.vcard.exception;
+
+/**
+ * The exception which tells that the input VCard is probably valid from the view of
+ * specification but not supported in the current framework for now.
+ * 
+ * This is a kind of a good news from the view of development.
+ * It may be good to ask users to send a report with the VCard example
+ * for the future development.
+ */
+public class VCardNotSupportedException extends VCardException {
+    public VCardNotSupportedException() {
+        super();
+    }
+    public VCardNotSupportedException(String message) {
+        super(message);
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/pim/vcard/exception/VCardVersionException.java b/core/java/android/pim/vcard/exception/VCardVersionException.java
new file mode 100644
index 0000000..9fe8b7f
--- /dev/null
+++ b/core/java/android/pim/vcard/exception/VCardVersionException.java
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+
+package android.pim.vcard.exception;
+
+/**
+ * VCardException used only when the version of the vCard is different. 
+ */
+public class VCardVersionException extends VCardException {
+    public VCardVersionException() {
+        super();
+    }
+    public VCardVersionException(String message) {
+        super(message);
+    }
+}
diff --git a/core/java/android/pim/vcard/exception/package.html b/core/java/android/pim/vcard/exception/package.html
new file mode 100644
index 0000000..26b8a32
--- /dev/null
+++ b/core/java/android/pim/vcard/exception/package.html
@@ -0,0 +1,5 @@
+<HTML>
+<BODY>
+{@hide}
+</BODY>
+</HTML>
\ No newline at end of file
diff --git a/core/java/android/pim/vcard/package.html b/core/java/android/pim/vcard/package.html
new file mode 100644
index 0000000..26b8a32
--- /dev/null
+++ b/core/java/android/pim/vcard/package.html
@@ -0,0 +1,5 @@
+<HTML>
+<BODY>
+{@hide}
+</BODY>
+</HTML>
\ No newline at end of file
diff --git a/core/java/android/preference/RingtonePreference.java b/core/java/android/preference/RingtonePreference.java
index 6beb06d..b46f180 100644
--- a/core/java/android/preference/RingtonePreference.java
+++ b/core/java/android/preference/RingtonePreference.java
@@ -31,8 +31,9 @@
  * The chosen ringtone's URI will be persisted as a string.
  * <p>
  * If the user chooses the "Default" item, the saved string will be one of
- * {@link System#DEFAULT_RINGTONE_URI} or
- * {@link System#DEFAULT_NOTIFICATION_URI}. If the user chooses the "Silent"
+ * {@link System#DEFAULT_RINGTONE_URI},
+ * {@link System#DEFAULT_NOTIFICATION_URI}, or
+ * {@link System#DEFAULT_ALARM_ALERT_URI}. If the user chooses the "Silent"
  * item, the saved string will be an empty string.
  * 
  * @attr ref android.R.styleable#RingtonePreference_ringtoneType
diff --git a/core/java/android/preference/VolumePreference.java b/core/java/android/preference/VolumePreference.java
index 20702a1..abdcd93 100644
--- a/core/java/android/preference/VolumePreference.java
+++ b/core/java/android/preference/VolumePreference.java
@@ -22,6 +22,7 @@
 import android.media.Ringtone;
 import android.media.RingtoneManager;
 import android.media.AudioManager;
+import android.net.Uri;
 import android.os.Handler;
 import android.preference.PreferenceManager;
 import android.provider.Settings;
@@ -147,10 +148,16 @@
                     System.getUriFor(System.VOLUME_SETTINGS[mStreamType]),
                     false, mVolumeObserver);
     
-            mRingtone = RingtoneManager.getRingtone(mContext,
-                    mStreamType == AudioManager.STREAM_NOTIFICATION
-                            ? Settings.System.DEFAULT_NOTIFICATION_URI
-                            : Settings.System.DEFAULT_RINGTONE_URI);
+            Uri defaultUri = null;
+            if (mStreamType == AudioManager.STREAM_RING) {
+                defaultUri = Settings.System.DEFAULT_RINGTONE_URI;
+            } else if (mStreamType == AudioManager.STREAM_NOTIFICATION) {
+                defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI;
+            } else {
+                defaultUri = Settings.System.DEFAULT_ALARM_ALERT_URI;
+            }
+
+            mRingtone = RingtoneManager.getRingtone(mContext, defaultUri);
             mRingtone.setStreamType(mStreamType);
         }
         
diff --git a/core/java/android/provider/Browser.java b/core/java/android/provider/Browser.java
index 1ba5e25e..b95e4e1 100644
--- a/core/java/android/provider/Browser.java
+++ b/core/java/android/provider/Browser.java
@@ -107,7 +107,7 @@
     public static final String[] HISTORY_PROJECTION = new String[] {
         BookmarkColumns._ID, BookmarkColumns.URL, BookmarkColumns.VISITS,
         BookmarkColumns.DATE, BookmarkColumns.BOOKMARK, BookmarkColumns.TITLE,
-        BookmarkColumns.FAVICON };
+        BookmarkColumns.FAVICON, BookmarkColumns.THUMBNAIL };
 
     /* these indices dependent on HISTORY_PROJECTION */
     public static final int HISTORY_PROJECTION_ID_INDEX = 0;
@@ -117,6 +117,10 @@
     public static final int HISTORY_PROJECTION_BOOKMARK_INDEX = 4;
     public static final int HISTORY_PROJECTION_TITLE_INDEX = 5;
     public static final int HISTORY_PROJECTION_FAVICON_INDEX = 6;
+    /**
+     * @hide
+     */
+    public static final int HISTORY_PROJECTION_THUMBNAIL_INDEX = 7;
 
     /* columns needed to determine whether to truncate history */
     public static final String[] TRUNCATE_HISTORY_PROJECTION = new String[] {
@@ -513,6 +517,10 @@
         public static final String TITLE = "title";
         public static final String CREATED = "created";
         public static final String FAVICON = "favicon";
+        /**
+         * @hide
+         */
+        public static final String THUMBNAIL = "thumbnail";
     }
 
     public static class SearchColumns implements BaseColumns {
diff --git a/core/java/android/provider/Calendar.java b/core/java/android/provider/Calendar.java
index 4a709f6..75bd989 100644
--- a/core/java/android/provider/Calendar.java
+++ b/core/java/android/provider/Calendar.java
@@ -32,6 +32,7 @@
 import android.text.format.Time;
 import android.util.Config;
 import android.util.Log;
+import android.accounts.Account;
 import com.android.internal.database.ArrayListCursor;
 import com.google.android.gdata.client.AndroidGDataClient;
 import com.google.android.gdata.client.AndroidXmlParserFactory;
@@ -80,6 +81,11 @@
     public interface CalendarsColumns
     {
         /**
+         * A string that uniquely identifies this contact to its source
+         */
+        public static final String SOURCE_ID = "sourceid";
+
+        /**
          * The color of the calendar
          * <P>Type: INTEGER (color value)</P>
          */
@@ -124,6 +130,12 @@
          * <p>Type: INTEGER (boolean)</p>
          */
         public static final String SYNC_EVENTS = "sync_events";
+
+        /**
+         * Sync state data.
+         * <p>Type: String (blob)</p>
+         */
+        public static final String SYNC_STATE = "sync_state";
     }
 
     /**
@@ -157,11 +169,12 @@
          * @param account the account whose rows should be deleted
          * @return the count of rows that were deleted
          */
-        public static int deleteCalendarsForAccount(ContentResolver cr,
-                String account) {
+        public static int deleteCalendarsForAccount(ContentResolver cr, Account account) {
             // delete all calendars that match this account
-            return Calendar.Calendars.delete(cr, Calendar.Calendars._SYNC_ACCOUNT + "=?",
-                    new String[] {account});
+            return Calendar.Calendars.delete(cr,
+                    Calendar.Calendars._SYNC_ACCOUNT + "=? AND "
+                            + Calendar.Calendars._SYNC_ACCOUNT_TYPE + "=?",
+                    new String[] {account.mName, account.mType});
         }
 
         /**
@@ -170,9 +183,6 @@
         public static final Uri CONTENT_URI =
             Uri.parse("content://calendar/calendars");
 
-        public static final Uri LIVE_CONTENT_URI =
-            Uri.parse("content://calendar/calendars?update=1");
-
         /**
          * The default sort order for this table
          */
@@ -694,6 +704,8 @@
          * The content:// style URL for this table
          */
         public static final Uri CONTENT_URI = Uri.parse("content://calendar/instances/when");
+        public static final Uri CONTENT_BY_DAY_URI =
+            Uri.parse("content://calendar/instances/whenbyday");
 
         /**
          * The default sort order for this table.
diff --git a/core/java/android/provider/CallLog.java b/core/java/android/provider/CallLog.java
index 7d03801..b54ad5d 100644
--- a/core/java/android/provider/CallLog.java
+++ b/core/java/android/provider/CallLog.java
@@ -73,7 +73,7 @@
         public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/calls";
 
         /**
-         * The type of the the phone number.
+         * The type of the call (incoming, outgoing or missed).
          * <P>Type: INTEGER (int)</P>
          */
         public static final String TYPE = "type";
@@ -151,34 +151,20 @@
                 int presentation, int callType, long start, int duration) {
             final ContentResolver resolver = context.getContentResolver();
 
-            // TODO(Moto): Which is correct: original code, this only changes the
-            // number if the number is empty and never changes the caller info name.
-        if (false) {
-            if (TextUtils.isEmpty(number)) {
-                if (presentation == Connection.PRESENTATION_RESTRICTED) {
-                    number = CallerInfo.PRIVATE_NUMBER;
-                } else if (presentation == Connection.PRESENTATION_PAYPHONE) {
-                    number = CallerInfo.PAYPHONE_NUMBER;
-                } else {
-                    number = CallerInfo.UNKNOWN_NUMBER;
-                }
-            }
-        } else {
-            // NEWCODE: From Motorola
-
-            //If this is a private number then set the number to Private, otherwise check
-            //if the number field is empty and set the number to Unavailable
+            // If this is a private number then set the number to Private, otherwise check
+            // if the number field is empty and set the number to Unavailable
             if (presentation == Connection.PRESENTATION_RESTRICTED) {
                 number = CallerInfo.PRIVATE_NUMBER;
-                ci.name = "";
+                if (ci != null) ci.name = "";
             } else if (presentation == Connection.PRESENTATION_PAYPHONE) {
                 number = CallerInfo.PAYPHONE_NUMBER;
-                ci.name = "";
-            } else if (TextUtils.isEmpty(number) || presentation == Connection.PRESENTATION_UNKNOWN) {
+                if (ci != null) ci.name = "";
+            } else if (TextUtils.isEmpty(number)
+                    || presentation == Connection.PRESENTATION_UNKNOWN) {
                 number = CallerInfo.UNKNOWN_NUMBER;
-                ci.name = "";
+                if (ci != null) ci.name = "";
             }
-        }
+
             ContentValues values = new ContentValues(5);
 
             values.put(NUMBER, number);
diff --git a/core/java/android/provider/Contacts.java b/core/java/android/provider/Contacts.java
index 84fe184..5f84e57 100644
--- a/core/java/android/provider/Contacts.java
+++ b/core/java/android/provider/Contacts.java
@@ -30,6 +30,7 @@
 import android.text.TextUtils;
 import android.util.Log;
 import android.widget.ImageView;
+import android.accounts.Account;
 
 import java.io.ByteArrayInputStream;
 import java.io.InputStream;
@@ -39,7 +40,7 @@
  */
 public class Contacts {
     private static final String TAG = "Contacts";
-    
+
     public static final String AUTHORITY = "contacts";
 
     /**
@@ -75,6 +76,12 @@
         public static final String _SYNC_ACCOUNT = "_sync_account";
 
         /**
+         * The _SYNC_ACCOUNT_TYPE to which this setting corresponds. This may be null.
+         * <P>Type: TEXT</P>
+         */
+        public static final String _SYNC_ACCOUNT_TYPE = "_sync_account_type";
+
+        /**
          * The key of this setting.
          * <P>Type: TEXT</P>
          */
@@ -134,6 +141,7 @@
                 selectString = (account == null)
                         ? "_sync_account is null AND key=?"
                         : "_sync_account=? AND key=?";
+//                : "_sync_account=? AND _sync_account_type=? AND key=?";
                 selectArgs = (account == null)
                 ? new String[]{key}
                 : new String[]{account, key};
@@ -158,7 +166,8 @@
             // the account name is, so we're using a global setting for SYNC_EVERYTHING.
             // Some day when we add multiple accounts to the UI this should honor the account
             // that was asked for.
-            //values.put(_SYNC_ACCOUNT, account);
+            //values.put(_SYNC_ACCOUNT, account.mName);
+            //values.put(_SYNC_ACCOUNT_TYPE, account.mType);
             values.put(KEY, key);
             values.put(VALUE, value);
             cr.update(Settings.CONTENT_URI, values, null, null);
@@ -182,7 +191,7 @@
          * <p>Type: TEXT</P>
          */
         public static final String PHONETIC_NAME = "phonetic_name";
-        
+
         /**
          * The display name. If name is not null name, else if number is not null number,
          * else if email is not null email.
@@ -197,7 +206,7 @@
          * @hide Used only in Contacts application for now.
          */
         public static final String SORT_STRING = "sort_string";
-        
+
         /**
          * Notes about the person.
          * <P>Type: TEXT</P>
@@ -239,7 +248,7 @@
          * The server version of the photo
          * <P>Type: TEXT (the version number portion of the photo URI)</P>
          */
-        public static final String PHOTO_VERSION = "photo_version";       
+        public static final String PHOTO_VERSION = "photo_version";
     }
 
     /**
@@ -278,14 +287,14 @@
          * additional path segment after this URI. This matches any people with
          * at least one E-mail or IM {@link ContactMethods} that match the
          * filter.
-         * 
+         *
          * Not exposed because we expect significant changes in the contacts
          * schema and do not want to have to support this.
          * @hide
          */
         public static final Uri WITH_EMAIL_OR_IM_FILTER_URI =
             Uri.parse("content://contacts/people/with_email_or_im_filter");
-        
+
         /**
          * The MIME type of {@link #CONTENT_URI} providing a directory of
          * people.
@@ -370,13 +379,13 @@
             if (groupId == 0) {
                 throw new IllegalStateException("Failed to find the My Contacts group");
             }
-            
+
             return addToGroup(resolver, personId, groupId);
         }
 
         /**
          * Adds a person to a group referred to by name.
-         * 
+         *
          * @param resolver the resolver to use
          * @param personId the person to add to the group
          * @param groupName the name of the group to add the contact to
@@ -400,13 +409,13 @@
             if (groupId == 0) {
                 throw new IllegalStateException("Failed to find the My Contacts group");
             }
-            
+
             return addToGroup(resolver, personId, groupId);
         }
 
         /**
          * Adds a person to a group.
-         * 
+         *
          * @param resolver the resolver to use
          * @param personId the person to add to the group
          * @param groupId the group to add the person to
@@ -418,14 +427,14 @@
             values.put(GroupMembership.GROUP_ID, groupId);
             return resolver.insert(GroupMembership.CONTENT_URI, values);
         }
-        
+
         private static final String[] GROUPS_PROJECTION = new String[] {
             Groups._ID,
         };
 
         /**
          * Creates a new contacts and adds it to the "My Contacts" group.
-         * 
+         *
          * @param resolver the ContentResolver to use
          * @param values the values to use when creating the contact
          * @return the URI of the contact, or null if the operation fails
@@ -463,7 +472,7 @@
             values.put(Photos.DATA, data);
             cr.update(photoUri, values, null, null);
         }
-        
+
         /**
          * Opens an InputStream for the person's photo and returns the photo as a Bitmap.
          * If the person's photo isn't present returns the placeholderImageResource instead.
@@ -730,7 +739,7 @@
             CharSequence display = "";
 
             if (type != People.Phones.TYPE_CUSTOM) {
-                CharSequence[] labels = labelArray != null? labelArray 
+                CharSequence[] labels = labelArray != null? labelArray
                         : context.getResources().getTextArray(
                                 com.android.internal.R.array.phoneTypes);
                 try {
@@ -750,7 +759,7 @@
                 CharSequence label) {
             return getDisplayLabel(context, type, label, null);
         }
-        
+
         /**
          * The content:// style URL for this table
          */
@@ -846,6 +855,12 @@
         public static final String GROUP_SYNC_ACCOUNT = "group_sync_account";
 
         /**
+         * The account type of the group.
+         * <P>Type: TEXT</P>
+         */
+        public static final String GROUP_SYNC_ACCOUNT_TYPE = "group_sync_account_type";
+
+        /**
          * The row id of the person.
          * <P>Type: TEXT</P>
          */
@@ -969,7 +984,7 @@
             throw new IllegalArgumentException(
                     "the value is not a valid encoded protocol, " + encodedString);
         }
-        
+
         /**
          * This looks up the provider name defined in
          * {@link android.provider.Im.ProviderNames} from the predefined IM protocol id.
@@ -1022,13 +1037,7 @@
                         }
                     } else {
                         if (!TextUtils.isEmpty(label)) {
-                            if (label.toString().equals(MOBILE_EMAIL_TYPE_NAME)) {
-                                display =
-                                    context.getString(
-                                            com.android.internal.R.string.mobileEmailTypeName);
-                            } else {
-                                display = label;
-                            }
+                            display = label;
                         }
                     }
                     break;
@@ -1188,7 +1197,7 @@
 
         /**
          * Gets the resource ID for the proper presence icon.
-         * 
+         *
          * @param status the status to get the icon for
          * @return the resource ID for the proper presence icon
          */
@@ -1196,17 +1205,17 @@
             switch (status) {
                 case Contacts.People.AVAILABLE:
                     return com.android.internal.R.drawable.presence_online;
-    
+
                 case Contacts.People.IDLE:
                 case Contacts.People.AWAY:
                     return com.android.internal.R.drawable.presence_away;
-    
+
                 case Contacts.People.DO_NOT_DISTURB:
                     return com.android.internal.R.drawable.presence_busy;
-    
+
                 case Contacts.People.INVISIBLE:
                     return com.android.internal.R.drawable.presence_invisible;
-                    
+
                 case Contacts.People.OFFLINE:
                 default:
                     return com.android.internal.R.drawable.presence_offline;
@@ -1229,7 +1238,7 @@
      */
     public interface OrganizationColumns {
         /**
-         * The type of the the phone number.
+         * The type of the organizations.
          * <P>Type: INTEGER (one of the constants below)</P>
          */
         public static final String TYPE = "type";
@@ -1446,28 +1455,27 @@
          * This is the intent that is fired when a search suggestion is clicked on.
          */
         public static final String SEARCH_SUGGESTION_CLICKED =
-                "android.provider.Contacts.SEARCH_SUGGESTION_CLICKED";
+                ContactsContract.Intents.SEARCH_SUGGESTION_CLICKED;
 
         /**
-         * This is the intent that is fired when a search suggestion for dialing a number 
+         * This is the intent that is fired when a search suggestion for dialing a number
          * is clicked on.
          */
         public static final String SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED =
-                "android.provider.Contacts.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED";
+                ContactsContract.Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED;
 
         /**
          * This is the intent that is fired when a search suggestion for creating a contact
          * is clicked on.
          */
         public static final String SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED =
-                "android.provider.Contacts.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED";
+                ContactsContract.Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED;
 
         /**
          * Starts an Activity that lets the user pick a contact to attach an image to.
          * After picking the contact it launches the image cropper in face detection mode.
          */
-        public static final String ATTACH_IMAGE =
-                "com.android.contacts.action.ATTACH_IMAGE";
+        public static final String ATTACH_IMAGE = ContactsContract.Intents.ATTACH_IMAGE;
 
         /**
          * Takes as input a data URI with a mailto: or tel: scheme. If a single
@@ -1493,7 +1501,7 @@
          * prompting the user when the contact doesn't exist.
          */
         public static final String SHOW_OR_CREATE_CONTACT =
-                "com.android.contacts.action.SHOW_OR_CREATE_CONTACT";
+                ContactsContract.Intents.SHOW_OR_CREATE_CONTACT;
 
         /**
          * Used with {@link #SHOW_OR_CREATE_CONTACT} to force creating a new
@@ -1502,9 +1510,8 @@
          * <p>
          * Type: BOOLEAN
          */
-        public static final String EXTRA_FORCE_CREATE =
-                "com.android.contacts.action.FORCE_CREATE";
-        
+        public static final String EXTRA_FORCE_CREATE = ContactsContract.Intents.EXTRA_FORCE_CREATE;
+
         /**
          * Used with {@link #SHOW_OR_CREATE_CONTACT} to specify an exact
          * description to be shown when prompting user about creating a new
@@ -1513,7 +1520,7 @@
          * Type: STRING
          */
         public static final String EXTRA_CREATE_DESCRIPTION =
-            "com.android.contacts.action.CREATE_DESCRIPTION";
+                ContactsContract.Intents.EXTRA_CREATE_DESCRIPTION;
 
         /**
          * Intents related to the Contacts app UI.
@@ -1522,43 +1529,42 @@
             /**
              * The action for the default contacts list tab.
              */
-            public static final String LIST_DEFAULT =
-                    "com.android.contacts.action.LIST_DEFAULT";
+            public static final String LIST_DEFAULT = ContactsContract.Intents.UI.LIST_DEFAULT;
 
             /**
              * The action for the contacts list tab.
              */
             public static final String LIST_GROUP_ACTION =
-                    "com.android.contacts.action.LIST_GROUP";
+                    ContactsContract.Intents.UI.LIST_GROUP_ACTION;
 
             /**
              * When in LIST_GROUP_ACTION mode, this is the group to display.
              */
-            public static final String GROUP_NAME_EXTRA_KEY = "com.android.contacts.extra.GROUP";
-            
+            public static final String GROUP_NAME_EXTRA_KEY =
+                    ContactsContract.Intents.UI.GROUP_NAME_EXTRA_KEY;
             /**
              * The action for the all contacts list tab.
              */
             public static final String LIST_ALL_CONTACTS_ACTION =
-                    "com.android.contacts.action.LIST_ALL_CONTACTS";
+                    ContactsContract.Intents.UI.LIST_ALL_CONTACTS_ACTION;
 
             /**
              * The action for the contacts with phone numbers list tab.
              */
             public static final String LIST_CONTACTS_WITH_PHONES_ACTION =
-                    "com.android.contacts.action.LIST_CONTACTS_WITH_PHONES";
+                    ContactsContract.Intents.UI.LIST_CONTACTS_WITH_PHONES_ACTION;
 
             /**
              * The action for the starred contacts list tab.
              */
             public static final String LIST_STARRED_ACTION =
-                    "com.android.contacts.action.LIST_STARRED";
+                    ContactsContract.Intents.UI.LIST_STARRED_ACTION;
 
             /**
              * The action for the frequent contacts list tab.
              */
             public static final String LIST_FREQUENT_ACTION =
-                    "com.android.contacts.action.LIST_FREQUENT";
+                    ContactsContract.Intents.UI.LIST_FREQUENT_ACTION;
 
             /**
              * The action for the "strequent" contacts list tab. It first lists the starred
@@ -1566,15 +1572,15 @@
              * order of the number of times they have been contacted.
              */
             public static final String LIST_STREQUENT_ACTION =
-                    "com.android.contacts.action.LIST_STREQUENT";
+                    ContactsContract.Intents.UI.LIST_STREQUENT_ACTION;
 
             /**
              * A key for to be used as an intent extra to set the activity
              * title to a custom String value.
              */
             public static final String TITLE_EXTRA_KEY =
-                "com.android.contacts.extra.TITLE_EXTRA";
-            
+                    ContactsContract.Intents.UI.TITLE_EXTRA_KEY;
+
             /**
              * Activity Action: Display a filtered list of contacts
              * <p>
@@ -1583,15 +1589,15 @@
              * <p>
              * Output: Nothing.
              */
-            public static final String FILTER_CONTACTS_ACTION = 
-                "com.android.contacts.action.FILTER_CONTACTS";
-            
+            public static final String FILTER_CONTACTS_ACTION =
+                    ContactsContract.Intents.UI.FILTER_CONTACTS_ACTION;
+
             /**
              * Used as an int extra field in {@link #FILTER_CONTACTS_ACTION}
              * intents to supply the text on which to filter.
              */
-            public static final String FILTER_TEXT_EXTRA_KEY = 
-                "com.android.contacts.extra.FILTER_TEXT";
+            public static final String FILTER_TEXT_EXTRA_KEY =
+                    ContactsContract.Intents.UI.FILTER_TEXT_EXTRA_KEY;
         }
 
         /**
@@ -1600,170 +1606,179 @@
          */
         public static final class Insert {
             /** The action code to use when adding a contact */
-            public static final String ACTION = Intent.ACTION_INSERT;
-
+            public static final String ACTION = ContactsContract.Intents.Insert.ACTION;
             /**
              * If present, forces a bypass of quick insert mode.
              */
-            public static final String FULL_MODE = "full_mode";
-
+            public static final String FULL_MODE = ContactsContract.Intents.Insert.FULL_MODE;
             /**
              * The extra field for the contact name.
              * <P>Type: String</P>
              */
-            public static final String NAME = "name";
+            public static final String NAME = ContactsContract.Intents.Insert.NAME;
 
             /**
              * The extra field for the contact phonetic name.
              * <P>Type: String</P>
              */
-            public static final String PHONETIC_NAME = "phonetic_name";
+            public static final String PHONETIC_NAME =
+                    ContactsContract.Intents.Insert.PHONETIC_NAME;
 
             /**
              * The extra field for the contact company.
              * <P>Type: String</P>
              */
-            public static final String COMPANY = "company";
+            public static final String COMPANY = ContactsContract.Intents.Insert.COMPANY;
 
             /**
              * The extra field for the contact job title.
              * <P>Type: String</P>
              */
-            public static final String JOB_TITLE = "job_title";
+            public static final String JOB_TITLE = ContactsContract.Intents.Insert.JOB_TITLE;
 
             /**
              * The extra field for the contact notes.
              * <P>Type: String</P>
              */
-            public static final String NOTES = "notes";
+            public static final String NOTES = ContactsContract.Intents.Insert.NOTES;
 
             /**
              * The extra field for the contact phone number.
              * <P>Type: String</P>
              */
-            public static final String PHONE = "phone";
+            public static final String PHONE = ContactsContract.Intents.Insert.PHONE;
 
             /**
              * The extra field for the contact phone number type.
              * <P>Type: Either an integer value from {@link android.provider.Contacts.PhonesColumns PhonesColumns},
              *  or a string specifying a custom label.</P>
              */
-            public static final String PHONE_TYPE = "phone_type";
+            public static final String PHONE_TYPE = ContactsContract.Intents.Insert.PHONE_TYPE;
 
             /**
              * The extra field for the phone isprimary flag.
              * <P>Type: boolean</P>
              */
-            public static final String PHONE_ISPRIMARY = "phone_isprimary";
+            public static final String PHONE_ISPRIMARY =
+                    ContactsContract.Intents.Insert.PHONE_ISPRIMARY;
 
             /**
              * The extra field for an optional second contact phone number.
              * <P>Type: String</P>
              */
-            public static final String SECONDARY_PHONE = "secondary_phone";
+            public static final String SECONDARY_PHONE =
+                    ContactsContract.Intents.Insert.SECONDARY_PHONE;
 
             /**
              * The extra field for an optional second contact phone number type.
              * <P>Type: Either an integer value from {@link android.provider.Contacts.PhonesColumns PhonesColumns},
              *  or a string specifying a custom label.</P>
              */
-            public static final String SECONDARY_PHONE_TYPE = "secondary_phone_type";
+            public static final String SECONDARY_PHONE_TYPE =
+                    ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE;
 
             /**
              * The extra field for an optional third contact phone number.
              * <P>Type: String</P>
              */
-            public static final String TERTIARY_PHONE = "tertiary_phone";
+            public static final String TERTIARY_PHONE =
+                    ContactsContract.Intents.Insert.TERTIARY_PHONE;
 
             /**
              * The extra field for an optional third contact phone number type.
              * <P>Type: Either an integer value from {@link android.provider.Contacts.PhonesColumns PhonesColumns},
              *  or a string specifying a custom label.</P>
              */
-            public static final String TERTIARY_PHONE_TYPE = "tertiary_phone_type";
+            public static final String TERTIARY_PHONE_TYPE =
+                    ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE;
 
             /**
              * The extra field for the contact email address.
              * <P>Type: String</P>
              */
-            public static final String EMAIL = "email";
+            public static final String EMAIL = ContactsContract.Intents.Insert.EMAIL;
 
             /**
              * The extra field for the contact email type.
              * <P>Type: Either an integer value from {@link android.provider.Contacts.ContactMethodsColumns ContactMethodsColumns}
              *  or a string specifying a custom label.</P>
              */
-            public static final String EMAIL_TYPE = "email_type";
+            public static final String EMAIL_TYPE = ContactsContract.Intents.Insert.EMAIL_TYPE;
 
             /**
              * The extra field for the email isprimary flag.
              * <P>Type: boolean</P>
              */
-            public static final String EMAIL_ISPRIMARY = "email_isprimary";
+            public static final String EMAIL_ISPRIMARY =
+                    ContactsContract.Intents.Insert.EMAIL_ISPRIMARY;
 
             /**
              * The extra field for an optional second contact email address.
              * <P>Type: String</P>
              */
-            public static final String SECONDARY_EMAIL = "secondary_email";
+            public static final String SECONDARY_EMAIL =
+                    ContactsContract.Intents.Insert.SECONDARY_EMAIL;
 
             /**
              * The extra field for an optional second contact email type.
              * <P>Type: Either an integer value from {@link android.provider.Contacts.ContactMethodsColumns ContactMethodsColumns}
              *  or a string specifying a custom label.</P>
              */
-            public static final String SECONDARY_EMAIL_TYPE = "secondary_email_type";
+            public static final String SECONDARY_EMAIL_TYPE =
+                    ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE;
 
             /**
              * The extra field for an optional third contact email address.
              * <P>Type: String</P>
              */
-            public static final String TERTIARY_EMAIL = "tertiary_email";
+            public static final String TERTIARY_EMAIL =
+                    ContactsContract.Intents.Insert.TERTIARY_EMAIL;
 
             /**
              * The extra field for an optional third contact email type.
              * <P>Type: Either an integer value from {@link android.provider.Contacts.ContactMethodsColumns ContactMethodsColumns}
              *  or a string specifying a custom label.</P>
              */
-            public static final String TERTIARY_EMAIL_TYPE = "tertiary_email_type";
+            public static final String TERTIARY_EMAIL_TYPE =
+                    ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE;
 
             /**
              * The extra field for the contact postal address.
              * <P>Type: String</P>
              */
-            public static final String POSTAL = "postal";
+            public static final String POSTAL = ContactsContract.Intents.Insert.POSTAL;
 
             /**
              * The extra field for the contact postal address type.
              * <P>Type: Either an integer value from {@link android.provider.Contacts.ContactMethodsColumns ContactMethodsColumns}
              *  or a string specifying a custom label.</P>
              */
-            public static final String POSTAL_TYPE = "postal_type";
+            public static final String POSTAL_TYPE = ContactsContract.Intents.Insert.POSTAL_TYPE;
 
             /**
              * The extra field for the postal isprimary flag.
              * <P>Type: boolean</P>
              */
-            public static final String POSTAL_ISPRIMARY = "postal_isprimary";
+            public static final String POSTAL_ISPRIMARY = ContactsContract.Intents.Insert.POSTAL_ISPRIMARY;
 
             /**
              * The extra field for an IM handle.
              * <P>Type: String</P>
              */
-            public static final String IM_HANDLE = "im_handle";
+            public static final String IM_HANDLE = ContactsContract.Intents.Insert.IM_HANDLE;
 
             /**
              * The extra field for the IM protocol
              * <P>Type: the result of {@link Contacts.ContactMethods#encodePredefinedImProtocol}
              * or {@link Contacts.ContactMethods#encodeCustomImProtocol}.</P>
              */
-            public static final String IM_PROTOCOL = "im_protocol";
+            public static final String IM_PROTOCOL = ContactsContract.Intents.Insert.IM_PROTOCOL;
 
             /**
              * The extra field for the IM isprimary flag.
              * <P>Type: boolean</P>
              */
-            public static final String IM_ISPRIMARY = "im_isprimary";
+            public static final String IM_ISPRIMARY = ContactsContract.Intents.Insert.IM_ISPRIMARY;
         }
     }
 }
diff --git a/core/java/android/provider/ContactsContract.java b/core/java/android/provider/ContactsContract.java
new file mode 100644
index 0000000..da1e9dc
--- /dev/null
+++ b/core/java/android/provider/ContactsContract.java
@@ -0,0 +1,1629 @@
+/*
+ * 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
+ */
+
+package android.provider;
+
+import android.content.Intent;
+import android.content.ContentProviderClient;
+import android.content.ContentProviderOperation;
+import android.content.res.Resources;
+import android.graphics.BitmapFactory;
+import android.net.Uri;
+import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
+import android.accounts.Account;
+import android.os.RemoteException;
+
+/**
+ * The contract between the contacts provider and applications. Contains definitions
+ * for the supported URIs and columns.
+ *
+ * @hide
+ */
+public final class ContactsContract {
+    /** The authority for the contacts provider */
+    public static final String AUTHORITY = "com.android.contacts";
+    /** A content:// style uri to the authority for the contacts provider */
+    public static final Uri AUTHORITY_URI = Uri.parse("content://" + AUTHORITY);
+
+    public interface SyncStateColumns extends SyncStateContract.Columns {
+    }
+
+    public static final class SyncState {
+        /**
+         * This utility class cannot be instantiated
+         */
+        private SyncState() {}
+
+        public static final String CONTENT_DIRECTORY =
+                SyncStateContract.Constants.CONTENT_DIRECTORY;
+
+        /**
+         * The content:// style URI for this table
+         */
+        public static final Uri CONTENT_URI =
+                Uri.withAppendedPath(AUTHORITY_URI, CONTENT_DIRECTORY);
+
+        /**
+         * @see android.provider.SyncStateContract.Helpers#get
+         */
+        public static byte[] get(ContentProviderClient provider, Account account)
+                throws RemoteException {
+            return SyncStateContract.Helpers.get(provider, CONTENT_URI, account);
+        }
+
+        /**
+         * @see android.provider.SyncStateContract.Helpers#set
+         */
+        public static void set(ContentProviderClient provider, Account account, byte[] data)
+                throws RemoteException {
+            SyncStateContract.Helpers.set(provider, CONTENT_URI, account, data);
+        }
+
+        /**
+         * @see android.provider.SyncStateContract.Helpers#newSetOperation
+         */
+        public static ContentProviderOperation newSetOperation(Account account, byte[] data) {
+            return SyncStateContract.Helpers.newSetOperation(CONTENT_URI, account, data);
+        }
+    }
+
+    public interface ContactOptionsColumns {
+        /**
+         * The number of times a person has been contacted
+         * <P>Type: INTEGER</P>
+         */
+        public static final String TIMES_CONTACTED = "times_contacted";
+
+        /**
+         * The last time a person was contacted.
+         * <P>Type: INTEGER</P>
+         */
+        public static final String LAST_TIME_CONTACTED = "last_time_contacted";
+
+        /**
+         * Is the contact starred?
+         * <P>Type: INTEGER (boolean)</P>
+         */
+        public static final String STARRED = "starred";
+
+        /**
+         * A custom ringtone associated with a person. Not always present.
+         * <P>Type: TEXT (URI to the ringtone)</P>
+         */
+        public static final String CUSTOM_RINGTONE = "custom_ringtone";
+
+        /**
+         * Whether the person should always be sent to voicemail. Not always
+         * present.
+         * <P>Type: INTEGER (0 for false, 1 for true)</P>
+         */
+        public static final String SEND_TO_VOICEMAIL = "send_to_voicemail";
+    }
+
+    private interface AggregatesColumns {
+        /**
+         * The display name for the contact.
+         * <P>Type: TEXT</P>
+         */
+        public static final String DISPLAY_NAME = "display_name";
+
+        /**
+         * Reference to the row in the data table holding the primary phone number.
+         * <P>Type: INTEGER REFERENCES data(_id)</P>
+         */
+        public static final String PRIMARY_PHONE_ID = "primary_phone_id";
+
+        /**
+         * Reference to the row in the data table holding the primary email address.
+         * <P>Type: INTEGER REFERENCES data(_id)</P>
+         */
+        public static final String PRIMARY_EMAIL_ID = "primary_email_id";
+
+        /**
+         * Reference to the row in the data table holding the photo.
+         * <P>Type: INTEGER REFERENCES data(_id)</P>
+         */
+        public static final String PHOTO_ID = "photo_id";
+
+        /**
+         * Lookup value that reflects the {@link Groups#GROUP_VISIBLE} state of
+         * any {@link GroupMembership} for this aggregate.
+         */
+        public static final String IN_VISIBLE_GROUP = "in_visible_group";
+
+        /**
+         * Contact presence status.  See {@link android.provider.Im.CommonPresenceColumns}
+         * for individual status definitions.
+         */
+        public static final String PRESENCE_STATUS = Presence.PRESENCE_STATUS;
+
+        /**
+         * The type of data, for example Home or Work.
+         * <P>Type: INTEGER</P>
+         */
+        public static final String PRIMARY_PHONE_TYPE = CommonDataKinds.Phone.TYPE;
+
+        /**
+         * The user defined label for the primary phone.
+         * <P>Type: TEXT</P>
+         */
+        public static final String PRIMARY_PHONE_LABEL = CommonDataKinds.Phone.LABEL;
+
+        /**
+         * The primary phone number.
+         * <P>Type: TEXT</P>
+         */
+        public static final String PRIMARY_PHONE_NUMBER = CommonDataKinds.Phone.NUMBER;
+    }
+
+
+    /**
+     * Constants for the aggregates table, which contains a record per group
+     * of contact representing the same person.
+     */
+    public static final class Aggregates implements BaseColumns, AggregatesColumns,
+            ContactOptionsColumns {
+        /**
+         * This utility class cannot be instantiated
+         */
+        private Aggregates()  {}
+
+        /**
+         * The content:// style URI for this table
+         */
+        public static final Uri CONTENT_URI = Uri.withAppendedPath(AUTHORITY_URI, "aggregates");
+
+        /**
+         * The content:// style URI for this table joined with useful data from
+         * {@link Data}.
+         */
+        public static final Uri CONTENT_SUMMARY_URI = Uri.withAppendedPath(AUTHORITY_URI,
+                "aggregates_summary");
+
+        /**
+         * The content:// style URI used for "type-to-filter" functionality on the
+         * {@link #CONTENT_SUMMARY_URI} URI. The filter string will be used to match
+         * various parts of the aggregate name. The filter argument should be passed
+         * as an additional path segment after this URI.
+         */
+        public static final Uri CONTENT_SUMMARY_FILTER_URI = Uri.withAppendedPath(
+                CONTENT_SUMMARY_URI, "filter");
+
+        /**
+         * The content:// style URI for this table joined with useful data from
+         * {@link Data}, filtered to include only starred aggregates
+         * and the most frequently contacted aggregates.
+         */
+        public static final Uri CONTENT_SUMMARY_STREQUENT_URI = Uri.withAppendedPath(
+                CONTENT_SUMMARY_URI, "strequent");
+
+        /**
+         * The content:// style URI used for "type-to-filter" functionality on the
+         * {@link #CONTENT_SUMMARY_STREQUENT_URI} URI. The filter string will be used to match
+         * various parts of the aggregate name. The filter argument should be passed
+         * as an additional path segment after this URI.
+         */
+        public static final Uri CONTENT_SUMMARY_STREQUENT_FILTER_URI = Uri.withAppendedPath(
+                CONTENT_SUMMARY_STREQUENT_URI, "filter");
+
+        public static final Uri CONTENT_SUMMARY_GROUP_URI = Uri.withAppendedPath(
+                CONTENT_SUMMARY_URI, "group");
+        /**
+         * The MIME type of {@link #CONTENT_URI} providing a directory of
+         * people.
+         */
+        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/person_aggregate";
+
+        /**
+         * The MIME type of a {@link #CONTENT_URI} subdirectory of a single
+         * person.
+         */
+        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/person_aggregate";
+
+        /**
+         * A sub-directory of a single contact aggregate that contains all of their
+         * {@link Data} rows.
+         */
+        public static final class Data implements BaseColumns, DataColumns {
+            /**
+             * no public constructor since this is a utility class
+             */
+            private Data() {}
+
+            /**
+             * The directory twig for this sub-table
+             */
+            public static final String CONTENT_DIRECTORY = "data";
+        }
+
+        /**
+         * A sub-directory of a single contact aggregate that contains all aggregation suggestions
+         * (other aggregates).  The aggregation suggestions are computed based on approximate
+         * data matches with this aggregate.
+         */
+        public static final class AggregationSuggestions implements BaseColumns, AggregatesColumns {
+            /**
+             * No public constructor since this is a utility class
+             */
+            private AggregationSuggestions() {}
+
+            /**
+             * The directory twig for this sub-table
+             */
+            public static final String CONTENT_DIRECTORY = "suggestions";
+
+            /**
+             * An optional query parameter that can be supplied to limit the number of returned
+             * suggestions.
+             * <p>
+             * Type: INTEGER
+             */
+            public static final String MAX_SUGGESTIONS = "max_suggestions";
+        }
+    }
+
+    /**
+     * Columns that appear when each row of a table belongs to a specific
+     * account, including sync information that an account may need.
+     */
+    private interface SyncColumns {
+        /**
+         * The name of the account instance to which this row belongs.
+         * <P>Type: TEXT</P>
+         */
+        public static final String ACCOUNT_NAME = "account_name";
+
+        /**
+         * The type of account to which this row belongs, which when paired with
+         * {@link #ACCOUNT_NAME} identifies a specific account.
+         * <P>Type: TEXT</P>
+         */
+        public static final String ACCOUNT_TYPE = "account_type";
+
+        /**
+         * String that uniquely identifies this row to its source account.
+         * <P>Type: TEXT</P>
+         */
+        public static final String SOURCE_ID = "sourceid";
+
+        /**
+         * Version number that is updated whenever this row or its related data
+         * changes.
+         * <P>Type: INTEGER</P>
+         */
+        public static final String VERSION = "version";
+
+        /**
+         * Flag indicating that {@link #VERSION} has changed, and this row needs
+         * to be synchronized by its owning account.
+         * <P>Type: INTEGER (boolean)</P>
+         */
+        public static final String DIRTY = "dirty";
+
+    }
+
+    private interface ContactsColumns {
+        /**
+         * A reference to the {@link Aggregates#_ID} that this data belongs to.
+         * <P>Type: INTEGER</P>
+         */
+        public static final String AGGREGATE_ID = "aggregate_id";
+
+        /**
+         * Flag indicating that this {@link Contacts} entry and its children has
+         * been restricted to specific platform apps.
+         * <P>Type: INTEGER (boolean)</P>
+         *
+         * @hide until finalized in future platform release
+         */
+        public static final String IS_RESTRICTED = "is_restricted";
+
+        /**
+         * The aggregation mode for this contact.
+         * <P>Type: INTEGER</P>
+         */
+        public static final String AGGREGATION_MODE = "aggregation_mode";
+    }
+
+    /**
+     * Constants for the contacts table, which contains the base contact information.
+     */
+    public static final class Contacts implements BaseColumns, ContactsColumns, SyncColumns,
+            ContactOptionsColumns {
+        /**
+         * This utility class cannot be instantiated
+         */
+        private Contacts() {
+        }
+
+        /**
+         * The content:// style URI for this table
+         */
+        public static final Uri CONTENT_URI = Uri.withAppendedPath(AUTHORITY_URI, "contacts");
+
+        /**
+         * The content:// style URL for filtering people by email address. The
+         * filter argument should be passed as an additional path segment after
+         * this URI.
+         *
+         * @hide
+         */
+        public static final Uri CONTENT_FILTER_EMAIL_URI =
+                Uri.withAppendedPath(CONTENT_URI, "filter_email");
+
+        /**
+         * The MIME type of {@link #CONTENT_URI} providing a directory of
+         * people.
+         */
+        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/person";
+
+        /**
+         * The MIME type of a {@link #CONTENT_URI} subdirectory of a single
+         * person.
+         */
+        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/person";
+
+        /**
+         * Aggregation mode: aggregate asynchronously.
+         */
+        public static final int AGGREGATION_MODE_DEFAULT = 0;
+
+        /**
+         * Aggregation mode: aggregate at the time the contact is inserted/updated.
+         */
+        public static final int AGGREGATION_MODE_IMMEDITATE = 1;
+
+        /**
+         * Aggregation mode: never aggregate this contact (note that the contact will not
+         * have a corresponding Aggregate and therefore will not be included in Aggregates
+         * query results.)
+         */
+        public static final int AGGREGATION_MODE_DISABLED = 2;
+
+        /**
+         * A sub-directory of a single contact that contains all of their {@link Data} rows.
+         * To access this directory append
+         */
+        public static final class Data implements BaseColumns, DataColumns {
+            /**
+             * no public constructor since this is a utility class
+             */
+            private Data() {
+            }
+
+            /**
+             * The directory twig for this sub-table
+             */
+            public static final String CONTENT_DIRECTORY = "data";
+        }
+    }
+
+    private interface DataColumns {
+        /**
+         * The package name to use when creating {@link Resources} objects for
+         * this data row. This value is only designed for use when building user
+         * interfaces, and should not be used to infer the owner.
+         */
+        public static final String RES_PACKAGE = "res_package";
+
+        /**
+         * The MIME type of the item represented by this row.
+         */
+        public static final String MIMETYPE = "mimetype";
+
+        /**
+         * A reference to the {@link android.provider.ContactsContract.Contacts#_ID}
+         * that this data belongs to.
+         */
+        public static final String CONTACT_ID = "contact_id";
+
+        /**
+         * Whether this is the primary entry of its kind for the contact it belongs to
+         * <P>Type: INTEGER (if set, non-0 means true)</P>
+         */
+        public static final String IS_PRIMARY = "is_primary";
+
+        /**
+         * Whether this is the primary entry of its kind for the aggregate it belongs to. Any data
+         * record that is "super primary" must also be "primary".
+         * <P>Type: INTEGER (if set, non-0 means true)</P>
+         */
+        public static final String IS_SUPER_PRIMARY = "is_super_primary";
+
+        /**
+         * The version of this data record. This is a read-only value. The data column is
+         * guaranteed to not change without the version going up. This value is monotonically
+         * increasing.
+         * <P>Type: INTEGER</P>
+         */
+        public static final String DATA_VERSION = "data_version";
+
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA1 = "data1";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA2 = "data2";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA3 = "data3";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA4 = "data4";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA5 = "data5";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA6 = "data6";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA7 = "data7";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA8 = "data8";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA9 = "data9";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA10 = "data10";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA11 = "data11";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA12 = "data12";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA13 = "data13";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA14 = "data14";
+        /** Generic data column, the meaning is {@link #MIMETYPE} specific */
+        public static final String DATA15 = "data15";
+    }
+
+    /**
+     * Constants for the data table, which contains data points tied to a contact.
+     * For example, a phone number or email address. Each row in this table contains a type
+     * definition and some generic columns. Each data type can define the meaning for each of
+     * the generic columns.
+     */
+    public static final class Data implements BaseColumns, DataColumns {
+        /**
+         * This utility class cannot be instantiated
+         */
+        private Data() {}
+
+        /**
+         * The content:// style URI for this table
+         */
+        public static final Uri CONTENT_URI = Uri.withAppendedPath(AUTHORITY_URI, "data");
+
+        /**
+         * The MIME type of {@link #CONTENT_URI} providing a directory of data.
+         */
+        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/data";
+    }
+
+    /**
+     * A table that represents the result of looking up a phone number, for
+     * example for caller ID. The table joins that data row for the phone number
+     * with the contact that owns the number. To perform a lookup you must
+     * append the number you want to find to {@link #CONTENT_FILTER_URI}.
+     */
+    public static final class PhoneLookup implements BaseColumns, DataColumns, AggregatesColumns {
+        /**
+         * This utility class cannot be instantiated
+         */
+        private PhoneLookup() {}
+
+        /**
+         * The content:// style URI for this table. Append the phone number you want to lookup
+         * to this URI and query it to perform a lookup. For example:
+         *
+         * {@code
+         * Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_URI, phoneNumber);
+         * }
+         */
+        public static final Uri CONTENT_FILTER_URI = Uri.withAppendedPath(AUTHORITY_URI,
+                "phone_lookup");
+    }
+
+    /**
+     * Additional data mixed in with {@link Im.CommonPresenceColumns} to link
+     * back to specific {@link ContactsContract.Aggregates#_ID} entries.
+     */
+    private interface PresenceColumns {
+
+        /**
+         * The unique ID for a row.
+         * <P>Type: INTEGER (long)</P>
+         */
+        public static final String _ID = "presence_id";
+
+        /**
+         * Reference to the {@link android.provider.ContactsContract.Contacts#_ID} this presence
+         * references.
+         * <P>Type: INTEGER</P>
+         */
+        public static final String CONTACT_ID = "contact_id";
+
+        /**
+         * Reference to the {@link Data#_ID} entry that owns this presence.
+         * <P>Type: INTEGER</P>
+         */
+        public static final String DATA_ID = "data_id";
+
+        /**
+         * The IM service the presence is coming from. Formatted using either
+         * {@link CommonDataKinds.Im#encodePredefinedImProtocol(int)} or
+         * {@link CommonDataKinds.Im#encodeCustomImProtocol(String)}.
+         * <P>Type: TEXT</P>
+         */
+        public static final String IM_PROTOCOL = "im_protocol";
+
+        /**
+         * The IM handle the presence item is for. The handle is scoped to the
+         * {@link #IM_PROTOCOL}.
+         * <P>Type: TEXT</P>
+         */
+        public static final String IM_HANDLE = "im_handle";
+
+        /**
+         * The IM account for the local user that the presence data came from.
+         * <P>Type: TEXT</P>
+         */
+        public static final String IM_ACCOUNT = "im_account";
+    }
+
+    public static final class Presence implements PresenceColumns, Im.CommonPresenceColumns {
+        /**
+         * This utility class cannot be instantiated
+         */
+        private Presence() {
+        }
+
+        /**
+         * The content:// style URI for this table
+         */
+        public static final Uri CONTENT_URI = Uri.withAppendedPath(AUTHORITY_URI, "presence");
+
+        /**
+         * Gets the resource ID for the proper presence icon.
+         *
+         * @param status the status to get the icon for
+         * @return the resource ID for the proper presence icon
+         */
+        public static final int getPresenceIconResourceId(int status) {
+            switch (status) {
+                case AVAILABLE:
+                    return android.R.drawable.presence_online;
+                case IDLE:
+                case AWAY:
+                    return android.R.drawable.presence_away;
+                case DO_NOT_DISTURB:
+                    return android.R.drawable.presence_busy;
+                case INVISIBLE:
+                    return android.R.drawable.presence_invisible;
+                case OFFLINE:
+                default:
+                    return android.R.drawable.presence_offline;
+            }
+        }
+
+        /**
+         * Returns the precedence of the status code the higher number being the higher precedence.
+         *
+         * @param status The status code.
+         * @return An integer representing the precedence, 0 being the lowest.
+         */
+        public static final int getPresencePrecedence(int status) {
+            // Keep this function here incase we want to enforce a different precedence than the
+            // natural order of the status constants.
+            return status;
+        }
+
+        /**
+         * The MIME type of {@link #CONTENT_URI} providing a directory of
+         * presence details.
+         */
+        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/im-presence";
+
+        /**
+         * The MIME type of a {@link #CONTENT_URI} subdirectory of a single
+         * presence detail.
+         */
+        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/im-presence";
+    }
+
+    /**
+     * Container for definitions of common data types stored in the {@link Data} table.
+     */
+    public static final class CommonDataKinds {
+        /**
+         * The {@link Data#RES_PACKAGE} value for common data that should be
+         * shown using a default style.
+         */
+        public static final String PACKAGE_COMMON = "common";
+
+        /**
+         * Columns common across the specific types.
+         */
+        private interface BaseCommonColumns {
+            /**
+             * The package name to use when creating {@link Resources} objects for
+             * this data row. This value is only designed for use when building user
+             * interfaces, and should not be used to infer the owner.
+             */
+            public static final String RES_PACKAGE = "res_package";
+
+            /**
+             * The MIME type of the item represented by this row.
+             */
+            public static final String MIMETYPE = "mimetype";
+
+            /**
+             * The {@link Contacts#_ID} that this data belongs to.
+             */
+            public static final String CONTACT_ID = "contact_id";
+        }
+
+        /**
+         * The base types that all "Typed" data kinds support.
+         */
+        public interface BaseTypes {
+
+            /**
+             * A custom type. The custom label should be supplied by user.
+             */
+            public static int TYPE_CUSTOM = 0;
+        }
+
+        /**
+         * Columns common across the specific types.
+         */
+        private interface CommonColumns extends BaseTypes{
+            /**
+             * The type of data, for example Home or Work.
+             * <P>Type: INTEGER</P>
+             */
+            public static final String TYPE = "data1";
+
+            /**
+             * The data for the contact method.
+             * <P>Type: TEXT</P>
+             */
+            public static final String DATA = "data2";
+
+            /**
+             * The user defined label for the the contact method.
+             * <P>Type: TEXT</P>
+             */
+            public static final String LABEL = "data3";
+        }
+
+        /**
+         * Parts of the name.
+         */
+        public static final class StructuredName implements BaseCommonColumns {
+            private StructuredName() {}
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/name";
+
+            /**
+             * The given name for the contact.
+             * <P>Type: TEXT</P>
+             */
+            public static final String GIVEN_NAME = "data1";
+
+            /**
+             * The family name for the contact.
+             * <P>Type: TEXT</P>
+             */
+            public static final String FAMILY_NAME = "data2";
+
+            /**
+             * The contact's honorific prefix, e.g. "Sir"
+             * <P>Type: TEXT</P>
+             */
+            public static final String PREFIX = "data3";
+
+            /**
+             * The contact's middle name
+             * <P>Type: TEXT</P>
+             */
+            public static final String MIDDLE_NAME = "data4";
+
+            /**
+             * The contact's honorific suffix, e.g. "Jr"
+             */
+            public static final String SUFFIX = "data5";
+
+            /**
+             * The phonetic version of the given name for the contact.
+             * <P>Type: TEXT</P>
+             */
+            public static final String PHONETIC_GIVEN_NAME = "data6";
+
+            /**
+             * The phonetic version of the additional name for the contact.
+             * <P>Type: TEXT</P>
+             */
+            public static final String PHONETIC_MIDDLE_NAME = "data7";
+
+            /**
+             * The phonetic version of the family name for the contact.
+             * <P>Type: TEXT</P>
+             */
+            public static final String PHONETIC_FAMILY_NAME = "data8";
+
+            /**
+             * The name that should be used to display the contact.
+             * <P>Type: TEXT</P>
+             */
+            public static final String DISPLAY_NAME = "data9";
+        }
+
+        /**
+         * A nickname.
+         */
+        public static final class Nickname implements CommonColumns, BaseCommonColumns {
+            private Nickname() {}
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/nickname";
+
+            public static final int TYPE_DEFAULT = 1;
+            public static final int TYPE_OTHER_NAME = 2;
+            public static final int TYPE_MAINDEN_NAME = 3;
+            public static final int TYPE_SHORT_NAME = 4;
+            public static final int TYPE_INITIALS = 5;
+
+            /**
+             * The name itself
+             */
+            public static final String NAME = DATA;
+        }
+
+        /**
+         * Common data definition for telephone numbers.
+         */
+        public static final class Phone implements BaseCommonColumns, CommonColumns {
+            private Phone() {}
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/phone";
+
+            /**
+             * The MIME type of {@link #CONTENT_URI} providing a directory of
+             * phones.
+             */
+            public static final String CONTENT_TYPE = "vnd.android.cursor.dir/phone";
+
+            /**
+             * The content:// style URI for all data records of the
+             * {@link Phone#CONTENT_ITEM_TYPE} MIME type, combined with the
+             * associated contact and aggregate data.
+             */
+            public static final Uri CONTENT_URI = Uri.withAppendedPath(Data.CONTENT_URI,
+                    "phones");
+
+            /**
+             * The content:// style URI for filtering data records of the
+             * {@link Phone#CONTENT_ITEM_TYPE} MIME type, combined with the
+             * associated contact and aggregate data. The filter argument should
+             * be passed as an additional path segment after this URI.
+             */
+            public static final Uri CONTENT_FILTER_URI = Uri.withAppendedPath(CONTENT_URI,
+                    "filter");
+
+            public static final int TYPE_HOME = 1;
+            public static final int TYPE_MOBILE = 2;
+            public static final int TYPE_WORK = 3;
+            public static final int TYPE_FAX_WORK = 4;
+            public static final int TYPE_FAX_HOME = 5;
+            public static final int TYPE_PAGER = 6;
+            public static final int TYPE_OTHER = 7;
+
+            /**
+             * The phone number as the user entered it.
+             * <P>Type: TEXT</P>
+             */
+            public static final String NUMBER = DATA;
+        }
+
+        /**
+         * Common data definition for email addresses.
+         */
+        public static final class Email implements BaseCommonColumns, CommonColumns {
+            private Email() {}
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/email";
+
+            public static final int TYPE_HOME = 1;
+            public static final int TYPE_WORK = 2;
+            public static final int TYPE_OTHER = 3;
+        }
+
+        /**
+         * Common data definition for postal addresses.
+         */
+        public static final class StructuredPostal implements BaseCommonColumns, CommonColumns {
+            private StructuredPostal() {
+            }
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/postal-address";
+
+            /**
+             * The MIME type of {@link #CONTENT_URI} providing a directory of
+             * postal addresses.
+             */
+            public static final String CONTENT_TYPE = "vnd.android.cursor.dir/postal-address";
+
+            /**
+             * The content:// style URI for all data records of the
+             * {@link StructuredPostal#CONTENT_ITEM_TYPE} MIME type.
+             */
+            public static final Uri CONTENT_URI = Uri.withAppendedPath(Data.CONTENT_URI,
+                    "postals");
+
+            public static final int TYPE_HOME = 1;
+            public static final int TYPE_WORK = 2;
+            public static final int TYPE_OTHER = 3;
+
+            /**
+             * The full, unstructured postal address.
+             * <p>
+             * Type: TEXT
+             */
+            public static final String FORMATTED_ADDRESS = DATA;
+
+            /**
+             * The agent who actually receives the mail. Used in work addresses.
+             * Also for 'in care of' or 'c/o'.
+             * <p>
+             * Type: TEXT
+             */
+            public static final String AGENT = "data4";
+
+            /**
+             * Used in places where houses or buildings have names (and not
+             * necessarily numbers), eg. "The Pillars".
+             * <p>
+             * Type: TEXT
+             */
+            public static final String HOUSENAME = "data5";
+
+            /**
+             * Can be street, avenue, road, etc. This element also includes the
+             * house number and room/apartment/flat/floor number.
+             * <p>
+             * Type: TEXT
+             */
+            public static final String STREET = "data6";
+
+            /**
+             * Covers actual P.O. boxes, drawers, locked bags, etc. This is
+             * usually but not always mutually exclusive with street.
+             * <p>
+             * Type: TEXT
+             */
+            public static final String POBOX = "data7";
+
+            /**
+             * This is used to disambiguate a street address when a city
+             * contains more than one street with the same name, or to specify a
+             * small place whose mail is routed through a larger postal town. In
+             * China it could be a county or a minor city.
+             * <p>
+             * Type: TEXT
+             */
+            public static final String NEIGHBORHOOD = "data8";
+
+            /**
+             * Can be city, village, town, borough, etc. This is the postal town
+             * and not necessarily the place of residence or place of business.
+             * <p>
+             * Type: TEXT
+             */
+            public static final String CITY = "data9";
+
+            /**
+             * Handles administrative districts such as U.S. or U.K. counties
+             * that are not used for mail addressing purposes. Subregion is not
+             * intended for delivery addresses.
+             * <p>
+             * Type: TEXT
+             */
+            public static final String SUBREGION = "data10";
+
+            /**
+             * A state, province, county (in Ireland), Land (in Germany),
+             * departement (in France), etc.
+             * <p>
+             * Type: TEXT
+             */
+            public static final String REGION = "data11";
+
+            /**
+             * Postal code. Usually country-wide, but sometimes specific to the
+             * city (e.g. "2" in "Dublin 2, Ireland" addresses).
+             * <p>
+             * Type: TEXT
+             */
+            public static final String POSTCODE = "data12";
+
+            /**
+             * The name or code of the country.
+             * <p>
+             * Type: TEXT
+             */
+            public static final String COUNTRY = "data13";
+        }
+
+       /**
+        * Common data definition for IM addresses.
+        */
+        public static final class Im implements BaseCommonColumns, CommonColumns {
+            private Im() {}
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/im";
+
+            public static final int TYPE_HOME = 1;
+            public static final int TYPE_WORK = 2;
+            public static final int TYPE_OTHER = 3;
+
+            public static final String PROTOCOL = "data5";
+
+            /**
+             * The predefined IM protocol types. The protocol can either be non-present, one
+             * of these types, or a free-form string. These cases are encoded in the PROTOCOL
+             * column as:
+             * <ul>
+             * <li>null</li>
+             * <li>pre:&lt;an integer, one of the protocols below&gt;</li>
+             * <li>custom:&lt;a string&gt;</li>
+             * </ul>
+             */
+            public static final int PROTOCOL_AIM = 0;
+            public static final int PROTOCOL_MSN = 1;
+            public static final int PROTOCOL_YAHOO = 2;
+            public static final int PROTOCOL_SKYPE = 3;
+            public static final int PROTOCOL_QQ = 4;
+            public static final int PROTOCOL_GOOGLE_TALK = 5;
+            public static final int PROTOCOL_ICQ = 6;
+            public static final int PROTOCOL_JABBER = 7;
+
+            public static String encodePredefinedImProtocol(int protocol) {
+               return "pre:" + protocol;
+            }
+
+            public static String encodeCustomImProtocol(String protocolString) {
+               return "custom:" + protocolString;
+            }
+
+            public static Object decodeImProtocol(String encodedString) {
+               if (encodedString == null) {
+                   return null;
+               }
+
+               if (encodedString.startsWith("pre:")) {
+                   return Integer.parseInt(encodedString.substring(4));
+               }
+
+               if (encodedString.startsWith("custom:")) {
+                   return encodedString.substring(7);
+               }
+
+               throw new IllegalArgumentException(
+                       "the value is not a valid encoded protocol, " + encodedString);
+            }
+        }
+
+        /**
+         * Common data definition for organizations.
+         */
+        public static final class Organization implements BaseCommonColumns, CommonColumns {
+            private Organization() {}
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/organization";
+
+            public static final int TYPE_WORK = 1;
+            public static final int TYPE_OTHER = 2;
+
+            /**
+             * The company as the user entered it.
+             * <P>Type: TEXT</P>
+             */
+            public static final String COMPANY = DATA;
+
+            /**
+             * The position title at this company as the user entered it.
+             * <P>Type: TEXT</P>
+             */
+            public static final String TITLE = "data4";
+        }
+
+        /**
+         * Photo of the contact.
+         */
+        public static final class Photo implements BaseCommonColumns {
+            private Photo() {}
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/photo";
+
+            /**
+             * Thumbnail photo of the contact. This is the raw bytes of an image
+             * that could be inflated using {@link BitmapFactory}.
+             * <p>
+             * Type: BLOB
+             */
+            public static final String PHOTO = "data1";
+        }
+
+        /**
+         * Notes about the contact.
+         */
+        public static final class Note implements BaseCommonColumns {
+            private Note() {}
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/note";
+
+            /**
+             * The note text.
+             * <P>Type: TEXT</P>
+             */
+            public static final String NOTE = "data1";
+        }
+
+        /**
+         * Group Membership.
+         */
+        public static final class GroupMembership implements BaseCommonColumns {
+            private GroupMembership() {}
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE =
+                    "vnd.android.cursor.item/group_membership";
+
+            /**
+             * The row id of the group that this group membership refers to. Exactly one of
+             * this or {@link #GROUP_SOURCE_ID} must be set when inserting a row.
+             * <P>Type: INTEGER</P>
+             */
+            public static final String GROUP_ROW_ID = "data1";
+
+            /**
+             * The sourceid of the group that this group membership refers to.  Exactly one of
+             * this or {@link #GROUP_ROW_ID} must be set when inserting a row.
+             * <P>Type: TEXT</P>
+             */
+            public static final String GROUP_SOURCE_ID = "group_sourceid";
+        }
+
+        /**
+         * Website related to the contact.
+         */
+        public static final class Website implements BaseCommonColumns {
+            private Website() {}
+
+            /** MIME type used when storing this in data table. */
+            public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/website";
+
+            /**
+             * The website URL string.
+             * <P>Type: TEXT</P>
+             */
+            public static final String URL = "data1";
+        }
+    }
+
+    public interface GroupsColumns {
+        /**
+         * The display title of this group.
+         * <p>
+         * Type: TEXT
+         */
+        public static final String TITLE = "title";
+
+        /**
+         * The package name to use when creating {@link Resources} objects for
+         * this group. This value is only designed for use when building user
+         * interfaces, and should not be used to infer the owner.
+         */
+        public static final String RES_PACKAGE = "res_package";
+
+        /**
+         * The display title of this group to load as a resource from
+         * {@link #RES_PACKAGE}, which may be localized.
+         * <P>Type: TEXT</P>
+         */
+        public static final String TITLE_RES = "title_res";
+
+        /**
+         * Notes about the group.
+         * <p>
+         * Type: TEXT
+         */
+        public static final String NOTES = "notes";
+
+        /**
+         * The ID of this group if it is a System Group, i.e. a group that has a special meaning
+         * to the sync adapter, null otherwise.
+         * <P>Type: TEXT</P>
+         */
+        public static final String SYSTEM_ID = "system_id";
+
+        /**
+         * The total number of {@link Aggregates} that have
+         * {@link GroupMembership} in this group. Read-only value that is only
+         * present when querying {@link Groups#CONTENT_SUMMARY_URI}.
+         * <p>
+         * Type: INTEGER
+         */
+        public static final String SUMMARY_COUNT = "summ_count";
+
+        /**
+         * The total number of {@link Aggregates} that have both
+         * {@link GroupMembership} in this group, and also have phone numbers.
+         * Read-only value that is only present when querying
+         * {@link Groups#CONTENT_SUMMARY_URI}.
+         * <p>
+         * Type: INTEGER
+         */
+        public static final String SUMMARY_WITH_PHONES = "summ_phones";
+
+        /**
+         * Flag indicating if the contacts belonging to this group should be
+         * visible in any user interface.
+         * <p>
+         * Type: INTEGER
+         */
+        public static final String GROUP_VISIBLE = "group_visible";
+    }
+
+    /**
+     * Constants for the groups table.
+     */
+    public static final class Groups implements BaseColumns, GroupsColumns, SyncColumns {
+        /**
+         * This utility class cannot be instantiated
+         */
+        private Groups() {
+        }
+
+        /**
+         * The content:// style URI for this table
+         */
+        public static final Uri CONTENT_URI = Uri.withAppendedPath(AUTHORITY_URI, "groups");
+
+        /**
+         * The content:// style URI for this table joined with details data from
+         * {@link Data}.
+         */
+        public static final Uri CONTENT_SUMMARY_URI = Uri.withAppendedPath(AUTHORITY_URI,
+                "groups_summary");
+
+        /**
+         * The MIME type of a directory of groups.
+         */
+        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/group";
+
+        /**
+         * The MIME type of a single group.
+         */
+        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/group";
+    }
+
+    /**
+     * Constants for the contact aggregation exceptions table, which contains
+     * aggregation rules overriding those used by automatic aggregation.  This type only
+     * supports query and update. Neither insert nor delete are supported.
+     */
+    public static final class AggregationExceptions implements BaseColumns {
+        /**
+         * This utility class cannot be instantiated
+         */
+        private AggregationExceptions() {}
+
+        /**
+         * The content:// style URI for this table
+         */
+        public static final Uri CONTENT_URI =
+                Uri.withAppendedPath(AUTHORITY_URI, "aggregation_exceptions");
+
+        /**
+         * The MIME type of {@link #CONTENT_URI} providing a directory of data.
+         */
+        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/aggregation_exception";
+
+        /**
+         * The MIME type of a {@link #CONTENT_URI} subdirectory of an aggregation exception
+         */
+        public static final String CONTENT_ITEM_TYPE =
+                "vnd.android.cursor.item/aggregation_exception";
+
+        /**
+         * The type of exception: {@link #TYPE_KEEP_IN}, {@link #TYPE_KEEP_OUT} or
+         * {@link #TYPE_AUTOMATIC}.
+         *
+         * <P>Type: INTEGER</P>
+         */
+        public static final String TYPE = "type";
+
+        /**
+         * Allows the provider to automatically decide whether the aggregate should include
+         * a particular contact or not.
+         */
+        public static final int TYPE_AUTOMATIC = 0;
+
+        /**
+         * Makes sure that the specified contact is included in the specified aggregate.
+         */
+        public static final int TYPE_KEEP_IN = 1;
+
+        /**
+         * Makes sure that the specified contact is NOT included in the specified aggregate.
+         */
+        public static final int TYPE_KEEP_OUT = 2;
+
+        /**
+         * A reference to the {@link Aggregates#_ID} of the aggregate that the rule applies to.
+         */
+        public static final String AGGREGATE_ID = "aggregate_id";
+
+        /**
+         * A reference to the {@link android.provider.ContactsContract.Contacts#_ID} of the
+         * contact that the rule applies to.
+         */
+        public static final String CONTACT_ID = "contact_id";
+    }
+
+    /**
+     * Contains helper classes used to create or manage {@link android.content.Intent Intents}
+     * that involve contacts.
+     */
+    public static final class Intents {
+        /**
+         * This is the intent that is fired when a search suggestion is clicked on.
+         */
+        public static final String SEARCH_SUGGESTION_CLICKED =
+                "android.provider.Contacts.SEARCH_SUGGESTION_CLICKED";
+
+        /**
+         * This is the intent that is fired when a search suggestion for dialing a number
+         * is clicked on.
+         */
+        public static final String SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED =
+                "android.provider.Contacts.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED";
+
+        /**
+         * This is the intent that is fired when a search suggestion for creating a contact
+         * is clicked on.
+         */
+        public static final String SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED =
+                "android.provider.Contacts.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED";
+
+        /**
+         * Starts an Activity that lets the user pick a contact to attach an image to.
+         * After picking the contact it launches the image cropper in face detection mode.
+         */
+        public static final String ATTACH_IMAGE =
+                "com.android.contacts.action.ATTACH_IMAGE";
+
+        /**
+         * Takes as input a data URI with a mailto: or tel: scheme. If a single
+         * contact exists with the given data it will be shown. If no contact
+         * exists, a dialog will ask the user if they want to create a new
+         * contact with the provided details filled in. If multiple contacts
+         * share the data the user will be prompted to pick which contact they
+         * want to view.
+         * <p>
+         * For <code>mailto:</code> URIs, the scheme specific portion must be a
+         * raw email address, such as one built using
+         * {@link Uri#fromParts(String, String, String)}.
+         * <p>
+         * For <code>tel:</code> URIs, the scheme specific portion is compared
+         * to existing numbers using the standard caller ID lookup algorithm.
+         * The number must be properly encoded, for example using
+         * {@link Uri#fromParts(String, String, String)}.
+         * <p>
+         * Any extras from the {@link Insert} class will be passed along to the
+         * create activity if there are no contacts to show.
+         * <p>
+         * Passing true for the {@link #EXTRA_FORCE_CREATE} extra will skip
+         * prompting the user when the contact doesn't exist.
+         */
+        public static final String SHOW_OR_CREATE_CONTACT =
+                "com.android.contacts.action.SHOW_OR_CREATE_CONTACT";
+
+        /**
+         * Used with {@link #SHOW_OR_CREATE_CONTACT} to force creating a new
+         * contact if no matching contact found. Otherwise, default behavior is
+         * to prompt user with dialog before creating.
+         * <p>
+         * Type: BOOLEAN
+         */
+        public static final String EXTRA_FORCE_CREATE =
+                "com.android.contacts.action.FORCE_CREATE";
+
+        /**
+         * Used with {@link #SHOW_OR_CREATE_CONTACT} to specify an exact
+         * description to be shown when prompting user about creating a new
+         * contact.
+         * <p>
+         * Type: STRING
+         */
+        public static final String EXTRA_CREATE_DESCRIPTION =
+            "com.android.contacts.action.CREATE_DESCRIPTION";
+
+        /**
+         * Intents related to the Contacts app UI.
+         */
+        public static final class UI {
+            /**
+             * The action for the default contacts list tab.
+             */
+            public static final String LIST_DEFAULT =
+                    "com.android.contacts.action.LIST_DEFAULT";
+
+            /**
+             * The action for the contacts list tab.
+             */
+            public static final String LIST_GROUP_ACTION =
+                    "com.android.contacts.action.LIST_GROUP";
+
+            /**
+             * When in LIST_GROUP_ACTION mode, this is the group to display.
+             */
+            public static final String GROUP_NAME_EXTRA_KEY = "com.android.contacts.extra.GROUP";
+
+            /**
+             * The action for the all contacts list tab.
+             */
+            public static final String LIST_ALL_CONTACTS_ACTION =
+                    "com.android.contacts.action.LIST_ALL_CONTACTS";
+
+            /**
+             * The action for the contacts with phone numbers list tab.
+             */
+            public static final String LIST_CONTACTS_WITH_PHONES_ACTION =
+                    "com.android.contacts.action.LIST_CONTACTS_WITH_PHONES";
+
+            /**
+             * The action for the starred contacts list tab.
+             */
+            public static final String LIST_STARRED_ACTION =
+                    "com.android.contacts.action.LIST_STARRED";
+
+            /**
+             * The action for the frequent contacts list tab.
+             */
+            public static final String LIST_FREQUENT_ACTION =
+                    "com.android.contacts.action.LIST_FREQUENT";
+
+            /**
+             * The action for the "strequent" contacts list tab. It first lists the starred
+             * contacts in alphabetical order and then the frequent contacts in descending
+             * order of the number of times they have been contacted.
+             */
+            public static final String LIST_STREQUENT_ACTION =
+                    "com.android.contacts.action.LIST_STREQUENT";
+
+            /**
+             * A key for to be used as an intent extra to set the activity
+             * title to a custom String value.
+             */
+            public static final String TITLE_EXTRA_KEY =
+                "com.android.contacts.extra.TITLE_EXTRA";
+
+            /**
+             * Activity Action: Display a filtered list of contacts
+             * <p>
+             * Input: Extra field {@link #FILTER_TEXT_EXTRA_KEY} is the text to use for
+             * filtering
+             * <p>
+             * Output: Nothing.
+             */
+            public static final String FILTER_CONTACTS_ACTION =
+                "com.android.contacts.action.FILTER_CONTACTS";
+
+            /**
+             * Used as an int extra field in {@link #FILTER_CONTACTS_ACTION}
+             * intents to supply the text on which to filter.
+             */
+            public static final String FILTER_TEXT_EXTRA_KEY =
+                "com.android.contacts.extra.FILTER_TEXT";
+        }
+
+        /**
+         * Convenience class that contains string constants used
+         * to create contact {@link android.content.Intent Intents}.
+         */
+        public static final class Insert {
+            /** The action code to use when adding a contact */
+            public static final String ACTION = Intent.ACTION_INSERT;
+
+            /**
+             * If present, forces a bypass of quick insert mode.
+             */
+            public static final String FULL_MODE = "full_mode";
+
+            /**
+             * The extra field for the contact name.
+             * <P>Type: String</P>
+             */
+            public static final String NAME = "name";
+
+            // TODO add structured name values here.
+
+            /**
+             * The extra field for the contact phonetic name.
+             * <P>Type: String</P>
+             */
+            public static final String PHONETIC_NAME = "phonetic_name";
+
+            /**
+             * The extra field for the contact company.
+             * <P>Type: String</P>
+             */
+            public static final String COMPANY = "company";
+
+            /**
+             * The extra field for the contact job title.
+             * <P>Type: String</P>
+             */
+            public static final String JOB_TITLE = "job_title";
+
+            /**
+             * The extra field for the contact notes.
+             * <P>Type: String</P>
+             */
+            public static final String NOTES = "notes";
+
+            /**
+             * The extra field for the contact phone number.
+             * <P>Type: String</P>
+             */
+            public static final String PHONE = "phone";
+
+            /**
+             * The extra field for the contact phone number type.
+             * <P>Type: Either an integer value from
+             * {@link android.provider.Contacts.PhonesColumns PhonesColumns},
+             *  or a string specifying a custom label.</P>
+             */
+            public static final String PHONE_TYPE = "phone_type";
+
+            /**
+             * The extra field for the phone isprimary flag.
+             * <P>Type: boolean</P>
+             */
+            public static final String PHONE_ISPRIMARY = "phone_isprimary";
+
+            /**
+             * The extra field for an optional second contact phone number.
+             * <P>Type: String</P>
+             */
+            public static final String SECONDARY_PHONE = "secondary_phone";
+
+            /**
+             * The extra field for an optional second contact phone number type.
+             * <P>Type: Either an integer value from
+             * {@link android.provider.Contacts.PhonesColumns PhonesColumns},
+             *  or a string specifying a custom label.</P>
+             */
+            public static final String SECONDARY_PHONE_TYPE = "secondary_phone_type";
+
+            /**
+             * The extra field for an optional third contact phone number.
+             * <P>Type: String</P>
+             */
+            public static final String TERTIARY_PHONE = "tertiary_phone";
+
+            /**
+             * The extra field for an optional third contact phone number type.
+             * <P>Type: Either an integer value from
+             * {@link android.provider.Contacts.PhonesColumns PhonesColumns},
+             *  or a string specifying a custom label.</P>
+             */
+            public static final String TERTIARY_PHONE_TYPE = "tertiary_phone_type";
+
+            /**
+             * The extra field for the contact email address.
+             * <P>Type: String</P>
+             */
+            public static final String EMAIL = "email";
+
+            /**
+             * The extra field for the contact email type.
+             * <P>Type: Either an integer value from
+             * {@link android.provider.Contacts.ContactMethodsColumns ContactMethodsColumns}
+             *  or a string specifying a custom label.</P>
+             */
+            public static final String EMAIL_TYPE = "email_type";
+
+            /**
+             * The extra field for the email isprimary flag.
+             * <P>Type: boolean</P>
+             */
+            public static final String EMAIL_ISPRIMARY = "email_isprimary";
+
+            /**
+             * The extra field for an optional second contact email address.
+             * <P>Type: String</P>
+             */
+            public static final String SECONDARY_EMAIL = "secondary_email";
+
+            /**
+             * The extra field for an optional second contact email type.
+             * <P>Type: Either an integer value from
+             * {@link android.provider.Contacts.ContactMethodsColumns ContactMethodsColumns}
+             *  or a string specifying a custom label.</P>
+             */
+            public static final String SECONDARY_EMAIL_TYPE = "secondary_email_type";
+
+            /**
+             * The extra field for an optional third contact email address.
+             * <P>Type: String</P>
+             */
+            public static final String TERTIARY_EMAIL = "tertiary_email";
+
+            /**
+             * The extra field for an optional third contact email type.
+             * <P>Type: Either an integer value from
+             * {@link android.provider.Contacts.ContactMethodsColumns ContactMethodsColumns}
+             *  or a string specifying a custom label.</P>
+             */
+            public static final String TERTIARY_EMAIL_TYPE = "tertiary_email_type";
+
+            /**
+             * The extra field for the contact postal address.
+             * <P>Type: String</P>
+             */
+            public static final String POSTAL = "postal";
+
+            /**
+             * The extra field for the contact postal address type.
+             * <P>Type: Either an integer value from
+             * {@link android.provider.Contacts.ContactMethodsColumns ContactMethodsColumns}
+             *  or a string specifying a custom label.</P>
+             */
+            public static final String POSTAL_TYPE = "postal_type";
+
+            /**
+             * The extra field for the postal isprimary flag.
+             * <P>Type: boolean</P>
+             */
+            public static final String POSTAL_ISPRIMARY = "postal_isprimary";
+
+            /**
+             * The extra field for an IM handle.
+             * <P>Type: String</P>
+             */
+            public static final String IM_HANDLE = "im_handle";
+
+            /**
+             * The extra field for the IM protocol
+             * <P>Type: the result of {@link CommonDataKinds.Im#encodePredefinedImProtocol(int)}
+             * or {@link CommonDataKinds.Im#encodeCustomImProtocol(String)}.</P>
+             */
+            public static final String IM_PROTOCOL = "im_protocol";
+
+            /**
+             * The extra field for the IM isprimary flag.
+             * <P>Type: boolean</P>
+             */
+            public static final String IM_ISPRIMARY = "im_isprimary";
+        }
+    }
+
+}
diff --git a/core/java/android/provider/Downloads.java b/core/java/android/provider/Downloads.java
index 4c58e0d..790fe5c 100644
--- a/core/java/android/provider/Downloads.java
+++ b/core/java/android/provider/Downloads.java
@@ -63,7 +63,7 @@
      * that had initiated a download when that download completes. The
      * download's content: uri is specified in the intent's data.
      */
-    public static final String DOWNLOAD_COMPLETED_ACTION =
+    public static final String ACTION_DOWNLOAD_COMPLETED =
             "android.intent.action.DOWNLOAD_COMPLETED";
 
     /**
@@ -76,7 +76,7 @@
      * Note: this is not currently sent for downloads that have completed
      * successfully.
      */
-    public static final String NOTIFICATION_CLICKED_ACTION =
+    public static final String ACTION_NOTIFICATION_CLICKED =
             "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
 
     /**
@@ -84,14 +84,14 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init/Read</P>
      */
-    public static final String URI = "uri";
+    public static final String COLUMN_URI = "uri";
 
     /**
      * The name of the column containing application-specific data.
      * <P>Type: TEXT</P>
      * <P>Owner can Init/Read/Write</P>
      */
-    public static final String APP_DATA = "entity";
+    public static final String COLUMN_APP_DATA = "entity";
 
     /**
      * The name of the column containing the flags that indicates whether
@@ -104,7 +104,7 @@
      * <P>Type: BOOLEAN</P>
      * <P>Owner can Init</P>
      */
-    public static final String NO_INTEGRITY = "no_integrity";
+    public static final String COLUMN_NO_INTEGRITY = "no_integrity";
 
     /**
      * The name of the column containing the filename that the initiating
@@ -113,7 +113,7 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init</P>
      */
-    public static final String FILENAME_HINT = "hint";
+    public static final String COLUMN_FILE_NAME_HINT = "hint";
 
     /**
      * The name of the column containing the filename where the downloaded data
@@ -128,7 +128,7 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init/Read</P>
      */
-    public static final String MIMETYPE = "mimetype";
+    public static final String COLUMN_MIME_TYPE = "mimetype";
 
     /**
      * The name of the column containing the flag that controls the destination
@@ -136,7 +136,7 @@
      * <P>Type: INTEGER</P>
      * <P>Owner can Init</P>
      */
-    public static final String DESTINATION = "destination";
+    public static final String COLUMN_DESTINATION = "destination";
 
     /**
      * The name of the column containing the flags that controls whether the
@@ -145,7 +145,7 @@
      * <P>Type: INTEGER</P>
      * <P>Owner can Init/Read/Write</P>
      */
-    public static final String VISIBILITY = "visibility";
+    public static final String COLUMN_VISIBILITY = "visibility";
 
     /**
      * The name of the column containing the current control state  of the download.
@@ -154,7 +154,7 @@
      * <P>Type: INTEGER</P>
      * <P>Owner can Read</P>
      */
-    public static final String CONTROL = "control";
+    public static final String COLUMN_CONTROL = "control";
 
     /**
      * The name of the column containing the current status of the download.
@@ -163,7 +163,7 @@
      * <P>Type: INTEGER</P>
      * <P>Owner can Read</P>
      */
-    public static final String STATUS = "status";
+    public static final String COLUMN_STATUS = "status";
 
     /**
      * The name of the column containing the date at which some interesting
@@ -172,7 +172,7 @@
      * <P>Type: BIGINT</P>
      * <P>Owner can Read</P>
      */
-    public static final String LAST_MODIFICATION = "lastmod";
+    public static final String COLUMN_LAST_MODIFICATION = "lastmod";
 
     /**
      * The name of the column containing the package name of the application
@@ -181,7 +181,7 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init/Read</P>
      */
-    public static final String NOTIFICATION_PACKAGE = "notificationpackage";
+    public static final String COLUMN_NOTIFICATION_PACKAGE = "notificationpackage";
 
     /**
      * The name of the column containing the component name of the class that
@@ -191,7 +191,7 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init/Read</P>
      */
-    public static final String NOTIFICATION_CLASS = "notificationclass";
+    public static final String COLUMN_NOTIFICATION_CLASS = "notificationclass";
 
     /**
      * If extras are specified when requesting a download they will be provided in the intent that
@@ -199,7 +199,7 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init</P>
      */
-    public static final String NOTIFICATION_EXTRAS = "notificationextras";
+    public static final String COLUMN_NOTIFICATION_EXTRAS = "notificationextras";
 
     /**
      * The name of the column contain the values of the cookie to be used for
@@ -208,7 +208,7 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init</P>
      */
-    public static final String COOKIE_DATA = "cookiedata";
+    public static final String COLUMN_COOKIE_DATA = "cookiedata";
 
     /**
      * The name of the column containing the user agent that the initiating
@@ -216,7 +216,7 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init</P>
      */
-    public static final String USER_AGENT = "useragent";
+    public static final String COLUMN_USER_AGENT = "useragent";
 
     /**
      * The name of the column containing the referer (sic) that the initiating
@@ -224,7 +224,7 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init</P>
      */
-    public static final String REFERER = "referer";
+    public static final String COLUMN_REFERER = "referer";
 
     /**
      * The name of the column containing the total size of the file being
@@ -232,7 +232,7 @@
      * <P>Type: INTEGER</P>
      * <P>Owner can Read</P>
      */
-    public static final String TOTAL_BYTES = "total_bytes";
+    public static final String COLUMN_TOTAL_BYTES = "total_bytes";
 
     /**
      * The name of the column containing the size of the part of the file that
@@ -240,7 +240,7 @@
      * <P>Type: INTEGER</P>
      * <P>Owner can Read</P>
      */
-    public static final String CURRENT_BYTES = "current_bytes";
+    public static final String COLUMN_CURRENT_BYTES = "current_bytes";
 
     /**
      * The name of the column where the initiating application can provide the
@@ -252,7 +252,7 @@
      * <P>Type: INTEGER</P>
      * <P>Owner can Init</P>
      */
-    public static final String OTHER_UID = "otheruid";
+    public static final String COLUMN_OTHER_UID = "otheruid";
 
     /**
      * The name of the column where the initiating application can provided the
@@ -261,7 +261,7 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init/Read/Write</P>
      */
-    public static final String TITLE = "title";
+    public static final String COLUMN_TITLE = "title";
 
     /**
      * The name of the column where the initiating application can provide the
@@ -270,7 +270,7 @@
      * <P>Type: TEXT</P>
      * <P>Owner can Init/Read/Write</P>
      */
-    public static final String DESCRIPTION = "description";
+    public static final String COLUMN_DESCRIPTION = "description";
 
     /*
      * Lists the destinations that an application can specify for a download.
diff --git a/core/java/android/provider/Im.java b/core/java/android/provider/Im.java
index 19ad158..ef4ff51 100644
--- a/core/java/android/provider/Im.java
+++ b/core/java/android/provider/Im.java
@@ -871,14 +871,22 @@
     }
 
     /**
-     * The common columns for both one-to-one chat messages or group chat messages.
+     * The common columns for messages table
      */
-    public interface BaseMessageColumns {
+    public interface MessageColumns {
         /**
-         * The user this message belongs to
-         * <P>Type: TEXT</P>
+         * The thread_id column stores the contact id of the contact the message belongs to.
+         * For groupchat messages, the thread_id stores the group id, which is the contact id
+         * of the temporary group contact created for the groupchat. So there should be no
+         * collision between groupchat message thread id and regular message thread id. 
          */
-        String CONTACT = "contact";
+        String THREAD_ID = "thread_id";
+
+        /**
+         * The nickname. This is used for groupchat messages to indicate the participant's
+         * nickname. For non groupchat messages, this field should be left empty.
+         */
+        String NICKNAME = "nickname";
 
         /**
          * The body
@@ -917,68 +925,193 @@
          * <P>Type: STRING</P>
          */
         String PACKET_ID = "packet_id";
-    }
-
-    /**
-     * Columns from the Messages table.
-     */
-    public interface MessagesColumns extends BaseMessageColumns{
-        /**
-         * The provider id
-         * <P> Type: INTEGER </P>
-         */
-        String PROVIDER = "provider";
 
         /**
-         * The account id
-         * <P> Type: INTEGER </P>
+         * Is groupchat message or not
+         * <P>Type: INTEGER</P>
          */
-        String ACCOUNT = "account";
+        String IS_GROUP_CHAT = "is_muc";
     }
 
     /**
      * This table contains messages.
      */
-    public static final class Messages implements BaseColumns, MessagesColumns {
+    public static final class Messages implements BaseColumns, MessageColumns {
         /**
          * no public constructor since this is a utility class
          */
         private Messages() {}
 
         /**
-         * Gets the Uri to query messages by contact.
+         * Gets the Uri to query messages by thread id.
          *
-         * @param providerId the provider id of the contact.
+         * @param threadId the thread id of the message.
+         * @return the Uri
+         */
+        public static final Uri getContentUriByThreadId(long threadId) {
+            Uri.Builder builder = CONTENT_URI_MESSAGES_BY_THREAD_ID.buildUpon();
+            ContentUris.appendId(builder, threadId);
+            return builder.build();
+        }
+
+        /**
+         * @deprecated
+         *
+         * Gets the Uri to query messages by account and contact.
+         *
          * @param accountId the account id of the contact.
          * @param username the user name of the contact.
          * @return the Uri
          */
-        public static final Uri getContentUriByContact(long providerId,
-                long accountId, String username) {
-            Uri.Builder builder = CONTENT_URI_MESSAGES_BY.buildUpon();
-            ContentUris.appendId(builder, providerId);
+        public static final Uri getContentUriByContact(long accountId, String username) {
+            Uri.Builder builder = CONTENT_URI_MESSAGES_BY_ACCOUNT_AND_CONTACT.buildUpon();
             ContentUris.appendId(builder, accountId);
             builder.appendPath(username);
             return builder.build();
         }
 
         /**
+         * Gets the Uri to query messages by provider.
+         *
+         * @param providerId the service provider id.
+         * @return the Uri
+         */
+        public static final Uri getContentUriByProvider(long providerId) {
+            Uri.Builder builder = CONTENT_URI_MESSAGES_BY_PROVIDER.buildUpon();
+            ContentUris.appendId(builder, providerId);
+            return builder.build();
+        }
+
+        /**
+         * Gets the Uri to query off the record messages by account.
+         *
+         * @param accountId the account id.
+         * @return the Uri
+         */
+        public static final Uri getContentUriByAccount(long accountId) {
+            Uri.Builder builder = CONTENT_URI_BY_ACCOUNT.buildUpon();
+            ContentUris.appendId(builder, accountId);
+            return builder.build();
+        }
+
+        /**
+         * Gets the Uri to query off the record messages by thread id.
+         *
+         * @param threadId the thread id of the message.
+         * @return the Uri
+         */
+        public static final Uri getOtrMessagesContentUriByThreadId(long threadId) {
+            Uri.Builder builder = OTR_MESSAGES_CONTENT_URI_BY_THREAD_ID.buildUpon();
+            ContentUris.appendId(builder, threadId);
+            return builder.build();
+        }
+
+        /**
+         * @deprecated
+         *
+         * Gets the Uri to query off the record messages by account and contact.
+         *
+         * @param accountId the account id of the contact.
+         * @param username the user name of the contact.
+         * @return the Uri
+         */
+        public static final Uri getOtrMessagesContentUriByContact(long accountId, String username) {
+            Uri.Builder builder = OTR_MESSAGES_CONTENT_URI_BY_ACCOUNT_AND_CONTACT.buildUpon();
+            ContentUris.appendId(builder, accountId);
+            builder.appendPath(username);
+            return builder.build();
+        }
+
+        /**
+         * Gets the Uri to query off the record messages by provider.
+         *
+         * @param providerId the service provider id.
+         * @return the Uri
+         */
+        public static final Uri getOtrMessagesContentUriByProvider(long providerId) {
+            Uri.Builder builder = OTR_MESSAGES_CONTENT_URI_BY_PROVIDER.buildUpon();
+            ContentUris.appendId(builder, providerId);
+            return builder.build();
+        }
+
+        /**
+         * Gets the Uri to query off the record messages by account.
+         *
+         * @param accountId the account id.
+         * @return the Uri
+         */
+        public static final Uri getOtrMessagesContentUriByAccount(long accountId) {
+            Uri.Builder builder = OTR_MESSAGES_CONTENT_URI_BY_ACCOUNT.buildUpon();
+            ContentUris.appendId(builder, accountId);
+            return builder.build();
+        }
+
+        /**
          * The content:// style URL for this table
          */
         public static final Uri CONTENT_URI =
-            Uri.parse("content://im/messages");
+                Uri.parse("content://im/messages");
 
         /**
-         * The content:// style URL for messages by provider and account
+         * The content:// style URL for messages by thread id
          */
-        public static final Uri CONTENT_URI_MESSAGES_BY =
-            Uri.parse("content://im/messagesBy");
+        public static final Uri CONTENT_URI_MESSAGES_BY_THREAD_ID =
+                Uri.parse("content://im/messagesByThreadId");
+
+        /**
+         * The content:// style URL for messages by account and contact
+         */
+        public static final Uri CONTENT_URI_MESSAGES_BY_ACCOUNT_AND_CONTACT =
+                Uri.parse("content://im/messagesByAcctAndContact");
+
+        /**
+         * The content:// style URL for messages by provider
+         */
+        public static final Uri CONTENT_URI_MESSAGES_BY_PROVIDER =
+                Uri.parse("content://im/messagesByProvider");
+
+        /**
+         * The content:// style URL for messages by account
+         */
+        public static final Uri CONTENT_URI_BY_ACCOUNT =
+                Uri.parse("content://im/messagesByAccount");
+
+        /**
+         * The content:// style url for off the record messages
+         */
+        public static final Uri OTR_MESSAGES_CONTENT_URI =
+                Uri.parse("content://im/otrMessages");
+
+        /**
+         * The content:// style url for off the record messages by thread id
+         */
+        public static final Uri OTR_MESSAGES_CONTENT_URI_BY_THREAD_ID =
+                Uri.parse("content://im/otrMessagesByThreadId");
+
+        /**
+         * The content:// style url for off the record messages by account and contact
+         */
+        public static final Uri OTR_MESSAGES_CONTENT_URI_BY_ACCOUNT_AND_CONTACT =
+                Uri.parse("content://im/otrMessagesByAcctAndContact");
+
+        /**
+         * The content:// style URL for off the record messages by provider
+         */
+        public static final Uri OTR_MESSAGES_CONTENT_URI_BY_PROVIDER =
+                Uri.parse("content://im/otrMessagesByProvider");
+
+        /**
+         * The content:// style URL for off the record messages by account
+         */
+        public static final Uri OTR_MESSAGES_CONTENT_URI_BY_ACCOUNT =
+                Uri.parse("content://im/otrMessagesByAccount");
 
         /**
          * The MIME type of {@link #CONTENT_URI} providing a directory of
          * people.
          */
-        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/im-messages";
+        public static final String CONTENT_TYPE =
+                "vnd.android.cursor.dir/im-messages";
 
         /**
          * The MIME type of a {@link #CONTENT_URI} subdirectory of a single
@@ -992,6 +1125,11 @@
          */
         public static final String DEFAULT_SORT_ORDER = "date ASC";
 
+        /**
+         * The "contact" column. This is not a real column in the messages table, but a
+         * temoprary column created when querying for messages (joined with the contacts table)
+         */
+        public static final String CONTACT = "contact";
     }
 
     /**
@@ -1119,67 +1257,6 @@
     }
 
     /**
-     * Columns from the GroupMessages table
-     */
-    public interface GroupMessageColumns extends BaseMessageColumns {
-        /**
-         * The group this message belongs to
-         * <p>Type: TEXT</p>
-         */
-        String GROUP = "groupId";
-    }
-
-    /**
-     * This table contains group messages.
-     */
-    public final static class GroupMessages implements BaseColumns,
-            GroupMessageColumns {
-        private GroupMessages() {}
-
-        /**
-         * Gets the Uri to query group messages by group.
-         *
-         * @param groupId the group id.
-         * @return the Uri
-         */
-        public static final Uri getContentUriByGroup(long groupId) {
-            Uri.Builder builder = CONTENT_URI_GROUP_MESSAGES_BY.buildUpon();
-            ContentUris.appendId(builder, groupId);
-            return builder.build();
-        }
-
-        /**
-         * The content:// style URL for this table
-         */
-        public static final Uri CONTENT_URI =
-            Uri.parse("content://im/groupMessages");
-
-        /**
-         * The content:// style URL for group messages by provider and account
-         */
-        public static final Uri CONTENT_URI_GROUP_MESSAGES_BY =
-            Uri.parse("content://im/groupMessagesBy");
-
-        /**
-         * The MIME type of {@link #CONTENT_URI} providing a directory of
-         * group messages.
-         */
-        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/im-groupMessages";
-
-        /**
-         * The MIME type of a {@link #CONTENT_URI} subdirectory of a single
-         * group message.
-         */
-        public static final String CONTENT_ITEM_TYPE =
-                "vnd.android.cursor.item/im-groupMessages";
-
-        /**
-         * The default sort order for this table
-         */
-        public static final String DEFAULT_SORT_ORDER = "date ASC";
-    }
-
-    /**
      * Columns from the Avatars table
      */
     public interface AvatarsColumns {
@@ -1534,6 +1611,9 @@
         /** specifies whether or not to show mobile indicator to friends */
         public static final String SETTING_SHOW_MOBILE_INDICATOR = "mobile_indicator";
 
+        /** specifies whether or not to show as away when device is idle */
+        public static final String SETTING_SHOW_AWAY_ON_IDLE = "show_away_on_idle";
+
         /**
          * Used for reliable message queue (RMQ). This is for storing the last rmq id received
          * from the GTalk server
@@ -1742,6 +1822,17 @@
                     showMobileIndicator);
         }
 
+        /**
+         * A convenience method to set whether or not to show as away when device is idle.
+         *
+         * @param contentResolver The ContentResolver to use to access the setting table.
+         * @param showAway Whether or not to show as away when device is idle.
+         */
+        public static void setShowAwayOnIdle(ContentResolver contentResolver,
+                long providerId, boolean showAway) {
+            putBooleanValue(contentResolver, providerId, SETTING_SHOW_AWAY_ON_IDLE, showAway);
+        }
+
         public static class QueryMap extends ContentQueryMap {
             private ContentResolver mContentResolver;
             private long mProviderId;
@@ -1872,6 +1963,25 @@
             }
 
             /**
+             * Set whether or not to show as away when device is idle.
+             *
+             * @param showAway whether or not to show as away when device is idle.
+             */
+            public void setShowAwayOnIdle(boolean showAway) {
+                ProviderSettings.setShowAwayOnIdle(mContentResolver, mProviderId, showAway);
+            }
+
+            /**
+             * Get whether or not to show as away when device is idle.
+             *
+             * @return Whether or not to show as away when device is idle.
+             */
+            public boolean getShowAwayOnIdle() {
+                return getBoolean(SETTING_SHOW_AWAY_ON_IDLE,
+                        true /* by default show as away on idle*/);
+            }
+
+            /**
              * Convenience function for retrieving a single settings value
              * as a boolean.
              *
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 9a9ddc9..0c2b65e 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -1182,6 +1182,22 @@
         public static final Uri DEFAULT_NOTIFICATION_URI = getUriFor(NOTIFICATION_SOUND);
 
         /**
+         * Persistent store for the system-wide default alarm alert.
+         *
+         * @see #RINGTONE
+         * @see #DEFAULT_ALARM_ALERT_URI
+         */
+        public static final String ALARM_ALERT = "alarm_alert";
+
+        /**
+         * A {@link Uri} that will point to the current default alarm alert at
+         * any given time.
+         *
+         * @see #DEFAULT_ALARM_ALERT_URI
+         */
+        public static final Uri DEFAULT_ALARM_ALERT_URI = getUriFor(ALARM_ALERT);
+
+        /**
          * Setting to enable Auto Replace (AutoText) in text editors. 1 = On, 0 = Off
          */
         public static final String TEXT_AUTO_REPLACE = "auto_replace";
@@ -1968,6 +1984,12 @@
         public static final String LOCATION_PROVIDERS_ALLOWED = "location_providers_allowed";
 
         /**
+         * Whether assisted GPS should be enabled or not.
+         * @hide
+         */
+        public static final String ASSISTED_GPS_ENABLED = "assisted_gps_enabled";
+
+        /**
          * The Logging ID (a unique 64-bit value) as a hex string.
          * Used as a pseudonymous identifier for logging.
          * @deprecated This identifier is poorly initialized and has
@@ -2804,6 +2826,12 @@
                 "gtalk_nosync_heartbeat_ping_interval_ms";
 
         /**
+         * The maximum heartbeat interval used while on the WIFI network.
+         */
+        public static final String GTALK_SERVICE_WIFI_MAX_HEARTBEAT_INTERVAL_MS =
+                "gtalk_wifi_max_heartbeat_ping_interval_ms";
+
+        /**
          * How long we wait to receive a heartbeat ping acknowledgement (or another packet)
          * from the GTalk server, before deeming the connection dead.
          */
@@ -2856,6 +2884,52 @@
         public static final String GTALK_USE_BARE_JID_TIMEOUT_MS = "gtalk_use_barejid_timeout_ms";
 
         /**
+         * This is the threshold of retry number when there is an authentication expired failure
+         * for Google Talk. In some situation, e.g. when a Google Apps account is disabled chat
+         * service, the connection keeps failing. This threshold controls when we should stop
+         * the retrying.
+         */
+        public static final String GTALK_MAX_RETRIES_FOR_AUTH_EXPIRED =
+            "gtalk_max_retries_for_auth_expired";
+
+        /**
+         * This is the url for getting the app token for server-to-device push messaging.
+         */
+        public static final String PUSH_MESSAGING_REGISTRATION_URL =
+                "push_messaging_registration_url";
+
+        /**
+         * This is gdata url to lookup album and picture info from picasa web.
+         */
+        public static final String GTALK_PICASA_ALBUM_URL =
+            "gtalk_picasa_album_url";
+
+        /**
+         * This is the url to lookup picture info from flickr.
+         */
+        public static final String GTALK_FLICKR_PHOTO_INFO_URL =
+            "gtalk_flickr_photo_info_url";
+
+        /**
+         * This is the url to lookup an actual picture from flickr.
+         */
+        public static final String GTALK_FLICKR_PHOTO_URL =
+            "gtalk_flickr_photo_url";
+
+        /**
+         * This is the gdata url to lookup info on a youtube video.
+         */
+        public static final String GTALK_YOUTUBE_VIDEO_URL =
+            "gtalk_youtube_video_url";
+
+
+        /**
+         * This is the url for getting the app token for server-to-device data messaging.
+         */
+        public static final String DATA_MESSAGE_GET_APP_TOKEN_URL =
+                "data_messaging_get_app_token_url";
+
+        /**
          * Enable use of ssl session caching.
          * 'db' - save each session in a (per process) database
          * 'file' - save each session in a (per process) file
diff --git a/core/java/android/provider/SocialContract.java b/core/java/android/provider/SocialContract.java
new file mode 100644
index 0000000..a3b1d6e
--- /dev/null
+++ b/core/java/android/provider/SocialContract.java
@@ -0,0 +1,187 @@
+/*
+ * 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
+ */
+
+package android.provider;
+
+import android.content.res.Resources;
+import android.graphics.BitmapFactory;
+import android.net.Uri;
+import android.provider.ContactsContract.Aggregates;
+import android.provider.ContactsContract.Data;
+
+/**
+ * The contract between the social provider and applications. Contains
+ * definitions for the supported URIs and columns.
+ *
+ * @hide
+ */
+public class SocialContract {
+    /** The authority for the social provider */
+    public static final String AUTHORITY = "com.android.social";
+
+    /** A content:// style uri to the authority for the contacts provider */
+    public static final Uri AUTHORITY_URI = Uri.parse("content://" + AUTHORITY);
+
+    private interface ActivitiesColumns {
+        /**
+         * The package name to use when creating {@link Resources} objects for
+         * this data row. This value is only designed for use when building user
+         * interfaces, and should not be used to infer the owner.
+         * <p>
+         * Type: TEXT
+         */
+        public static final String RES_PACKAGE = "res_package";
+
+        /**
+         * The mime-type of this social activity.
+         * <p>
+         * Type: TEXT
+         */
+        public static final String MIMETYPE = "mimetype";
+
+        /**
+         * Internal raw identifier for this social activity. This field is
+         * analogous to the <code>atom:id</code> element defined in RFC 4287.
+         * <p>
+         * Type: TEXT
+         */
+        public static final String RAW_ID = "raw_id";
+
+        /**
+         * Reference to another {@link Activities#RAW_ID} that this social activity
+         * is replying to. This field is analogous to the
+         * <code>thr:in-reply-to</code> element defined in RFC 4685.
+         * <p>
+         * Type: TEXT
+         */
+        public static final String IN_REPLY_TO = "in_reply_to";
+
+        /**
+         * Reference to the {@link android.provider.ContactsContract.Contacts#_ID} that authored
+         * this social activity. This field is analogous to the <code>atom:author</code>
+         * element defined in RFC 4287.
+         * <p>
+         * Type: INTEGER
+         */
+        public static final String AUTHOR_CONTACT_ID = "author_contact_id";
+
+        /**
+         * Optional reference to the {@link android.provider.ContactsContract.Contacts#_ID} this
+         * social activity is targeted towards. If more than one direct target, this field may
+         * be left undefined. This field is analogous to the
+         * <code>activity:target</code> element defined in the Atom Activity
+         * Extensions Internet-Draft.
+         * <p>
+         * Type: INTEGER
+         */
+        public static final String TARGET_CONTACT_ID = "target_contact_id";
+
+        /**
+         * Timestamp when this social activity was published, in a
+         * {@link System#currentTimeMillis()} time base. This field is analogous
+         * to the <code>atom:published</code> element defined in RFC 4287.
+         * <p>
+         * Type: INTEGER
+         */
+        public static final String PUBLISHED = "published";
+
+        /**
+         * Timestamp when the original social activity in a thread was
+         * published. For activities that have an in-reply-to field specified, the
+         * content provider will automatically populate this field with the
+         * timestamp of the original activity.
+         * <p>
+         * This field is useful for sorting order of activities that keeps together all
+         * messages in each thread.
+         * <p>
+         * Type: INTEGER
+         */
+        public static final String THREAD_PUBLISHED = "thread_published";
+
+        /**
+         * Title of this social activity. This field is analogous to the
+         * <code>atom:title</code> element defined in RFC 4287.
+         * <p>
+         * Type: TEXT
+         */
+        public static final String TITLE = "title";
+
+        /**
+         * Summary of this social activity. This field is analogous to the
+         * <code>atom:summary</code> element defined in RFC 4287.
+         * <p>
+         * Type: TEXT
+         */
+        public static final String SUMMARY = "summary";
+
+        /**
+         * A URI associated this social activity. This field is analogous to the
+         * <code>atom:link rel="alternate"</code> element defined in RFC 4287.
+         * <p>
+         * Type: TEXT
+         */
+        public static final String LINK = "link";
+
+        /**
+         * Optional thumbnail specific to this social activity. This is the raw
+         * bytes of an image that could be inflated using {@link BitmapFactory}.
+         * <p>
+         * Type: BLOB
+         */
+        public static final String THUMBNAIL = "thumbnail";
+    }
+
+    public static final class Activities implements BaseColumns, ActivitiesColumns {
+        /**
+         * This utility class cannot be instantiated
+         */
+        private Activities() {
+        }
+
+        /**
+         * The content:// style URI for this table
+         */
+        public static final Uri CONTENT_URI = Uri.withAppendedPath(AUTHORITY_URI, "activities");
+
+        /**
+         * The content:// URI for this table filtered to the set of social activities
+         * authored by a specific {@link android.provider.ContactsContract.Contacts#_ID}.
+         */
+        public static final Uri CONTENT_AUTHORED_BY_URI =
+            Uri.withAppendedPath(CONTENT_URI, "authored_by");
+
+        /**
+         * The {@link Uri} for the latest social activity performed by any
+         * contact aggregated under the specified {@link Aggregates#_ID}. Will
+         * also join with most-present {@link Presence} for this aggregate.
+         */
+        public static final Uri CONTENT_AGGREGATE_STATUS_URI =
+            Uri.withAppendedPath(AUTHORITY_URI, "aggregate_status");
+
+        /**
+         * The MIME type of {@link #CONTENT_URI} providing a directory of social
+         * activities.
+         */
+        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/activity";
+
+        /**
+         * The MIME type of a {@link #CONTENT_URI} subdirectory of a single
+         * social activity.
+         */
+        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/activity";
+    }
+
+}
diff --git a/core/java/android/provider/SubscribedFeeds.java b/core/java/android/provider/SubscribedFeeds.java
index 4d430d5..f94b442 100644
--- a/core/java/android/provider/SubscribedFeeds.java
+++ b/core/java/android/provider/SubscribedFeeds.java
@@ -20,6 +20,7 @@
 import android.content.ContentValues;
 import android.database.Cursor;
 import android.net.Uri;
+import android.accounts.Account;
 
 /**
  * The SubscribedFeeds provider stores all information about subscribed feeds.
@@ -99,7 +100,7 @@
         /**
          * The default sort order for this table
          */
-        public static final String DEFAULT_SORT_ORDER = "_SYNC_ACCOUNT ASC";
+        public static final String DEFAULT_SORT_ORDER = "_SYNC_ACCOUNT_TYPE, _SYNC_ACCOUNT ASC";
     }
 
     /**
@@ -114,38 +115,36 @@
      * @return  the Uri of the feed that was added
      */
     public static Uri addFeed(ContentResolver resolver,
-            String feed, String account,
+            String feed, Account account,
             String authority, String service) {
         ContentValues values = new ContentValues();
         values.put(SubscribedFeeds.Feeds.FEED, feed);
-        values.put(SubscribedFeeds.Feeds._SYNC_ACCOUNT, account);
+        values.put(SubscribedFeeds.Feeds._SYNC_ACCOUNT, account.mName);
+        values.put(SubscribedFeeds.Feeds._SYNC_ACCOUNT_TYPE, account.mType);
         values.put(SubscribedFeeds.Feeds.AUTHORITY, authority);
         values.put(SubscribedFeeds.Feeds.SERVICE, service);
         return resolver.insert(SubscribedFeeds.Feeds.CONTENT_URI, values);
     }
 
     public static int deleteFeed(ContentResolver resolver,
-            String feed, String account, String authority) {
+            String feed, Account account, String authority) {
         StringBuilder where = new StringBuilder();
         where.append(SubscribedFeeds.Feeds._SYNC_ACCOUNT + "=?");
+        where.append(" AND " + SubscribedFeeds.Feeds._SYNC_ACCOUNT_TYPE + "=?");
         where.append(" AND " + SubscribedFeeds.Feeds.FEED + "=?");
         where.append(" AND " + SubscribedFeeds.Feeds.AUTHORITY + "=?");
         return resolver.delete(SubscribedFeeds.Feeds.CONTENT_URI,
-                where.toString(), new String[] {account, feed, authority});
+                where.toString(), new String[] {account.mName, account.mType, feed, authority});
     }
 
     public static int deleteFeeds(ContentResolver resolver,
-            String account, String authority) {
+            Account account, String authority) {
         StringBuilder where = new StringBuilder();
         where.append(SubscribedFeeds.Feeds._SYNC_ACCOUNT + "=?");
+        where.append(" AND " + SubscribedFeeds.Feeds._SYNC_ACCOUNT_TYPE + "=?");
         where.append(" AND " + SubscribedFeeds.Feeds.AUTHORITY + "=?");
         return resolver.delete(SubscribedFeeds.Feeds.CONTENT_URI,
-                where.toString(), new String[] {account, authority});
-    }
-
-    public static String gtalkServiceRoutingInfoFromAccountAndResource(
-            String account, String res) {
-        return Uri.parse("gtalk://" + account + "/" + res).toString();
+                where.toString(), new String[] {account.mName, account.mType, authority});
     }
 
     /**
@@ -157,6 +156,12 @@
          * <P>Type: TEXT</P>
          */
         public static final String _SYNC_ACCOUNT = SyncConstValue._SYNC_ACCOUNT;
+
+        /**
+         * The account type.
+         * <P>Type: TEXT</P>
+         */
+        public static final String _SYNC_ACCOUNT_TYPE = SyncConstValue._SYNC_ACCOUNT_TYPE;
     }
 
     /**
@@ -199,6 +204,6 @@
         /**
          * The default sort order for this table
          */
-        public static final String DEFAULT_SORT_ORDER = "_SYNC_ACCOUNT ASC";
+        public static final String DEFAULT_SORT_ORDER = "_SYNC_ACCOUNT_TYPE, _SYNC_ACCOUNT ASC";
     }
 }
diff --git a/core/java/android/provider/SyncConstValue.java b/core/java/android/provider/SyncConstValue.java
index 6eb4398..30966eb 100644
--- a/core/java/android/provider/SyncConstValue.java
+++ b/core/java/android/provider/SyncConstValue.java
@@ -29,6 +29,12 @@
     public static final String _SYNC_ACCOUNT = "_sync_account";
 
     /**
+     * The type of the account that was used to sync the entry to the device.
+     * <P>Type: TEXT</P>
+     */
+    public static final String _SYNC_ACCOUNT_TYPE = "_sync_account_type";
+
+    /**
      * The unique ID for a row assigned by the sync source. NULL if the row has never been synced.
      * <P>Type: TEXT</P>
      */
@@ -68,4 +74,9 @@
      * Used to indicate that this account is not synced
      */
     public static final String NON_SYNCABLE_ACCOUNT = "non_syncable";
+
+    /**
+     * Used to indicate that this account is not synced
+     */
+    public static final String NON_SYNCABLE_ACCOUNT_TYPE = "android.local";
 }
diff --git a/core/java/android/provider/SyncStateContract.java b/core/java/android/provider/SyncStateContract.java
new file mode 100644
index 0000000..7927e28
--- /dev/null
+++ b/core/java/android/provider/SyncStateContract.java
@@ -0,0 +1,125 @@
+/*
+ * 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
+ */
+
+package android.provider;
+
+import android.net.Uri;
+import android.content.ContentProviderClient;
+import android.content.ContentValues;
+import android.content.ContentProviderOperation;
+import android.accounts.Account;
+import android.database.Cursor;
+import android.os.RemoteException;
+
+/**
+ * The ContentProvider contract for associating data with ana data array account.
+ * This may be used by providers that want to store this data in a standard way.
+ */
+public class SyncStateContract {
+    public interface Columns extends BaseColumns {
+        /**
+         * A reference to the name of the account to which this data belongs
+         * <P>Type: STRING</P>
+         */
+        public static final String ACCOUNT_NAME = "account_name";
+
+        /**
+         * A reference to the type of the account to which this data belongs
+         * <P>Type: STRING</P>
+         */
+        public static final String ACCOUNT_TYPE = "account_type";
+
+        /**
+         * The sync data associated with this account.
+         * <P>Type: NONE</P>
+         */
+        public static final String DATA = "data";
+    }
+
+    public static class Constants implements Columns {
+        public static final String CONTENT_DIRECTORY = "syncstate";
+    }
+
+    public static final class Helpers {
+        private static final String[] DATA_PROJECTION = new String[]{Columns.DATA};
+        private static final String SELECT_BY_ACCOUNT =
+                Columns.ACCOUNT_NAME + "=? AND " + Columns.ACCOUNT_TYPE + "=?";
+
+        /**
+         * Get the sync state that is associated with the account or null.
+         * @param provider the {@link ContentProviderClient} that is to be used to communicate
+         * with the {@link android.content.ContentProvider} that contains the sync state.
+         * @param uri the uri of the sync state
+         * @param account the {@link Account} whose sync state should be returned
+         * @return the sync state or null if there is no sync state associated with the account
+         * @throws RemoteException if there is a failure communicating with the remote
+         * {@link android.content.ContentProvider}
+         */
+        public static byte[] get(ContentProviderClient provider, Uri uri,
+                Account account) throws RemoteException {
+            Cursor c = provider.query(uri, DATA_PROJECTION, SELECT_BY_ACCOUNT,
+                    new String[]{account.mName, account.mType}, null);
+            try {
+                if (c.moveToNext()) {
+                    return c.getBlob(c.getColumnIndexOrThrow(Columns.DATA));
+                }
+            } finally {
+                c.close();
+            }
+            return null;
+        }
+
+        /**
+         * Assigns the data array as the sync state for the given account.
+         * @param provider the {@link ContentProviderClient} that is to be used to communicate
+         * with the {@link android.content.ContentProvider} that contains the sync state.
+         * @param uri the uri of the sync state
+         * @param account the {@link Account} whose sync state should be set
+         * @param data the byte[] that contains the sync state
+         * @throws RemoteException if there is a failure communicating with the remote
+         * {@link android.content.ContentProvider}
+         */
+        public static void set(ContentProviderClient provider, Uri uri,
+                Account account, byte[] data) throws RemoteException {
+            ContentValues values = new ContentValues();
+            values.put(Columns.DATA, data);
+            values.put(Columns.ACCOUNT_NAME, account.mName);
+            values.put(Columns.ACCOUNT_TYPE, account.mType);
+            provider.insert(uri, values);
+        }
+
+        /**
+         * Creates and returns a ContentProviderOperation that assigns the data array as the
+         * sync state for the given account.
+         * @param uri the uri of the sync state
+         * @param account the {@link Account} whose sync state should be set
+         * @param data the byte[] that contains the sync state
+         * @return the new ContentProviderOperation that assigns the data array as the
+         * account's sync state
+         */
+        public static ContentProviderOperation newSetOperation(Uri uri,
+                Account account, byte[] data) {
+            ContentValues values = new ContentValues();
+            values.put(Columns.DATA, data);
+            return ContentProviderOperation
+                    .newInsert(uri)
+                    .withValue(Columns.ACCOUNT_NAME, account.mName)
+                    .withValue(Columns.ACCOUNT_TYPE, account.mType)
+                    .withValues(values)
+                    .build();
+        }
+    }
+}
diff --git a/core/java/android/provider/Telephony.java b/core/java/android/provider/Telephony.java
index c292c53..7a6f6bb 100644
--- a/core/java/android/provider/Telephony.java
+++ b/core/java/android/provider/Telephony.java
@@ -146,7 +146,13 @@
          * <P>Type: TEXT</P>
          */
         public static final String SERVICE_CENTER = "service_center";
-    }
+
+        /**
+         * Has the message been locked?
+         * <P>Type: INTEGER (boolean)</P>
+         */
+        public static final String LOCKED = "locked";
+}
 
     /**
      * Contains all text based SMS messages.
@@ -1008,6 +1014,12 @@
          * <P>Type: INTEGER</P>
          */
         public static final String THREAD_ID = "thread_id";
+
+        /**
+         * Has the message been locked?
+         * <P>Type: INTEGER (boolean)</P>
+         */
+        public static final String LOCKED = "locked";
     }
 
     /**
@@ -1416,6 +1428,8 @@
              */
             public static final String _DATA = "_data";
 
+            public static final String TEXT = "text";
+
         }
 
         public static final class Rate {
@@ -1493,6 +1507,14 @@
         public static final Uri CONTENT_DRAFT_URI = Uri.parse(
                 "content://mms-sms/draft");
 
+        /***
+         * Pass in a query parameter called "pattern" which is the text
+         * to search for.
+         * The sort order is fixed to be thread_id ASC,date DESC.
+         */
+        public static final Uri SEARCH_URI = Uri.parse(
+                "content://mms-sms/search");
+
         // Constants for message protocol types.
         public static final int SMS_PROTO = 0;
         public static final int MMS_PROTO = 1;
diff --git a/core/java/android/server/BluetoothA2dpService.java b/core/java/android/server/BluetoothA2dpService.java
index 5c4e56d..fb436e5 100644
--- a/core/java/android/server/BluetoothA2dpService.java
+++ b/core/java/android/server/BluetoothA2dpService.java
@@ -26,14 +26,13 @@
 import android.bluetooth.BluetoothDevice;
 import android.bluetooth.BluetoothError;
 import android.bluetooth.BluetoothIntent;
+import android.bluetooth.BluetoothUuid;
 import android.bluetooth.IBluetoothA2dp;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.content.pm.PackageManager;
 import android.media.AudioManager;
-import android.os.Binder;
 import android.os.Handler;
 import android.os.Message;
 import android.provider.Settings;
@@ -44,6 +43,7 @@
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
+import java.util.UUID;
 
 public class BluetoothA2dpService extends IBluetoothA2dp.Stub {
     private static final String TAG = "BluetoothA2dpService";
@@ -54,61 +54,25 @@
     private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
     private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
 
-    private static final String A2DP_SINK_ADDRESS = "a2dp_sink_address";
     private static final String BLUETOOTH_ENABLED = "bluetooth_enabled";
 
     private static final int MESSAGE_CONNECT_TO = 1;
-    private static final int MESSAGE_DISCONNECT = 2;
+
+    private static final String PROPERTY_STATE = "State";
+
+    private static final String SINK_STATE_DISCONNECTED = "disconnected";
+    private static final String SINK_STATE_CONNECTING = "connecting";
+    private static final String SINK_STATE_CONNECTED = "connected";
+    private static final String SINK_STATE_PLAYING = "playing";
+
+    private static int mSinkCount;
+
 
     private final Context mContext;
     private final IntentFilter mIntentFilter;
-    private HashMap<String, SinkState> mAudioDevices;
+    private HashMap<String, Integer> mAudioDevices;
     private final AudioManager mAudioManager;
-    private final BluetoothDevice mBluetooth;
-
-    // list of disconnected sinks to process after a delay
-    private final ArrayList<String> mPendingDisconnects = new ArrayList<String>();
-    // number of active sinks
-    private int mSinkCount = 0; 
-
-    private class SinkState {
-        public String address;
-        public int state;
-        public SinkState(String a, int s) {address = a; state = s;}
-    }
-
-    public BluetoothA2dpService(Context context) {
-        mContext = context;
-
-        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
-
-        mBluetooth = (BluetoothDevice) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
-        if (mBluetooth == null) {
-            throw new RuntimeException("Platform does not support Bluetooth");
-        }
-
-        if (!initNative()) {
-            throw new RuntimeException("Could not init BluetoothA2dpService");
-        }
-
-        mIntentFilter = new IntentFilter(BluetoothIntent.BLUETOOTH_STATE_CHANGED_ACTION);
-        mIntentFilter.addAction(BluetoothIntent.BOND_STATE_CHANGED_ACTION);
-        mIntentFilter.addAction(BluetoothIntent.REMOTE_DEVICE_CONNECTED_ACTION);
-        mContext.registerReceiver(mReceiver, mIntentFilter);
-
-        if (mBluetooth.isEnabled()) {
-            onBluetoothEnable();
-        }
-    }
-
-    @Override
-    protected void finalize() throws Throwable {
-        try {
-            cleanupNative();
-        } finally {
-            super.finalize();
-        }
-    }
+    private final BluetoothDeviceService mBluetoothService;
 
     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
         @Override
@@ -139,7 +103,8 @@
                     break;
                 }
             } else if (action.equals(BluetoothIntent.REMOTE_DEVICE_CONNECTED_ACTION)) {
-                if (getSinkPriority(address) > BluetoothA2dp.PRIORITY_OFF) {
+                if (getSinkPriority(address) > BluetoothA2dp.PRIORITY_OFF &&
+                        isSinkDevice(address)) {
                     // This device is a preferred sink. Make an A2DP connection
                     // after a delay. We delay to avoid connection collisions,
                     // and to give other profiles such as HFP a chance to
@@ -151,6 +116,40 @@
         }
     };
 
+    public BluetoothA2dpService(Context context, BluetoothDeviceService bluetoothService) {
+        mContext = context;
+
+        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
+
+        mBluetoothService = bluetoothService;
+        if (mBluetoothService == null) {
+            throw new RuntimeException("Platform does not support Bluetooth");
+        }
+
+        if (!initNative()) {
+            throw new RuntimeException("Could not init BluetoothA2dpService");
+        }
+
+        mIntentFilter = new IntentFilter(BluetoothIntent.BLUETOOTH_STATE_CHANGED_ACTION);
+        mIntentFilter.addAction(BluetoothIntent.BOND_STATE_CHANGED_ACTION);
+        mIntentFilter.addAction(BluetoothIntent.REMOTE_DEVICE_CONNECTED_ACTION);
+        mContext.registerReceiver(mReceiver, mIntentFilter);
+
+        mAudioDevices = new HashMap<String, Integer>();
+
+        if (mBluetoothService.isEnabled())
+            onBluetoothEnable();
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            cleanupNative();
+        } finally {
+            super.finalize();
+        }
+    }
+
     private final Handler mHandler = new Handler() {
         @Override
         public void handleMessage(Message msg) {
@@ -159,7 +158,7 @@
                 String address = (String)msg.obj;
                 // check bluetooth is still on, device is still preferred, and
                 // nothing is currently connected
-                if (mBluetooth.isEnabled() &&
+                if (mBluetoothService.isEnabled() &&
                         getSinkPriority(address) > BluetoothA2dp.PRIORITY_OFF &&
                         lookupSinksMatchingStates(new int[] {
                             BluetoothA2dp.STATE_CONNECTING,
@@ -170,48 +169,100 @@
                     connectSink(address);
                 }
                 break;
-            case MESSAGE_DISCONNECT:
-                handleDeferredDisconnect((String)msg.obj);
-                break;
             }
         }
     };
 
-    private synchronized void onBluetoothEnable() {
-        mAudioDevices = new HashMap<String, SinkState>();
-        String[] paths = (String[])listHeadsetsNative();
-        if (paths != null) {
-            for (String path : paths) {
-                mAudioDevices.put(path, new SinkState(getAddressNative(path),
-                        isSinkConnectedNative(path) ? BluetoothA2dp.STATE_CONNECTED :
-                                                      BluetoothA2dp.STATE_DISCONNECTED));
+    private int convertBluezSinkStringtoState(String value) {
+        if (value.equalsIgnoreCase("disconnected"))
+            return BluetoothA2dp.STATE_DISCONNECTED;
+        if (value.equalsIgnoreCase("connecting"))
+            return BluetoothA2dp.STATE_CONNECTING;
+        if (value.equalsIgnoreCase("connected"))
+            return BluetoothA2dp.STATE_CONNECTED;
+        if (value.equalsIgnoreCase("playing"))
+            return BluetoothA2dp.STATE_PLAYING;
+        return -1;
+    }
+
+    private boolean isSinkDevice(String address) {
+        String uuids[] = mBluetoothService.getRemoteUuids(address);
+        UUID uuid;
+        for (String deviceUuid: uuids) {
+            uuid = UUID.fromString(deviceUuid);
+            if (BluetoothUuid.isAudioSink(uuid)) {
+                return true;
             }
         }
-        mAudioManager.setParameter(BLUETOOTH_ENABLED, "true");
+        return false;
+    }
+
+    private synchronized boolean addAudioSink (String address) {
+        String path = mBluetoothService.getObjectPathFromAddress(address);
+        String propValues[] = (String []) getSinkPropertiesNative(path);
+        if (propValues == null) {
+            Log.e(TAG, "Error while getting AudioSink properties for device: " + address);
+            return false;
+        }
+        Integer state = null;
+        // Properties are name-value pairs
+        for (int i = 0; i < propValues.length; i+=2) {
+            if (propValues[i].equals(PROPERTY_STATE)) {
+                state = new Integer(convertBluezSinkStringtoState(propValues[i+1]));
+                break;
+            }
+        }
+        mAudioDevices.put(address, state);
+        handleSinkStateChange(address, BluetoothA2dp.STATE_DISCONNECTED, state);
+        return true;
+    }
+
+    private synchronized void onBluetoothEnable() {
+        String devices = mBluetoothService.getProperty("Devices");
+        mSinkCount = 0;
+        if (devices != null) {
+            String [] paths = devices.split(",");
+            for (String path: paths) {
+                String address = mBluetoothService.getAddressFromObjectPath(path);
+                String []uuids = mBluetoothService.getRemoteUuids(address);
+                if (uuids != null)
+                    for (String uuid: uuids) {
+                        UUID remoteUuid = UUID.fromString(uuid);
+                        if (BluetoothUuid.isAudioSink(remoteUuid) ||
+                            BluetoothUuid.isAudioSource(remoteUuid) ||
+                            BluetoothUuid.isAdvAudioDist(remoteUuid)) {
+                            addAudioSink(address);
+                            break;
+                        }
+                    }
+            }
+        }
+        mAudioManager.setParameters(BLUETOOTH_ENABLED+"=true");
     }
 
     private synchronized void onBluetoothDisable() {
-        if (mAudioDevices != null) {
-            // copy to allow modification during iteration
-            String[] paths = new String[mAudioDevices.size()];
-            paths = mAudioDevices.keySet().toArray(paths);
-            for (String path : paths) {
-                switch (mAudioDevices.get(path).state) {
+        if (!mAudioDevices.isEmpty()) {
+            String [] addresses = new String[mAudioDevices.size()];
+            addresses = mAudioDevices.keySet().toArray(addresses);
+            for (String address : addresses) {
+                int state = getSinkState(address);
+                switch (state) {
                     case BluetoothA2dp.STATE_CONNECTING:
                     case BluetoothA2dp.STATE_CONNECTED:
                     case BluetoothA2dp.STATE_PLAYING:
-                        disconnectSinkNative(path);
-                        updateState(path, BluetoothA2dp.STATE_DISCONNECTED);
+                        disconnectSinkNative(mBluetoothService.getObjectPathFromAddress(address));
+                        handleSinkStateChange(address,state, BluetoothA2dp.STATE_DISCONNECTED);
                         break;
                     case BluetoothA2dp.STATE_DISCONNECTING:
-                        updateState(path, BluetoothA2dp.STATE_DISCONNECTED);
+                        handleSinkStateChange(address, BluetoothA2dp.STATE_DISCONNECTING,
+                                                BluetoothA2dp.STATE_DISCONNECTED);
                         break;
                 }
             }
-            mAudioDevices = null;
+            mAudioDevices.clear();
         }
-        mAudioManager.setBluetoothA2dpOn(false);
-        mAudioManager.setParameter(BLUETOOTH_ENABLED, "false");
+
+        mAudioManager.setParameters(BLUETOOTH_ENABLED+"=false");
     }
 
     public synchronized int connectSink(String address) {
@@ -221,9 +272,7 @@
         if (!BluetoothDevice.checkBluetoothAddress(address)) {
             return BluetoothError.ERROR;
         }
-        if (mAudioDevices == null) {
-            return BluetoothError.ERROR;
-        }
+
         // ignore if there are any active sinks
         if (lookupSinksMatchingStates(new int[] {
                 BluetoothA2dp.STATE_CONNECTING,
@@ -233,20 +282,11 @@
             return BluetoothError.ERROR;
         }
 
-        String path = lookupPath(address);
-        if (path == null) {
-            path = createHeadsetNative(address);
-            if (DBG) log("new bluez sink: " + address + " (" + path + ")");
-        }
-        if (path == null) {
+        if (mAudioDevices.get(address) == null && !addAudioSink(address))
             return BluetoothError.ERROR;
-        }
 
-        SinkState sink = mAudioDevices.get(path);
-        int state = BluetoothA2dp.STATE_DISCONNECTED;
-        if (sink != null) {
-            state = sink.state;
-        }
+        int state = mAudioDevices.get(address);
+
         switch (state) {
         case BluetoothA2dp.STATE_CONNECTED:
         case BluetoothA2dp.STATE_PLAYING:
@@ -256,11 +296,14 @@
             return BluetoothError.SUCCESS;
         }
 
+        String path = mBluetoothService.getObjectPathFromAddress(address);
+        if (path == null)
+            return BluetoothError.ERROR;
+
         // State is DISCONNECTED
         if (!connectSinkNative(path)) {
             return BluetoothError.ERROR;
         }
-        updateState(path, BluetoothA2dp.STATE_CONNECTING);
         return BluetoothError.SUCCESS;
     }
 
@@ -271,14 +314,12 @@
         if (!BluetoothDevice.checkBluetoothAddress(address)) {
             return BluetoothError.ERROR;
         }
-        if (mAudioDevices == null) {
-            return BluetoothError.ERROR;
-        }
-        String path = lookupPath(address);
+        String path = mBluetoothService.getObjectPathFromAddress(address);
         if (path == null) {
             return BluetoothError.ERROR;
         }
-        switch (mAudioDevices.get(path).state) {
+
+        switch (getSinkState(address)) {
         case BluetoothA2dp.STATE_DISCONNECTED:
             return BluetoothError.ERROR;
         case BluetoothA2dp.STATE_DISCONNECTING:
@@ -289,7 +330,6 @@
         if (!disconnectSinkNative(path)) {
             return BluetoothError.ERROR;
         } else {
-            updateState(path, BluetoothA2dp.STATE_DISCONNECTING);
             return BluetoothError.SUCCESS;
         }
     }
@@ -305,15 +345,10 @@
         if (!BluetoothDevice.checkBluetoothAddress(address)) {
             return BluetoothError.ERROR;
         }
-        if (mAudioDevices == null) {
+        Integer state = mAudioDevices.get(address);
+        if (state == null)
             return BluetoothA2dp.STATE_DISCONNECTED;
-        }
-        for (SinkState sink : mAudioDevices.values()) {
-            if (address.equals(sink.address)) {
-                return sink.state;
-            }
-        }
-        return BluetoothA2dp.STATE_DISCONNECTED;
+        return state;
     }
 
     public synchronized int getSinkPriority(String address) {
@@ -337,135 +372,41 @@
                 BluetoothError.SUCCESS : BluetoothError.ERROR;
     }
 
-    private synchronized void onHeadsetCreated(String path) {
-        updateState(path, BluetoothA2dp.STATE_DISCONNECTED);
-    }
-
-    private synchronized void onHeadsetRemoved(String path) {
-        if (mAudioDevices == null) return;
-        mAudioDevices.remove(path);
-    }
-
-    private synchronized void onSinkConnected(String path) {
-        // if we are reconnected, do not process previous disconnect event.
-        mPendingDisconnects.remove(path);
-
-        if (mAudioDevices == null) return;
-        // bluez 3.36 quietly disconnects the previous sink when a new sink
-        // is connected, so we need to mark all previously connected sinks as
-        // disconnected
-
-        // copy to allow modification during iteration
-        String[] paths = new String[mAudioDevices.size()];
-        paths = mAudioDevices.keySet().toArray(paths);
-        for (String oldPath : paths) {
-            if (path.equals(oldPath)) {
-                continue;
-            }
-            int state = mAudioDevices.get(oldPath).state;
-            if (state == BluetoothA2dp.STATE_CONNECTED || state == BluetoothA2dp.STATE_PLAYING) {
-                updateState(path, BluetoothA2dp.STATE_DISCONNECTED);
-            }
+    private synchronized void onSinkPropertyChanged(String path, String []propValues) {
+        String name = propValues[0];
+        String address = mBluetoothService.getAddressFromObjectPath(path);
+        if (address == null) {
+            Log.e(TAG, "onSinkPropertyChanged: Address of the remote device in null");
+            return;
         }
 
-        updateState(path, BluetoothA2dp.STATE_CONNECTING);
-        mAudioManager.setParameter(A2DP_SINK_ADDRESS, lookupAddress(path));
-        mAudioManager.setBluetoothA2dpOn(true);
-        updateState(path, BluetoothA2dp.STATE_CONNECTED);
-    }
-
-    private synchronized void onSinkDisconnected(String path) {
-        // This is to work around a problem in bluez that results 
-        // sink disconnect events being sent, immediately followed by a reconnect.
-        // To avoid unnecessary audio routing changes, we defer handling
-        // sink disconnects until after a short delay.
-        mPendingDisconnects.add(path);
-        Message msg = Message.obtain(mHandler, MESSAGE_DISCONNECT, path);
-        mHandler.sendMessageDelayed(msg, 2000);
-    }
-
-    private synchronized void handleDeferredDisconnect(String path) {
-        if (mPendingDisconnects.contains(path)) {
-            mPendingDisconnects.remove(path);
-            if (mSinkCount == 1) {
-                mAudioManager.setBluetoothA2dpOn(false);
-            }
-            updateState(path, BluetoothA2dp.STATE_DISCONNECTED);
+        if (mAudioDevices.get(address) == null) {
+            // Ignore this state change, since it means we have got it after
+            // bluetooth has been disabled.
+            return;
+        }
+        if (name.equals(PROPERTY_STATE)) {
+            int state = convertBluezSinkStringtoState(propValues[1]);
+            int prevState = mAudioDevices.get(address);
+            handleSinkStateChange(address, prevState, state);
         }
     }
 
-    private synchronized void onSinkPlaying(String path) {
-        updateState(path, BluetoothA2dp.STATE_PLAYING);
-    }
-
-    private synchronized void onSinkStopped(String path) {
-        updateState(path, BluetoothA2dp.STATE_CONNECTED);
-    }
-
-    private synchronized final String lookupAddress(String path) {
-        if (mAudioDevices == null) return null;
-        SinkState sink = mAudioDevices.get(path);
-        if (sink == null) {
-            Log.w(TAG, "lookupAddress() called for unknown device " + path);
-            updateState(path, BluetoothA2dp.STATE_DISCONNECTED);
-        }
-        String address = mAudioDevices.get(path).address;
-        if (address == null) Log.e(TAG, "Can't find address for " + path);
-        return address;
-    }
-
-    private synchronized final String lookupPath(String address) {
-        if (mAudioDevices == null) return null;
-
-        for (String path : mAudioDevices.keySet()) {
-            if (address.equals(mAudioDevices.get(path).address)) {
-                return path;
-            }
-        }
-        return null;
-    }
-
-    private synchronized List<String> lookupSinksMatchingStates(int[] states) {
-        List<String> sinks = new ArrayList<String>();
-        if (mAudioDevices == null) {
-            return sinks;
-        }
-        for (SinkState sink : mAudioDevices.values()) {
-            for (int state : states) {
-                if (sink.state == state) {
-                    sinks.add(sink.address);
-                    break;
-                }
-            }
-        }
-        return sinks;
-    }
-
-    private synchronized void updateState(String path, int state) {
-        if (mAudioDevices == null) return;
-
-        SinkState s = mAudioDevices.get(path);
-        int prevState;
-        String address;
-        if (s == null) {
-            address = getAddressNative(path);
-            mAudioDevices.put(path, new SinkState(address, state));
-            prevState = BluetoothA2dp.STATE_DISCONNECTED;
-        } else {
-            address = lookupAddress(path);
-            prevState = s.state;
-            s.state = state;
-        }
-
+    private void handleSinkStateChange(String address, int prevState, int state) {
         if (state != prevState) {
-            if (DBG) log("state " + address + " (" + path + ") " + prevState + "->" + state);
-            
-            // keep track of the number of active sinks
-            if (prevState == BluetoothA2dp.STATE_DISCONNECTED) {
-                mSinkCount++;
-            } else if (state == BluetoothA2dp.STATE_DISCONNECTED) {
+            if (state == BluetoothA2dp.STATE_DISCONNECTED ||
+                    state == BluetoothA2dp.STATE_DISCONNECTING) {
+                if (prevState == BluetoothA2dp.STATE_CONNECTED ||
+                        prevState == BluetoothA2dp.STATE_PLAYING) {
+                   // disconnecting or disconnected
+                   Intent intent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
+                   mContext.sendBroadcast(intent);
+                }
                 mSinkCount--;
+            } else if (state == BluetoothA2dp.STATE_CONNECTED) {
+                mSinkCount ++;
             }
+            mAudioDevices.put(address, state);
 
             Intent intent = new Intent(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
             intent.putExtra(BluetoothIntent.ADDRESS, address);
@@ -473,25 +414,35 @@
             intent.putExtra(BluetoothA2dp.SINK_STATE, state);
             mContext.sendBroadcast(intent, BLUETOOTH_PERM);
 
-            if ((prevState == BluetoothA2dp.STATE_CONNECTED ||
-                 prevState == BluetoothA2dp.STATE_PLAYING) &&
-                    (state != BluetoothA2dp.STATE_CONNECTING &&
-                     state != BluetoothA2dp.STATE_CONNECTED &&
-                     state != BluetoothA2dp.STATE_PLAYING)) {
-                // disconnected
-                intent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
-                mContext.sendBroadcast(intent);
-            }
+            if (DBG) log("A2DP state : address: " + address + " State:" + prevState + "->" + state);
         }
     }
 
+    private synchronized List<String> lookupSinksMatchingStates(int[] states) {
+        List<String> sinks = new ArrayList<String>();
+        if (mAudioDevices.isEmpty()) {
+            return sinks;
+        }
+        for (String path: mAudioDevices.keySet()) {
+            int sinkState = getSinkState(path);
+            for (int state : states) {
+                if (state == sinkState) {
+                    sinks.add(path);
+                    break;
+                }
+            }
+        }
+        return sinks;
+    }
+
+
     @Override
     protected synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-        if (mAudioDevices == null) return;
+        if (mAudioDevices.isEmpty()) return;
         pw.println("Cached audio devices:");
-        for (String path : mAudioDevices.keySet()) {
-            SinkState sink = mAudioDevices.get(path);
-            pw.println(path + " " + sink.address + " " + BluetoothA2dp.stateToString(sink.state));
+        for (String address : mAudioDevices.keySet()) {
+            int state = mAudioDevices.get(address);
+            pw.println(address + " " + BluetoothA2dp.stateToString(state));
         }
     }
 
@@ -501,11 +452,7 @@
 
     private native boolean initNative();
     private native void cleanupNative();
-    private synchronized native String[] listHeadsetsNative();
-    private synchronized native String createHeadsetNative(String address);
-    private synchronized native boolean removeHeadsetNative(String path);
-    private synchronized native String getAddressNative(String path);
     private synchronized native boolean connectSinkNative(String path);
     private synchronized native boolean disconnectSinkNative(String path);
-    private synchronized native boolean isSinkConnectedNative(String path);
+    private synchronized native Object []getSinkPropertiesNative(String path);
 }
diff --git a/core/java/android/server/BluetoothDeviceService.java b/core/java/android/server/BluetoothDeviceService.java
index 8c843ef..b780f41 100644
--- a/core/java/android/server/BluetoothDeviceService.java
+++ b/core/java/android/server/BluetoothDeviceService.java
@@ -30,7 +30,6 @@
 import android.bluetooth.BluetoothHeadset;
 import android.bluetooth.BluetoothIntent;
 import android.bluetooth.IBluetoothDevice;
-import android.bluetooth.IBluetoothDeviceCallback;
 import android.content.BroadcastReceiver;
 import android.content.ContentResolver;
 import android.content.Context;
@@ -38,7 +37,6 @@
 import android.content.IntentFilter;
 import android.os.Binder;
 import android.os.Handler;
-import android.os.IBinder;
 import android.os.Message;
 import android.os.RemoteException;
 import android.os.ServiceManager;
@@ -46,6 +44,8 @@
 import android.provider.Settings;
 import android.util.Log;
 
+import com.android.internal.app.IBatteryStats;
+
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.io.UnsupportedEncodingException;
@@ -55,8 +55,6 @@
 import java.util.Iterator;
 import java.util.Map;
 
-import com.android.internal.app.IBatteryStats;
-
 public class BluetoothDeviceService extends IBluetoothDevice.Stub {
     private static final String TAG = "BluetoothDeviceService";
     private static final boolean DBG = true;
@@ -80,10 +78,12 @@
     private static final int MESSAGE_REGISTER_SDP_RECORDS = 1;
     private static final int MESSAGE_FINISH_DISABLE = 2;
 
+    private Map<String, String> mProperties;
+    private HashMap <String, Map<String, String>> mRemoteDeviceProperties;
+
     static {
         classInitNative();
     }
-    private native static void classInitNative();
 
     public BluetoothDeviceService(Context context) {
         mContext = context;
@@ -109,8 +109,9 @@
         mIsDiscovering = false;
         mEventLoop = new BluetoothEventLoop(mContext, this);
         registerForAirplaneMode();
+        mProperties = new HashMap<String, String>();
+        mRemoteDeviceProperties = new HashMap<String, Map<String,String>>();
     }
-    private native void initializeNativeDataNative();
 
     @Override
     protected void finalize() throws Throwable {
@@ -123,13 +124,11 @@
             super.finalize();
         }
     }
-    private native void cleanupNativeDataNative();
 
     public boolean isEnabled() {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
         return mBluetoothState == BluetoothDevice.BLUETOOTH_STATE_ON;
     }
-    private native int isEnabledNative();
 
     public int getBluetoothState() {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
@@ -150,8 +149,7 @@
      * @param saveSetting If true, disable BT in settings
      */
     public synchronized boolean disable(boolean saveSetting) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
-                                                "Need BLUETOOTH_ADMIN permission");
+        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
 
         switch (mBluetoothState) {
         case BluetoothDevice.BLUETOOTH_STATE_OFF:
@@ -180,6 +178,7 @@
             return;
         }
         mEventLoop.stop();
+        tearDownNativeDataNative();
         disableNative();
 
         // mark in progress bondings as cancelled
@@ -188,25 +187,13 @@
                                     BluetoothDevice.UNBOND_REASON_AUTH_CANCELED);
         }
 
-        // Remove remoteServiceChannelCallbacks
-        HashMap<String, IBluetoothDeviceCallback> callbacksMap =
-            mEventLoop.getRemoteServiceChannelCallbacks();
-
-        for (Iterator<String> i = callbacksMap.keySet().iterator(); i.hasNext();) {
-            String address = i.next();
-            IBluetoothDeviceCallback callback = callbacksMap.get(address);
-            try {
-                callback.onGetRemoteServiceChannelResult(address, BluetoothError.ERROR_DISABLED);
-            } catch (RemoteException e) {}
-            i.remove();
-        }
-
         // update mode
         Intent intent = new Intent(BluetoothIntent.SCAN_MODE_CHANGED_ACTION);
         intent.putExtra(BluetoothIntent.SCAN_MODE, BluetoothDevice.SCAN_MODE_NONE);
         mContext.sendBroadcast(intent, BLUETOOTH_PERM);
 
         mIsDiscovering = false;
+        mProperties.clear();
 
         if (saveSetting) {
             persistBluetoothOnSetting(false);
@@ -270,7 +257,7 @@
         if (!disable(false)) {
             mRestart = false;
         }
-    }   
+    }
 
     private synchronized void setBluetoothState(int state) {
         if (state == mBluetoothState) {
@@ -298,6 +285,7 @@
                 if (isEnabled()) {
                     SystemService.start("hsag");
                     SystemService.start("hfag");
+                    SystemService.start("opush");
                 }
                 break;
             case MESSAGE_FINISH_DISABLE:
@@ -343,6 +331,9 @@
 
 
             if (res) {
+                if (!setupNativeDataNative()) {
+                    return;
+                }
                 if (mSaveSetting) {
                     persistBluetoothOnSetting(true);
                 }
@@ -369,7 +360,8 @@
 
             if (res) {
                 // Update mode
-                mEventLoop.onModeChanged(getModeNative());
+                String[] propVal = {"Pairable", getProperty("Pairable")};
+                mEventLoop.onPropertyChanged(propVal);
             }
 
             if (mIsAirplaneSensitive && isAirplaneModeOn()) {
@@ -386,9 +378,6 @@
         Binder.restoreCallingIdentity(origCallerIdentityToken);
     }
 
-    private native int enableNative();
-    private native int disableNative();
-
     /* package */ BondState getBondState() {
         return mBondState;
     }
@@ -423,14 +412,19 @@
             if (mBluetoothState != BluetoothDevice.BLUETOOTH_STATE_TURNING_ON) {
                 return;
             }
-            String[] bonds = listBondingsNative();
+            String []bonds = null;
+            String val = getProperty("Devices");
+            if (val != null) {
+                bonds = val.split(",");
+            }
             if (bonds == null) {
                 return;
             }
             mState.clear();
             if (DBG) log("found " + bonds.length + " bonded devices");
-            for (String address : bonds) {
-                mState.put(address.toUpperCase(), BluetoothDevice.BOND_BONDED);
+            for (String device : bonds) {
+                mState.put(getAddressFromObjectPath(device).toUpperCase(),
+                        BluetoothDevice.BOND_BONDED);
             }
         }
 
@@ -528,7 +522,6 @@
         }
 
     }
-    private native String[] listBondingsNative();
 
     private static String toBondStateString(int bondState) {
         switch (bondState) {
@@ -543,17 +536,49 @@
         }
     }
 
-    public synchronized String getAddress() {
+    /*package*/synchronized void getAllProperties() {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return getAddressNative();
-    }
-    private native String getAddressNative();
+        mProperties.clear();
 
-    public synchronized String getName() {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return getNameNative();
+        String properties[] = (String [])getAdapterPropertiesNative();
+        // The String Array consists of key-value pairs.
+        if (properties == null) {
+            Log.e(TAG, "*Error*: GetAdapterProperties returned NULL");
+            return;
+        }
+
+        for (int i = 0; i < properties.length; i++) {
+            String name = properties[i];
+            String newValue;
+            int len;
+            if (name == null) {
+                Log.e(TAG, "Error:Adapter Property at index" + i + "is null");
+                continue;
+            }
+            if (name.equals("Devices")) {
+                len = Integer.valueOf(properties[++i]);
+                if (len != 0)
+                    newValue = "";
+                else
+                    newValue = null;
+                for (int j = 0; j < len; j++) {
+                    newValue += properties[++i] + ",";
+                }
+            } else {
+                newValue = properties[++i];
+            }
+            mProperties.put(name, newValue);
+        }
+
+        // Add adapter object path property.
+        String adapterPath = getAdapterPathNative();
+        if (adapterPath != null)
+            mProperties.put("ObjectPath", adapterPath + "/dev_");
     }
-    private native String getNameNative();
+
+    /* package */ synchronized void setProperty(String name, String value) {
+        mProperties.put(name, value);
+    }
 
     public synchronized boolean setName(String name) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
@@ -561,74 +586,27 @@
         if (name == null) {
             return false;
         }
-        // hcid handles persistance of the bluetooth name
-        return setNameNative(name);
+        return setPropertyString("Name", name);
     }
-    private native boolean setNameNative(String name);
 
-    /**
-     * Returns the user-friendly name of a remote device.  This value is
-     * retrned from our local cache, which is updated during device discovery.
-     * Do not expect to retrieve the updated remote name immediately after
-     * changing the name on the remote device.
-     *
-     * @param address Bluetooth address of remote device.
-     *
-     * @return The user-friendly name of the specified remote device.
-     */
-    public synchronized String getRemoteName(String address) {
+    //TODO(): setPropertyString, setPropertyInteger, setPropertyBoolean
+    // Either have a single property function with Object as the parameter
+    // or have a function for each property and then obfuscate in the JNI layer.
+    // The following looks dirty.
+    private boolean setPropertyString(String key, String value) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return null;
-        }
-        return getRemoteNameNative(address);
+        return setAdapterPropertyStringNative(key, value);
     }
-    private native String getRemoteNameNative(String address);
 
-    /* pacakge */ native String getAdapterPathNative();
-
-    public synchronized boolean startDiscovery(boolean resolveNames) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
-                                                "Need BLUETOOTH_ADMIN permission");
-        return startDiscoveryNative(resolveNames);
-    }
-    private native boolean startDiscoveryNative(boolean resolveNames);
-
-    public synchronized boolean cancelDiscovery() {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
-                                                "Need BLUETOOTH_ADMIN permission");
-        return cancelDiscoveryNative();
-    }
-    private native boolean cancelDiscoveryNative();
-
-    public synchronized boolean isDiscovering() {
+    private boolean setPropertyInteger(String key, int value) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return mIsDiscovering;
+        return setAdapterPropertyIntegerNative(key, value);
     }
 
-    /* package */ void setIsDiscovering(boolean isDiscovering) {
-        mIsDiscovering = isDiscovering;
-    }
-
-    public synchronized boolean startPeriodicDiscovery() {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
-                                                "Need BLUETOOTH_ADMIN permission");
-        return startPeriodicDiscoveryNative();
-    }
-    private native boolean startPeriodicDiscoveryNative();
-
-    public synchronized boolean stopPeriodicDiscovery() {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
-                                                "Need BLUETOOTH_ADMIN permission");
-        return stopPeriodicDiscoveryNative();
-    }
-    private native boolean stopPeriodicDiscoveryNative();
-
-    public synchronized boolean isPeriodicDiscovery() {
+    private boolean setPropertyBoolean(String key, boolean value) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return isPeriodicDiscoveryNative();
+        return setAdapterPropertyBooleanNative(key, value ? 1 : 0);
     }
-    private native boolean isPeriodicDiscoveryNative();
 
     /**
      * Set the discoverability window for the device.  A timeout of zero
@@ -642,9 +620,67 @@
     public synchronized boolean setDiscoverableTimeout(int timeout) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
                                                 "Need BLUETOOTH_ADMIN permission");
-        return setDiscoverableTimeoutNative(timeout);
+        return setPropertyInteger("DiscoverableTimeout", timeout);
     }
-    private native boolean setDiscoverableTimeoutNative(int timeout_s);
+
+    public synchronized boolean setScanMode(int mode) {
+        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
+                                                "Need BLUETOOTH_ADMIN permission");
+        boolean pairable = false, discoverable = false;
+        String modeString = scanModeToBluezString(mode);
+        if (modeString.equals("off")) {
+            pairable = false;
+            discoverable = false;
+        } else if (modeString.equals("pariable")) {
+            pairable = true;
+            discoverable = false;
+        } else if (modeString.equals("discoverable")) {
+            pairable = true;
+            discoverable = true;
+        }
+        setPropertyBoolean("Pairable", pairable);
+        setPropertyBoolean("Discoverable", discoverable);
+
+        return true;
+    }
+
+    /*package*/ synchronized String getProperty (String name) {
+        if (!mProperties.isEmpty())
+            return mProperties.get(name);
+        getAllProperties();
+        return mProperties.get(name);
+    }
+
+    public synchronized String getAddress() {
+        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
+        return getProperty("Address");
+    }
+
+    public synchronized String getName() {
+        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
+        return getProperty("Name");
+    }
+
+    /**
+     * Returns the user-friendly name of a remote device.  This value is
+     * returned from our local cache, which is updated when onPropertyChange
+     * event is received.
+     * Do not expect to retrieve the updated remote name immediately after
+     * changing the name on the remote device.
+     *
+     * @param address Bluetooth address of remote device.
+     *
+     * @return The user-friendly name of the specified remote device.
+     */
+    public synchronized String getRemoteName(String address) {
+        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
+        if (!BluetoothDevice.checkBluetoothAddress(address)) {
+            return null;
+        }
+        Map <String, String> properties = mRemoteDeviceProperties.get(address);
+        if (properties != null) return properties.get("Name");
+        return null;
+    }
 
     /**
      * Get the discoverability window for the device.  A timeout of zero
@@ -656,45 +692,46 @@
      */
     public synchronized int getDiscoverableTimeout() {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return getDiscoverableTimeoutNative();
+        String timeout = getProperty("DiscoverableTimeout");
+        if (timeout != null)
+           return Integer.valueOf(timeout);
+        else
+            return -1;
     }
-    private native int getDiscoverableTimeoutNative();
-
-    public synchronized boolean isAclConnected(String address) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return false;
-        }
-        return isConnectedNative(address);
-    }
-    private native boolean isConnectedNative(String address);
 
     public synchronized int getScanMode() {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return bluezStringToScanMode(getModeNative());
-    }
-    private native String getModeNative();
+        if (!isEnabled())
+            return BluetoothError.ERROR;
 
-    public synchronized boolean setScanMode(int mode) {
+        boolean pairable = getProperty("Pairable").equals("true");
+        boolean discoverable = getProperty("Discoverable").equals("true");
+        return bluezStringToScanMode (pairable, discoverable);
+    }
+
+    public synchronized boolean startDiscovery() {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
                                                 "Need BLUETOOTH_ADMIN permission");
-        String bluezMode = scanModeToBluezString(mode);
-        if (bluezMode != null) {
-            return setModeNative(bluezMode);
-        }
-        return false;
-    }
-    private native boolean setModeNative(String mode);
-
-    public synchronized boolean disconnectRemoteDeviceAcl(String address) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
-                                                "Need BLUETOOTH_ADMIN permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
+        if (!isEnabled()) {
             return false;
         }
-        return disconnectRemoteDeviceNative(address);
+        return startDiscoveryNative();
     }
-    private native boolean disconnectRemoteDeviceNative(String address);
+
+    public synchronized boolean cancelDiscovery() {
+        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
+                                                "Need BLUETOOTH_ADMIN permission");
+        return stopDiscoveryNative();
+    }
+
+    public synchronized boolean isDiscovering() {
+        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
+        return mIsDiscovering;
+    }
+
+    /* package */ void setIsDiscovering(boolean isDiscovering) {
+        mIsDiscovering = isDiscovering;
+    }
 
     public synchronized boolean createBond(String address) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
@@ -719,14 +756,13 @@
             return false;
         }
 
-        if (!createBondingNative(address, 60000 /* 1 minute */)) {
+        if (!createPairedDeviceNative(address, 60000 /* 1 minute */)) {
             return false;
         }
 
         mBondState.setBondState(address, BluetoothDevice.BOND_BONDING);
         return true;
     }
-    private native boolean createBondingNative(String address, int timeout_ms);
 
     public synchronized boolean cancelBondProcess(String address) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
@@ -741,10 +777,9 @@
 
         mBondState.setBondState(address, BluetoothDevice.BOND_NOT_BONDED,
                                 BluetoothDevice.UNBOND_REASON_AUTH_CANCELED);
-        cancelBondingProcessNative(address);
+        cancelDeviceCreationNative(address);
         return true;
     }
-    private native boolean cancelBondingProcessNative(String address);
 
     public synchronized boolean removeBond(String address) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
@@ -752,9 +787,8 @@
         if (!BluetoothDevice.checkBluetoothAddress(address)) {
             return false;
         }
-        return removeBondingNative(address);
+        return removeDeviceNative(getObjectPathFromAddress(address));
     }
-    private native boolean removeBondingNative(String address);
 
     public synchronized String[] listBonds() {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
@@ -769,198 +803,78 @@
         return mBondState.getBondState(address.toUpperCase());
     }
 
-    public synchronized String[] listAclConnections() {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return listConnectionsNative();
-    }
-    private native String[] listConnectionsNative();
-
-    /**
-     * This method lists all remote devices that this adapter is aware of.
-     * This is a list not only of all most-recently discovered devices, but of
-     * all devices discovered by this adapter up to some point in the past.
-     * Note that many of these devices may not be in the neighborhood anymore,
-     * and attempting to connect to them will result in an error.
-     *
-     * @return An array of strings representing the Bluetooth addresses of all
-     *         remote devices that this adapter is aware of.
-     */
-    public synchronized String[] listRemoteDevices() {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return listRemoteDevicesNative();
-    }
-    private native String[] listRemoteDevicesNative();
-
-    /**
-     * Returns the version of the Bluetooth chip. This version is compiled from
-     * the LMP version. In case of EDR the features attribute must be checked.
-     * Example: "Bluetooth 2.0 + EDR".
-     *
-     * @return a String representation of the this Adapter's underlying
-     *         Bluetooth-chip version.
-     */
-    public synchronized String getVersion() {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return getVersionNative();
-    }
-    private native String getVersionNative();
-
-    /**
-     * Returns the revision of the Bluetooth chip. This is a vendor-specific
-     * value and in most cases it represents the firmware version. This might
-     * derive from the HCI revision and LMP subversion values or via extra
-     * vendord specific commands.
-     * In case the revision of a chip is not available. This method should
-     * return the LMP subversion value as a string.
-     * Example: "HCI 19.2"
-     *
-     * @return The HCI revision of this adapter.
-     */
-    public synchronized String getRevision() {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return getRevisionNative();
-    }
-    private native String getRevisionNative();
-
-    /**
-     * Returns the manufacturer of the Bluetooth chip. If the company id is not
-     * known the sting "Company ID %d" where %d should be replaced with the
-     * numeric value from the manufacturer field.
-     * Example: "Cambridge Silicon Radio"
-     *
-     * @return Manufacturer name.
-     */
-    public synchronized String getManufacturer() {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return getManufacturerNative();
-    }
-    private native String getManufacturerNative();
-
-    /**
-     * Returns the company name from the OUI database of the Bluetooth device
-     * address. This function will need a valid and up-to-date oui.txt from
-     * the IEEE. This value will be different from the manufacturer string in
-     * the most cases.
-     * If the oui.txt file is not present or the OUI part of the Bluetooth
-     * address is not listed, it should return the string "OUI %s" where %s is
-     * the actual OUI.
-     *
-     * Example: "Apple Computer"
-     *
-     * @return company name
-     */
-    public synchronized String getCompany() {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        return getCompanyNative();
-    }
-    private native String getCompanyNative();
-
-    /**
-     * Like getVersion(), but for a remote device.
-     *
-     * @param address The Bluetooth address of the remote device.
-     *
-     * @return remote-device Bluetooth version
-     *
-     * @see #getVersion
-     */
-    public synchronized String getRemoteVersion(String address) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return null;
+    /*package*/ synchronized String getRemoteDeviceProperty(String address, String property) {
+        Map<String, String> properties = mRemoteDeviceProperties.get(address);
+        if (properties != null) {
+            return properties.get(property);
+        } else {
+            // Query for remote device properties, again.
+            // We will need to reload the cache when we switch Bluetooth on / off
+            // or if we crash.
+            String objectPath = getObjectPathFromAddress(address);
+            String propValues[] = (String [])getDevicePropertiesNative(objectPath);
+            if (propValues != null) {
+                addRemoteDeviceProperties(address, propValues);
+                return getRemoteDeviceProperty(address, property);
+            }
         }
-        return getRemoteVersionNative(address);
+        Log.e(TAG, "getRemoteDeviceProperty: " + property + "not present:" + address);
+        return null;
     }
-    private native String getRemoteVersionNative(String address);
 
-    /**
-     * Like getRevision(), but for a remote device.
-     *
-     * @param address The Bluetooth address of the remote device.
-     *
-     * @return remote-device HCI revision
-     *
-     * @see #getRevision
-     */
-    public synchronized String getRemoteRevision(String address) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return null;
+    /* package */ synchronized void addRemoteDeviceProperties(String address, String[] properties) {
+        /*
+         * We get a DeviceFound signal every time RSSI changes or name changes.
+         * Don't create a new Map object every time */
+        Map<String, String> propertyValues = mRemoteDeviceProperties.get(address);
+        if (propertyValues != null) {
+            propertyValues.clear();
+        } else {
+            propertyValues = new HashMap<String, String>();
         }
-        return getRemoteRevisionNative(address);
-    }
-    private native String getRemoteRevisionNative(String address);
 
-    /**
-     * Like getManufacturer(), but for a remote device.
-     *
-     * @param address The Bluetooth address of the remote device.
-     *
-     * @return remote-device Bluetooth chip manufacturer
-     *
-     * @see #getManufacturer
-     */
-    public synchronized String getRemoteManufacturer(String address) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return null;
+        for (int i = 0; i < properties.length; i++) {
+            String name = properties[i];
+            String newValue;
+            int len;
+            if (name == null) {
+                Log.e(TAG, "Error: Remote Device Property at index" + i + "is null");
+                continue;
+            }
+            if (name.equals("UUIDs") || name.equals("Nodes")) {
+                len = Integer.valueOf(properties[++i]);
+                if (len != 0)
+                    newValue = "";
+                else
+                    newValue = null;
+                for (int j = 0; j < len; j++) {
+                    newValue += properties[++i] + ",";
+                }
+            } else {
+                newValue = properties[++i];
+            }
+            propertyValues.put(name, newValue);
         }
-        return getRemoteManufacturerNative(address);
+        mRemoteDeviceProperties.put(address, propertyValues);
     }
-    private native String getRemoteManufacturerNative(String address);
 
-    /**
-     * Like getCompany(), but for a remote device.
-     *
-     * @param address The Bluetooth address of the remote device.
-     *
-     * @return remote-device company
-     *
-     * @see #getCompany
-     */
-    public synchronized String getRemoteCompany(String address) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return null;
+    /* package */ void removeRemoteDeviceProperties(String address) {
+        mRemoteDeviceProperties.remove(address);
+    }
+
+    /* package */ synchronized void setRemoteDeviceProperty(String address, String name,
+                                                              String value) {
+        Map <String, String> propVal = mRemoteDeviceProperties.get(address);
+        if (propVal != null) {
+            propVal.put(name, value);
+            mRemoteDeviceProperties.put(address, propVal);
+        } else {
+            Log.e(TAG, "setRemoteDeviceProperty for a device not in cache:" + address);
         }
-        return getRemoteCompanyNative(address);
     }
-    private native String getRemoteCompanyNative(String address);
 
     /**
-     * Returns the date and time when the specified remote device has been seen
-     * by a discover procedure.
-     * Example: "2006-02-08 12:00:00 GMT"
-     *
-     * @return a String with the timestamp.
-     */
-    public synchronized String lastSeen(String address) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return null;
-        }
-        return lastSeenNative(address);
-    }
-    private native String lastSeenNative(String address);
-
-    /**
-     * Returns the date and time when the specified remote device has last been
-     * connected to
-     * Example: "2006-02-08 12:00:00 GMT"
-     *
-     * @return a String with the timestamp.
-     */
-    public synchronized String lastUsed(String address) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return null;
-        }
-        return lastUsedNative(address);
-    }
-    private native String lastUsedNative(String address);
-
-    /**
-     * Gets the remote major, minor, and service classes encoded as a 32-bit
+     * Gets the remote major, minor classes encoded as a 32-bit
      * integer.
      *
      * Note: this value is retrieved from cache, because we get it during
@@ -968,120 +882,56 @@
      *
      * @return 32-bit integer encoding the remote major, minor, and service
      *         classes.
-     *
-     * @see #getRemoteMajorClass
-     * @see #getRemoteMinorClass
-     * @see #getRemoteServiceClasses
      */
     public synchronized int getRemoteClass(String address) {
         if (!BluetoothDevice.checkBluetoothAddress(address)) {
             mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
             return BluetoothClass.ERROR;
         }
-        return getRemoteClassNative(address);
+        String val = getRemoteDeviceProperty(address, "Class");
+        if (val == null)
+            return BluetoothClass.ERROR;
+        else {
+            return Integer.valueOf(val);
+        }
     }
-    private native int getRemoteClassNative(String address);
+
 
     /**
      * Gets the remote features encoded as bit mask.
      *
      * Note: This method may be obsoleted soon.
      *
-     * @return byte array of features.
+     * @return String array of 128bit UUIDs
      */
-    public synchronized byte[] getRemoteFeatures(String address) {
+    public synchronized String[] getRemoteUuids(String address) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
         if (!BluetoothDevice.checkBluetoothAddress(address)) {
             return null;
         }
-        return getRemoteFeaturesNative(address);
+        String value = getRemoteDeviceProperty(address, "UUIDs");
+        String[] uuids = null;
+        // The UUIDs are stored as a "," separated string.
+        if (value != null)
+             uuids = value.split(",");
+        return uuids;
     }
-    private native byte[] getRemoteFeaturesNative(String address);
 
     /**
-     * This method and {@link #getRemoteServiceRecord} query the SDP service
-     * on a remote device.  They do not interpret the data, but simply return
-     * it raw to the user.  To read more about SDP service handles and records,
-     * consult the Bluetooth core documentation (www.bluetooth.com).
+     * Gets the rfcomm channel associated with the UUID.
      *
-     * @param address Bluetooth address of remote device.
-     * @param match a String match to narrow down the service-handle search.
-     *        The only supported value currently is "hsp" for the headset
-     *        profile.  To retrieve all service handles, simply pass an empty
-     *        match string.
+     * @param address Address of the remote device
+     * @param uuid UUID of the service attribute
      *
-     * @return all service handles corresponding to the string match.
-     *
-     * @see #getRemoteServiceRecord
+     * @return rfcomm channel associated with the service attribute
      */
-    public synchronized int[] getRemoteServiceHandles(String address, String match) {
+    public int getRemoteServiceChannel(String address, String uuid) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
         if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return null;
+            return BluetoothError.ERROR_IPC;
         }
-        if (match == null) {
-            match = "";
-        }
-        return getRemoteServiceHandlesNative(address, match);
+        return getDeviceServiceChannelNative(getObjectPathFromAddress(address), uuid, 0x0004);
     }
-    private native int[] getRemoteServiceHandlesNative(String address, String match);
-
-    /**
-     * This method retrieves the service records corresponding to a given
-     * service handle (method {@link #getRemoteServiceHandles} retrieves the
-     * service handles.)
-     *
-     * This method and {@link #getRemoteServiceHandles} do not interpret their
-     * data, but simply return it raw to the user.  To read more about SDP
-     * service handles and records, consult the Bluetooth core documentation
-     * (www.bluetooth.com).
-     *
-     * @param address Bluetooth address of remote device.
-     * @param handle Service handle returned by {@link #getRemoteServiceHandles}
-     *
-     * @return a byte array of all service records corresponding to the
-     *         specified service handle.
-     *
-     * @see #getRemoteServiceHandles
-     */
-    public synchronized byte[] getRemoteServiceRecord(String address, int handle) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return null;
-        }
-        return getRemoteServiceRecordNative(address, handle);
-    }
-    private native byte[] getRemoteServiceRecordNative(String address, int handle);
-
-    private static final int MAX_OUTSTANDING_ASYNC = 32;
-
-    // AIDL does not yet support short's
-    public synchronized boolean getRemoteServiceChannel(String address, int uuid16,
-            IBluetoothDeviceCallback callback) {
-        mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
-        if (!BluetoothDevice.checkBluetoothAddress(address)) {
-            return false;
-        }
-        HashMap<String, IBluetoothDeviceCallback> callbacks =
-            mEventLoop.getRemoteServiceChannelCallbacks();
-        if (callbacks.containsKey(address)) {
-            Log.w(TAG, "SDP request already in progress for " + address);
-            return false;
-        }
-        // Protect from malicious clients - only allow 32 bonding requests per minute.
-        if (callbacks.size() > MAX_OUTSTANDING_ASYNC) {
-            Log.w(TAG, "Too many outstanding SDP requests, dropping request for " + address);
-            return false;
-        }
-        callbacks.put(address, callback);
-
-        if (!getRemoteServiceChannelNative(address, (short)uuid16)) {
-            callbacks.remove(address);
-            return false;
-        }
-        return true;
-    }
-    private native boolean getRemoteServiceChannelNative(String address, short uuid16);
 
     public synchronized boolean setPin(String address, byte[] pin) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
@@ -1108,9 +958,39 @@
         }
         return setPinNative(address, pinString, data.intValue());
     }
-    private native boolean setPinNative(String address, String pin, int nativeData);
 
-    public synchronized boolean cancelPin(String address) {
+    public synchronized boolean setPasskey(String address, int passkey) {
+        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
+                                                "Need BLUETOOTH_ADMIN permission");
+        if (passkey < 0 || passkey > 999999 || !BluetoothDevice.checkBluetoothAddress(address)) {
+            return false;
+        }
+        address = address.toUpperCase();
+        Integer data = mEventLoop.getPasskeyAgentRequestData().remove(address);
+        if (data == null) {
+            Log.w(TAG, "setPasskey(" + address + ") called but no native data available, " +
+                  "ignoring. Maybe the PasskeyAgent Request was cancelled by the remote device" +
+                  " or by bluez.\n");
+            return false;
+        }
+        return setPasskeyNative(address, passkey, data.intValue());
+    }
+
+    public synchronized boolean setPairingConfirmation(String address, boolean confirm) {
+        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
+                                                "Need BLUETOOTH_ADMIN permission");
+        address = address.toUpperCase();
+        Integer data = mEventLoop.getPasskeyAgentRequestData().remove(address);
+        if (data == null) {
+            Log.w(TAG, "setPasskey(" + address + ") called but no native data available, " +
+                  "ignoring. Maybe the PasskeyAgent Request was cancelled by the remote device" +
+                  " or by bluez.\n");
+            return false;
+        }
+        return setPairingConfirmationNative(address, confirm, data.intValue());
+    }
+
+    public synchronized boolean cancelPairingUserInput(String address) {
         mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
                                                 "Need BLUETOOTH_ADMIN permission");
         if (!BluetoothDevice.checkBluetoothAddress(address)) {
@@ -1119,14 +999,13 @@
         address = address.toUpperCase();
         Integer data = mEventLoop.getPasskeyAgentRequestData().remove(address);
         if (data == null) {
-            Log.w(TAG, "cancelPin(" + address + ") called but no native data available, " +
-                  "ignoring. Maybe the PasskeyAgent Request was already cancelled by the remote " +
-                  "or by bluez.\n");
+            Log.w(TAG, "cancelUserInputNative(" + address + ") called but no native data " +
+                "available, ignoring. Maybe the PasskeyAgent Request was already cancelled " +
+                "by the remote or by bluez.\n");
             return false;
         }
-        return cancelPinNative(address, data.intValue());
+        return cancelPairingUserInputNative(address, data.intValue());
     }
-    private native boolean cancelPinNative(String address, int natveiData);
 
     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
         @Override
@@ -1190,20 +1069,22 @@
 
         BluetoothHeadset headset = new BluetoothHeadset(mContext, null);
 
-        String[] addresses = listRemoteDevices();
-
         pw.println("\n--Known devices--");
-        for (String address : addresses) {
+        for (String address : mRemoteDeviceProperties.keySet()) {
             pw.printf("%s %10s (%d) %s\n", address,
                        toBondStateString(mBondState.getBondState(address)),
                        mBondState.getAttempt(address),
                        getRemoteName(address));
         }
 
-        addresses = listAclConnections();
+        String value = getProperty("Devices");
+        String []devicesObjectPath = null;
+        if (value != null) {
+            devicesObjectPath = value.split(",");
+        }
         pw.println("\n--ACL connected devices--");
-        for (String address : addresses) {
-            pw.println(address);
+        for (String device : devicesObjectPath) {
+            pw.println(getAddressFromObjectPath(device));
         }
 
         // Rather not do this from here, but no-where else and I need this
@@ -1229,20 +1110,13 @@
         headset.close();
     }
 
-    /* package */ static int bluezStringToScanMode(String mode) {
-        if (mode == null) {
-            return BluetoothError.ERROR;
-        }
-        mode = mode.toLowerCase();
-        if (mode.equals("off")) {
-            return BluetoothDevice.SCAN_MODE_NONE;
-        } else if (mode.equals("connectable")) {
-            return BluetoothDevice.SCAN_MODE_CONNECTABLE;
-        } else if (mode.equals("discoverable")) {
+    /* package */ static int bluezStringToScanMode(boolean pairable, boolean discoverable) {
+        if (pairable && discoverable)
             return BluetoothDevice.SCAN_MODE_CONNECTABLE_DISCOVERABLE;
-        } else {
-            return BluetoothError.ERROR;
-        }
+        else if (pairable && !discoverable)
+            return BluetoothDevice.SCAN_MODE_CONNECTABLE;
+        else
+            return BluetoothDevice.SCAN_MODE_NONE;
     }
 
     /* package */ static String scanModeToBluezString(int mode) {
@@ -1257,7 +1131,70 @@
         return null;
     }
 
+    /*package*/ String getAddressFromObjectPath(String objectPath) {
+        String adapterObjectPath = getProperty("ObjectPath");
+        if (adapterObjectPath == null || objectPath == null) {
+            Log.e(TAG, "getAddressFromObjectPath: AdpaterObjectPath:" + adapterObjectPath +
+                    "  or deviceObjectPath:" + objectPath + " is null");
+            return null;
+        }
+        if (!objectPath.startsWith(adapterObjectPath)) {
+            Log.e(TAG, "getAddressFromObjectPath: AdpaterObjectPath:" + adapterObjectPath +
+                    "  is not a prefix of deviceObjectPath:" + objectPath +
+                    "bluetoothd crashed ?");
+            return null;
+        }
+        String address = objectPath.substring(adapterObjectPath.length());
+        if (address != null) return address.replace('_', ':');
+
+        Log.e(TAG, "getAddressFromObjectPath: Address being returned is null");
+        return null;
+    }
+
+    /*package*/ String getObjectPathFromAddress(String address) {
+        String path = getProperty("ObjectPath");
+        if (path == null) {
+            Log.e(TAG, "Error: Object Path is null");
+            return null;
+        }
+        path = path + address.replace(":", "_");
+        return path;
+    }
+
     private static void log(String msg) {
         Log.d(TAG, msg);
     }
+
+    private native static void classInitNative();
+    private native void initializeNativeDataNative();
+    private native boolean setupNativeDataNative();
+    private native boolean tearDownNativeDataNative();
+    private native void cleanupNativeDataNative();
+    private native String getAdapterPathNative();
+
+    private native int isEnabledNative();
+    private native int enableNative();
+    private native int disableNative();
+
+    private native Object[] getAdapterPropertiesNative();
+    private native Object[] getDevicePropertiesNative(String objectPath);
+    private native boolean setAdapterPropertyStringNative(String key, String value);
+    private native boolean setAdapterPropertyIntegerNative(String key, int value);
+    private native boolean setAdapterPropertyBooleanNative(String key, int value);
+
+    private native boolean startDiscoveryNative();
+    private native boolean stopDiscoveryNative();
+
+    private native boolean createPairedDeviceNative(String address, int timeout_ms);
+    private native boolean cancelDeviceCreationNative(String address);
+    private native boolean removeDeviceNative(String objectPath);
+    private native int getDeviceServiceChannelNative(String objectPath, String uuid,
+            int attributeId);
+
+    private native boolean cancelPairingUserInputNative(String address, int nativeData);
+    private native boolean setPinNative(String address, String pin, int nativeData);
+    private native boolean setPasskeyNative(String address, int passkey, int nativeData);
+    private native boolean setPairingConfirmationNative(String address, boolean confirm,
+            int nativeData);
+
 }
diff --git a/core/java/android/server/BluetoothEventLoop.java b/core/java/android/server/BluetoothEventLoop.java
index 8cc229b..dc84d1f 100644
--- a/core/java/android/server/BluetoothEventLoop.java
+++ b/core/java/android/server/BluetoothEventLoop.java
@@ -21,15 +21,15 @@
 import android.bluetooth.BluetoothDevice;
 import android.bluetooth.BluetoothError;
 import android.bluetooth.BluetoothIntent;
-import android.bluetooth.IBluetoothDeviceCallback;
+import android.bluetooth.BluetoothUuid;
 import android.content.Context;
 import android.content.Intent;
 import android.os.Handler;
 import android.os.Message;
-import android.os.RemoteException;
 import android.util.Log;
 
 import java.util.HashMap;
+import java.util.UUID;
 
 /**
  * TODO: Move this to
@@ -47,7 +47,6 @@
     private boolean mStarted;
     private boolean mInterrupted;
     private final HashMap<String, Integer> mPasskeyAgentRequestData;
-    private final HashMap<String, IBluetoothDeviceCallback> mGetRemoteServiceChannelCallbacks;
     private final BluetoothDeviceService mBluetoothService;
     private final Context mContext;
 
@@ -89,10 +88,8 @@
         mBluetoothService = bluetoothService;
         mContext = context;
         mPasskeyAgentRequestData = new HashMap();
-        mGetRemoteServiceChannelCallbacks = new HashMap();
         initializeNativeDataNative();
     }
-    private native void initializeNativeDataNative();
 
     protected void finalize() throws Throwable {
         try {
@@ -101,20 +98,11 @@
             super.finalize();
         }
     }
-    private native void cleanupNativeDataNative();
 
-    /* pacakge */ HashMap<String, IBluetoothDeviceCallback> getRemoteServiceChannelCallbacks() {
-        return mGetRemoteServiceChannelCallbacks;
-    }
-
-    /* pacakge */ HashMap<String, Integer> getPasskeyAgentRequestData() {
+    /* package */ HashMap<String, Integer> getPasskeyAgentRequestData() {
         return mPasskeyAgentRequestData;
     }
 
-    private native void startEventLoopNative();
-    private native void stopEventLoopNative();
-    private native boolean isEventLoopRunningNative();
-
     /* package */ void start() {
 
         if (!isEventLoopRunningNative()) {
@@ -134,79 +122,39 @@
         return isEventLoopRunningNative();
     }
 
-    /*package*/ void onModeChanged(String bluezMode) {
-        int mode = BluetoothDeviceService.bluezStringToScanMode(bluezMode);
-        if (mode >= 0) {
-            Intent intent = new Intent(BluetoothIntent.SCAN_MODE_CHANGED_ACTION);
-            intent.putExtra(BluetoothIntent.SCAN_MODE, mode);
-            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
+    private void onDeviceFound(String address, String[] properties) {
+        if (properties == null) {
+            Log.e(TAG, "ERROR: Remote device properties are null");
+            return;
+        }
+        mBluetoothService.addRemoteDeviceProperties(address, properties);
+        String rssi = mBluetoothService.getRemoteDeviceProperty(address, "RSSI");
+        String classValue = mBluetoothService.getRemoteDeviceProperty(address, "Class");
+        String name = mBluetoothService.getRemoteDeviceProperty(address, "Name");
+
+        if (rssi != null && classValue != null) {
+            Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_FOUND_ACTION);
+            intent.putExtra(BluetoothIntent.ADDRESS, address);
+            intent.putExtra(BluetoothIntent.CLASS, Integer.valueOf(classValue));
+            intent.putExtra(BluetoothIntent.RSSI, (short)Integer.valueOf(rssi).intValue());
+            intent.putExtra(BluetoothIntent.NAME, name);
+
             mContext.sendBroadcast(intent, BLUETOOTH_PERM);
+        } else {
+            log ("RSSI: " + rssi + " or ClassValue: " + classValue +
+                    " for remote device: " + address + " is null");
         }
     }
 
-    private void onDiscoveryStarted() {
-        mBluetoothService.setIsDiscovering(true);
-        Intent intent = new Intent(BluetoothIntent.DISCOVERY_STARTED_ACTION);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
-    }
-    private void onDiscoveryCompleted() {
-        mBluetoothService.setIsDiscovering(false);
-        Intent intent = new Intent(BluetoothIntent.DISCOVERY_COMPLETED_ACTION);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
-    }
+    private void onDeviceDisappeared(String address) {
+        mBluetoothService.removeRemoteDeviceProperties(address);
 
-    private void onRemoteDeviceFound(String address, int deviceClass, short rssi) {
-        Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_FOUND_ACTION);
-        intent.putExtra(BluetoothIntent.ADDRESS, address);
-        intent.putExtra(BluetoothIntent.CLASS, deviceClass);
-        intent.putExtra(BluetoothIntent.RSSI, rssi);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
-    }
-    private void onRemoteDeviceDisappeared(String address) {
         Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_DISAPPEARED_ACTION);
         intent.putExtra(BluetoothIntent.ADDRESS, address);
         mContext.sendBroadcast(intent, BLUETOOTH_PERM);
     }
-    private void onRemoteClassUpdated(String address, int deviceClass) {
-        Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_CLASS_UPDATED_ACTION);
-        intent.putExtra(BluetoothIntent.ADDRESS, address);
-        intent.putExtra(BluetoothIntent.CLASS, deviceClass);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
-    }
-    private void onRemoteDeviceConnected(String address) {
-        Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_CONNECTED_ACTION);
-        intent.putExtra(BluetoothIntent.ADDRESS, address);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
-    }
-    private void onRemoteDeviceDisconnectRequested(String address) {
-        Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_DISCONNECT_REQUESTED_ACTION);
-        intent.putExtra(BluetoothIntent.ADDRESS, address);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
-    }
-    private void onRemoteDeviceDisconnected(String address) {
-        Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_DISCONNECTED_ACTION);
-        intent.putExtra(BluetoothIntent.ADDRESS, address);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
-    }
-    private void onRemoteNameUpdated(String address, String name) {
-        Intent intent = new Intent(BluetoothIntent.REMOTE_NAME_UPDATED_ACTION);
-        intent.putExtra(BluetoothIntent.ADDRESS, address);
-        intent.putExtra(BluetoothIntent.NAME, name);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
-    }
-    private void onRemoteNameFailed(String address) {
-        Intent intent = new Intent(BluetoothIntent.REMOTE_NAME_FAILED_ACTION);
-        intent.putExtra(BluetoothIntent.ADDRESS, address);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
-    }
-    private void onRemoteNameChanged(String address, String name) {
-        Intent intent = new Intent(BluetoothIntent.REMOTE_NAME_UPDATED_ACTION);
-        intent.putExtra(BluetoothIntent.ADDRESS, address);
-        intent.putExtra(BluetoothIntent.NAME, name);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
-    }
 
-    private void onCreateBondingResult(String address, int result) {
+    private void onCreatePairedDeviceResult(String address, int result) {
         address = address.toUpperCase();
         if (result == BluetoothError.SUCCESS) {
             mBluetoothService.getBondState().setBondState(address, BluetoothDevice.BOND_BONDED);
@@ -259,31 +207,163 @@
         mBluetoothService.getBondState().attempt(address);
     }
 
-    private void onBondingCreated(String address) {
-        mBluetoothService.getBondState().setBondState(address.toUpperCase(),
-                                                      BluetoothDevice.BOND_BONDED);
+    private void onDeviceCreated(String deviceObjectPath) {
+        // do nothing.
+        return;
     }
 
-    private void onBondingRemoved(String address) {
-        mBluetoothService.getBondState().setBondState(address.toUpperCase(),
-                BluetoothDevice.BOND_NOT_BONDED, BluetoothDevice.UNBOND_REASON_REMOVED);
+    private void onDeviceRemoved(String deviceObjectPath) {
+        String address = mBluetoothService.getAddressFromObjectPath(deviceObjectPath);
+        if (address != null)
+            mBluetoothService.getBondState().setBondState(address.toUpperCase(),
+                    BluetoothDevice.BOND_NOT_BONDED, BluetoothDevice.UNBOND_REASON_REMOVED);
     }
 
-    private void onNameChanged(String name) {
-        Intent intent = new Intent(BluetoothIntent.NAME_CHANGED_ACTION);
-        intent.putExtra(BluetoothIntent.NAME, name);
-        mContext.sendBroadcast(intent, BLUETOOTH_PERM);
+    /*package*/ void onPropertyChanged(String[] propValues) {
+        String name = propValues[0];
+        if (name.equals("Name")) {
+            Intent intent = new Intent(BluetoothIntent.NAME_CHANGED_ACTION);
+            intent.putExtra(BluetoothIntent.NAME, propValues[1]);
+            mContext.sendBroadcast(intent, BLUETOOTH_PERM);
+            mBluetoothService.setProperty(name, propValues[1]);
+        } else if (name.equals("Pairable") || name.equals("Discoverable")) {
+            String pairable = name.equals("Pairable") ? propValues[1] :
+                mBluetoothService.getProperty("Pairable");
+            String discoverable = name.equals("Discoverable") ? propValues[1] :
+                mBluetoothService.getProperty("Discoverable");
+
+            // This shouldn't happen, unless Adapter Properties are null.
+            if (pairable == null || discoverable == null)
+                return;
+
+            int mode = BluetoothDeviceService.bluezStringToScanMode(
+                    pairable.equals("true"),
+                    discoverable.equals("true"));
+            if (mode >= 0) {
+                Intent intent = new Intent(BluetoothIntent.SCAN_MODE_CHANGED_ACTION);
+                intent.putExtra(BluetoothIntent.SCAN_MODE, mode);
+                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
+                mContext.sendBroadcast(intent, BLUETOOTH_PERM);
+            }
+            mBluetoothService.setProperty(name, propValues[1]);
+        } else if (name.equals("Discovering")) {
+            Intent intent;
+            if (propValues[1].equals("true")) {
+                mBluetoothService.setIsDiscovering(true);
+                intent = new Intent(BluetoothIntent.DISCOVERY_STARTED_ACTION);
+            } else {
+                // Stop the discovery.
+                mBluetoothService.cancelDiscovery();
+                mBluetoothService.setIsDiscovering(false);
+                intent = new Intent(BluetoothIntent.DISCOVERY_COMPLETED_ACTION);
+            }
+            mContext.sendBroadcast(intent, BLUETOOTH_PERM);
+            mBluetoothService.setProperty(name, propValues[1]);
+        } else if (name.equals("Devices")) {
+            String value = null;
+            int len = Integer.valueOf(propValues[1]);
+            if (len > 0) {
+                value = "";
+                for (int i = 2; i < propValues.length; i++) {
+                    value = value + propValues[i] + ',';
+                }
+            }
+            mBluetoothService.setProperty(name, value);
+        } else if (name.equals("Powered")) {
+            // bluetoothd has restarted, re-read all our properties.
+            // Note: bluez only sends this property change when it restarts.
+            if (propValues[1].equals("true"))
+                onRestartRequired();
+        }
     }
 
-    private void onPasskeyAgentRequest(String address, int nativeData) {
+    private void onDevicePropertyChanged(String deviceObjectPath, String[] propValues) {
+        String name = propValues[0];
+        String address = mBluetoothService.getAddressFromObjectPath(deviceObjectPath);
+        if (address == null) {
+            Log.e(TAG, "onDevicePropertyChanged: Address of the remote device in null");
+            return;
+        }
+        if (name.equals("Name")) {
+            Intent intent = new Intent(BluetoothIntent.REMOTE_NAME_UPDATED_ACTION);
+            intent.putExtra(BluetoothIntent.ADDRESS, address);
+            intent.putExtra(BluetoothIntent.NAME, propValues[1]);
+            mContext.sendBroadcast(intent, BLUETOOTH_PERM);
+            mBluetoothService.setRemoteDeviceProperty(address, name, propValues[1]);
+        } else if (name.equals("Class")) {
+            Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_CLASS_UPDATED_ACTION);
+            intent.putExtra(BluetoothIntent.ADDRESS, address);
+            intent.putExtra(BluetoothIntent.CLASS, propValues[1]);
+            mContext.sendBroadcast(intent, BLUETOOTH_PERM);
+            mBluetoothService.setRemoteDeviceProperty(address, name, propValues[1]);
+        } else if (name.equals("Connected")) {
+            Intent intent = null;
+            if (propValues[1].equals("true")) {
+                intent = new Intent(BluetoothIntent.REMOTE_DEVICE_CONNECTED_ACTION);
+            } else {
+                intent = new Intent(BluetoothIntent.REMOTE_DEVICE_DISCONNECTED_ACTION);
+            }
+            intent.putExtra(BluetoothIntent.ADDRESS, address);
+            mContext.sendBroadcast(intent, BLUETOOTH_PERM);
+            mBluetoothService.setRemoteDeviceProperty(address, name, propValues[1]);
+        } else if (name.equals("UUIDs")) {
+            String uuid = null;
+            int len = Integer.valueOf(propValues[1]);
+            if (len > 0) {
+                uuid = "";
+                for (int i = 2; i < propValues.length; i++) {
+                    uuid = uuid + propValues[i] + ",";
+                }
+            }
+            mBluetoothService.setRemoteDeviceProperty(address, name, uuid);
+        }
+    }
+
+    private String checkPairingRequestAndGetAddress(String objectPath, int nativeData) {
+        String address = mBluetoothService.getAddressFromObjectPath(objectPath);
+        if (address == null) {
+            Log.e(TAG, "Unable to get device address in checkPairingRequestAndGetAddress, " +
+                  "returning null");
+            return null;
+        }
         address = address.toUpperCase();
         mPasskeyAgentRequestData.put(address, new Integer(nativeData));
 
         if (mBluetoothService.getBluetoothState() == BluetoothDevice.BLUETOOTH_STATE_TURNING_OFF) {
             // shutdown path
-            mBluetoothService.cancelPin(address);
-            return;
+            mBluetoothService.cancelPairingUserInput(address);
+            return null;
         }
+        return address;
+    }
+
+    private void onRequestConfirmation(String objectPath, int passkey, int nativeData) {
+        String address = checkPairingRequestAndGetAddress(objectPath, nativeData);
+        if (address == null) return;
+
+        Intent intent = new Intent(BluetoothIntent.PAIRING_REQUEST_ACTION);
+        intent.putExtra(BluetoothIntent.ADDRESS, address);
+        intent.putExtra(BluetoothIntent.PASSKEY, passkey);
+        intent.putExtra(BluetoothIntent.PAIRING_VARIANT,
+                BluetoothDevice.PAIRING_VARIANT_CONFIRMATION);
+        mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
+        return;
+    }
+
+    private void onRequestPasskey(String objectPath, int nativeData) {
+        String address = checkPairingRequestAndGetAddress(objectPath, nativeData);
+        if (address == null) return;
+
+        Intent intent = new Intent(BluetoothIntent.PAIRING_REQUEST_ACTION);
+        intent.putExtra(BluetoothIntent.ADDRESS, address);
+        intent.putExtra(BluetoothIntent.PAIRING_VARIANT, BluetoothDevice.PAIRING_VARIANT_PASSKEY);
+        mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
+        return;
+    }
+
+    private void onRequestPinCode(String objectPath, int nativeData) {
+        String address = checkPairingRequestAndGetAddress(objectPath, nativeData);
+        if (address == null) return;
 
         if (mBluetoothService.getBondState().getBondState(address) ==
                 BluetoothDevice.BOND_BONDING) {
@@ -308,22 +388,21 @@
         }
         Intent intent = new Intent(BluetoothIntent.PAIRING_REQUEST_ACTION);
         intent.putExtra(BluetoothIntent.ADDRESS, address);
+        intent.putExtra(BluetoothIntent.PAIRING_VARIANT, BluetoothDevice.PAIRING_VARIANT_PIN);
         mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
+        return;
     }
 
-    private void onPasskeyAgentCancel(String address) {
-        address = address.toUpperCase();
-        mBluetoothService.cancelPin(address);
-        Intent intent = new Intent(BluetoothIntent.PAIRING_CANCEL_ACTION);
-        intent.putExtra(BluetoothIntent.ADDRESS, address);
-        mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
-        mBluetoothService.getBondState().setBondState(address, BluetoothDevice.BOND_NOT_BONDED,
-                                                      BluetoothDevice.UNBOND_REASON_AUTH_CANCELED);
-    }
+    private boolean onAgentAuthorize(String objectPath, String deviceUuid) {
+        String address = mBluetoothService.getAddressFromObjectPath(objectPath);
+        if (address == null) {
+            Log.e(TAG, "Unable to get device address in onAuthAgentAuthorize");
+            return false;
+        }
 
-    private boolean onAuthAgentAuthorize(String address, String service, String uuid) {
         boolean authorized = false;
-        if (mBluetoothService.isEnabled() && service.endsWith("service_audio")) {
+        UUID uuid = UUID.fromString(deviceUuid);
+        if (mBluetoothService.isEnabled() && BluetoothUuid.isAudioSink(uuid)) {
             BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
             authorized = a2dp.getSinkPriority(address) > BluetoothA2dp.PRIORITY_OFF;
             if (authorized) {
@@ -332,30 +411,21 @@
                 Log.i(TAG, "Rejecting incoming A2DP connection from " + address);
             }
         } else {
-            Log.i(TAG, "Rejecting incoming " + service + " connection from " + address);
+            Log.i(TAG, "Rejecting incoming " + deviceUuid + " connection from " + address);
         }
         return authorized;
     }
 
-    private void onAuthAgentCancel(String address, String service, String uuid) {
-        // We immediately response to DBUS Authorize() so this should not
-        // usually happen
-        log("onAuthAgentCancel(" + address + ", " + service + ", " + uuid + ")");
-    }
-
-    private void onGetRemoteServiceChannelResult(String address, int channel) {
-        IBluetoothDeviceCallback callback = mGetRemoteServiceChannelCallbacks.get(address);
-        if (callback != null) {
-            mGetRemoteServiceChannelCallbacks.remove(address);
-            try {
-                callback.onGetRemoteServiceChannelResult(address, channel);
-            } catch (RemoteException e) {}
-        }
+    private void onAgentCancel() {
+        Intent intent = new Intent(BluetoothIntent.PAIRING_CANCEL_ACTION);
+        mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
+        return;
     }
 
     private void onRestartRequired() {
         if (mBluetoothService.isEnabled()) {
-            Log.e(TAG, "*** A serious error occured (did hcid crash?) - restarting Bluetooth ***");
+            Log.e(TAG, "*** A serious error occured (did bluetoothd crash?) - " +
+                       "restarting Bluetooth ***");
             mHandler.sendEmptyMessage(EVENT_RESTART_BLUETOOTH);
         }
     }
@@ -363,4 +433,10 @@
     private static void log(String msg) {
         Log.d(TAG, msg);
     }
+
+    private native void initializeNativeDataNative();
+    private native void startEventLoopNative();
+    private native void stopEventLoopNative();
+    private native boolean isEventLoopRunningNative();
+    private native void cleanupNativeDataNative();
 }
diff --git a/core/java/android/syncml/pim/vcard/ContactStruct.java b/core/java/android/syncml/pim/vcard/ContactStruct.java
index ecd719d..4b4c394 100644
--- a/core/java/android/syncml/pim/vcard/ContactStruct.java
+++ b/core/java/android/syncml/pim/vcard/ContactStruct.java
@@ -17,6 +17,7 @@
 package android.syncml.pim.vcard;
 
 import android.content.AbstractSyncableContentProvider;
+import android.content.ContentProviderOperation;
 import android.content.ContentResolver;
 import android.content.ContentUris;
 import android.content.ContentValues;
@@ -780,17 +781,16 @@
                 personId = ContentUris.parseId(personUri);
             }
         } else {
-            personUri = provider.nonTransactionalInsert(People.CONTENT_URI, contentValues);
+            personUri = provider.insert(People.CONTENT_URI, contentValues);
             if (personUri != null) {
                 personId = ContentUris.parseId(personUri);
                 ContentValues values = new ContentValues();
                 values.put(GroupMembership.PERSON_ID, personId);
                 values.put(GroupMembership.GROUP_ID, myContactsGroupId);
-                Uri resultUri = provider.nonTransactionalInsert(
-                        GroupMembership.CONTENT_URI, values);
+                Uri resultUri = provider.insert(GroupMembership.CONTENT_URI, values);
                 if (resultUri == null) {
                     Log.e(LOG_TAG, "Faild to insert the person to MyContact.");
-                    provider.nonTransactionalDelete(personUri, null, null);
+                    provider.delete(personUri, null, null);
                     personUri = null;
                 }
             }
@@ -830,7 +830,7 @@
                 if (resolver != null) {
                     phoneUri = resolver.insert(Phones.CONTENT_URI, values);
                 } else {
-                    phoneUri = provider.nonTransactionalInsert(Phones.CONTENT_URI, values);
+                    phoneUri = provider.insert(Phones.CONTENT_URI, values);
                 }
                 if (phoneData.isPrimary) {
                     primaryPhoneId = Long.parseLong(phoneUri.getLastPathSegment());
@@ -856,8 +856,7 @@
                 if (resolver != null) {
                     organizationUri = resolver.insert(Organizations.CONTENT_URI, values);
                 } else {
-                    organizationUri = provider.nonTransactionalInsert(
-                            Organizations.CONTENT_URI, values);
+                    organizationUri = provider.insert(Organizations.CONTENT_URI, values);
                 }
                 if (organizationData.isPrimary) {
                     primaryOrganizationId = Long.parseLong(organizationUri.getLastPathSegment());
@@ -883,8 +882,7 @@
                     if (resolver != null) {
                         emailUri = resolver.insert(ContactMethods.CONTENT_URI, values);
                     } else {
-                        emailUri = provider.nonTransactionalInsert(
-                                ContactMethods.CONTENT_URI, values);
+                        emailUri = provider.insert(ContactMethods.CONTENT_URI, values);
                     }
                     if (contactMethod.isPrimary) {
                         primaryEmailId = Long.parseLong(emailUri.getLastPathSegment());
@@ -893,8 +891,7 @@
                     if (resolver != null) {
                         resolver.insert(ContactMethods.CONTENT_URI, values);
                     } else {
-                        provider.nonTransactionalInsert(
-                                ContactMethods.CONTENT_URI, values);
+                        provider.insert(ContactMethods.CONTENT_URI, values);
                     }
                 }
             }
@@ -918,7 +915,7 @@
                     if (resolver != null) {
                         contentValuesArray.add(values);
                     } else {
-                        provider.nonTransactionalInsert(Extensions.CONTENT_URI, values);
+                        provider.insert(Extensions.CONTENT_URI, values);
                     }
                 }
             }
@@ -942,7 +939,7 @@
             if (resolver != null) {
                 resolver.update(personUri, values, null, null);
             } else {
-                provider.nonTransactionalUpdate(personUri, values, null, null);
+                provider.update(personUri, values, null, null);
             }
         }
     }
@@ -960,12 +957,12 @@
     public void pushIntoAbstractSyncableContentProvider(
             AbstractSyncableContentProvider provider, long myContactsGroupId) {
         boolean successful = false;
-        provider.beginTransaction();
+        provider.beginBatch();
         try {
             pushIntoContentProviderOrResolver(provider, myContactsGroupId);
             successful = true;
         } finally {
-            provider.endTransaction(successful);
+            provider.endBatch(successful);
         }
     }
     
diff --git a/core/java/android/text/format/DateUtils.java b/core/java/android/text/format/DateUtils.java
index 1a4eb699..9dd8ceb 100644
--- a/core/java/android/text/format/DateUtils.java
+++ b/core/java/android/text/format/DateUtils.java
@@ -25,7 +25,9 @@
 
 import java.util.Calendar;
 import java.util.Date;
+import java.util.Formatter;
 import java.util.GregorianCalendar;
+import java.util.Locale;
 import java.util.TimeZone;
 
 /**
@@ -1040,6 +1042,31 @@
 
     /**
      * Formats a date or a time range according to the local conventions.
+     * <p>
+     * Note that this is a convenience method. Using it involves creating an
+     * internal {@link java.util.Formatter} instance on-the-fly, which is
+     * somewhat costly in terms of memory and time. This is probably acceptable
+     * if you use the method only rarely, but if you rely on it for formatting a
+     * large number of dates, consider creating and reusing your own
+     * {@link java.util.Formatter} instance and use the version of
+     * {@link #formatDateRange(Context, long, long, int) formatDateRange}
+     * that takes a {@link java.util.Formatter}.
+     * 
+     * @param context the context is required only if the time is shown
+     * @param startMillis the start time in UTC milliseconds
+     * @param endMillis the end time in UTC milliseconds
+     * @param flags a bit mask of options See
+     * {@link #formatDateRange(Context, long, long, int) formatDateRange}
+     * @return a string containing the formatted date/time range.
+     */
+    public static String formatDateRange(Context context, long startMillis,
+            long endMillis, int flags) {
+        Formatter f = new Formatter(new StringBuilder(50), Locale.getDefault());
+        return formatDateRange(context, f, startMillis, endMillis, flags).toString();
+    }
+
+    /**
+     * Formats a date or a time range according to the local conventions.
      * 
      * <p>
      * Example output strings (date formats in these examples are shown using
@@ -1181,14 +1208,17 @@
      * instead of "December 31, 2008".
      * 
      * @param context the context is required only if the time is shown
+     * @param formatter the Formatter used for formatting the date range.
+     * Note: be sure to call setLength(0) on StringBuilder passed to
+     * the Formatter constructor unless you want the results to accumulate.
      * @param startMillis the start time in UTC milliseconds
      * @param endMillis the end time in UTC milliseconds
      * @param flags a bit mask of options
      *   
-     * @return a string containing the formatted date/time range.
+     * @return the formatter with the formatted date/time range appended to the string buffer.
      */
-    public static String formatDateRange(Context context, long startMillis,
-                long endMillis, int flags) {
+    public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
+            long endMillis, int flags) {
         Resources res = Resources.getSystem();
         boolean showTime = (flags & FORMAT_SHOW_TIME) != 0;
         boolean showWeekDay = (flags & FORMAT_SHOW_WEEKDAY) != 0;
@@ -1423,8 +1453,7 @@
 
         if (noMonthDay && startMonthNum == endMonthNum) {
             // Example: "January, 2008"
-            String startDateString = startDate.format(defaultDateFormat);
-            return startDateString;
+            return formatter.format("%s", startDate.format(defaultDateFormat));
         }
 
         if (startYear != endYear || noMonthDay) {
@@ -1436,10 +1465,9 @@
 
             // The values that are used in a fullFormat string are specified
             // by position.
-            dateRange = String.format(fullFormat,
+            return formatter.format(fullFormat,
                     startWeekDayString, startDateString, startTimeString,
                     endWeekDayString, endDateString, endTimeString);
-            return dateRange;
         }
 
         // Get the month, day, and year strings for the start and end dates
@@ -1476,12 +1504,11 @@
 
             // The values that are used in a fullFormat string are specified
             // by position.
-            dateRange = String.format(fullFormat,
+            return formatter.format(fullFormat,
                     startWeekDayString, startMonthString, startMonthDayString,
                     startYearString, startTimeString,
                     endWeekDayString, endMonthString, endMonthDayString,
                     endYearString, endTimeString);
-            return dateRange;
         }
 
         if (startDay != endDay) {
@@ -1496,12 +1523,11 @@
 
             // The values that are used in a fullFormat string are specified
             // by position.
-            dateRange = String.format(fullFormat,
+            return formatter.format(fullFormat,
                     startWeekDayString, startMonthString, startMonthDayString,
                     startYearString, startTimeString,
                     endWeekDayString, endMonthString, endMonthDayString,
                     endYearString, endTimeString);
-            return dateRange;
         }
 
         // Same start and end day
@@ -1522,6 +1548,7 @@
             } else {
                 // Example: "10:00 - 11:00 am"
                 String timeFormat = res.getString(com.android.internal.R.string.time1_time2);
+                // Don't use the user supplied Formatter because the result will pollute the buffer.
                 timeString = String.format(timeFormat, startTimeString, endTimeString);
             }
         }
@@ -1545,7 +1572,7 @@
                     fullFormat = res.getString(com.android.internal.R.string.time_date);
                 } else {
                     // Example: "Oct 9"
-                    return dateString;
+                    return formatter.format("%s", dateString);
                 }
             }
         } else if (showWeekDay) {
@@ -1554,16 +1581,15 @@
                 fullFormat = res.getString(com.android.internal.R.string.time_wday);
             } else {
                 // Example: "Tue"
-                return startWeekDayString;
+                return formatter.format("%s", startWeekDayString);
             }
         } else if (showTime) {
-            return timeString;
+            return formatter.format("%s", timeString);
         }
 
         // The values that are used in a fullFormat string are specified
         // by position.
-        dateRange = String.format(fullFormat, timeString, startWeekDayString, dateString);
-        return dateRange;
+        return formatter.format(fullFormat, timeString, startWeekDayString, dateString);
     }
 
     /**
diff --git a/core/java/android/util/EventLog.java b/core/java/android/util/EventLog.java
index 24b4f73..0f0be79 100644
--- a/core/java/android/util/EventLog.java
+++ b/core/java/android/util/EventLog.java
@@ -73,7 +73,7 @@
  *   </ul>
  * </li>
  * <li> '\n': 1 byte - an automatically generated newline, used to help detect and recover from log
- *                     corruption and enable stansard unix tools like grep, tail and wc to operate
+ *                     corruption and enable standard unix tools like grep, tail and wc to operate
  *                     on event logs. </li>
  * </ul>
  *
@@ -192,17 +192,21 @@
             return decodeObject();
         }
 
+        public byte[] getRawData() {
+            return mBuffer.array();
+        }
+
         /** @return the loggable item at the current position in mBuffer. */
         private Object decodeObject() {
             if (mBuffer.remaining() < 1) return null;
             switch (mBuffer.get()) {
             case INT:
                 if (mBuffer.remaining() < 4) return null;
-                return mBuffer.getInt();
+                return (Integer) mBuffer.getInt();
 
             case LONG:
                 if (mBuffer.remaining() < 8) return null;
-                return mBuffer.getLong();
+                return (Long) mBuffer.getLong();
 
             case STRING:
                 try {
@@ -285,4 +289,13 @@
      */
     public static native void readEvents(int[] tags, Collection<Event> output)
             throws IOException;
+
+    /**
+     * Read events from a file.
+     * @param path to read from
+     * @param output container to add events into
+     * @throws IOException if something goes wrong reading events
+     */
+    public static native void readEvents(String path, Collection<Event> output)
+            throws IOException;
 }
diff --git a/core/java/android/util/Pair.java b/core/java/android/util/Pair.java
new file mode 100644
index 0000000..bf25306
--- /dev/null
+++ b/core/java/android/util/Pair.java
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+
+package android.util;
+
+/**
+ * Container to ease passing around a tuple of two objects. This object provides a sensible
+ * implementation of equals(), returning true if equals() is true on each of the contained
+ * objects.
+ */
+public class Pair<F, S> {
+    public final F first;
+    public final S second;
+
+    /**
+     * Constructor for a Pair. If either are null then equals() and hashCode() will throw
+     * a NullPointerException.
+     * @param first the first object in the Pair
+     * @param second the second object in the pair
+     */
+    public Pair(F first, S second) {
+        this.first = first;
+        this.second = second;
+    }
+
+    /**
+     * Checks the two objects for equality by delegating to their respective equals() methods.
+     * @param o the Pair to which this one is to be checked for equality
+     * @return true if the underlying objects of the Pair are both considered equals()
+     */
+    public boolean equals(Object o) {
+        if (o == this) return true;
+        if (!(o instanceof Pair)) return false;
+        final Pair<F, S> other;
+        try {
+            other = (Pair<F, S>) o;
+        } catch (ClassCastException e) {
+            return false;
+        }
+        return first.equals(other.first) && second.equals(other.second);
+    }
+
+    /**
+     * Compute a hash code using the hash codes of the underlying objects
+     * @return a hashcode of the Pair
+     */
+    public int hashCode() {
+        int result = 17;
+        result = 31 * result + first.hashCode();
+        result = 31 * result + second.hashCode();
+        return result;
+    }
+
+    /**
+     * Convenience method for creating an appropriately typed pair.
+     * @param a the first object in the Pair
+     * @param b the second object in the pair
+     * @return a Pair that is templatized with the types of a and b
+     */
+    public static <A, B> Pair <A, B> create(A a, B b) {
+        return new Pair<A, B>(a, b);
+    }
+}
diff --git a/core/java/android/view/HapticFeedbackConstants.java b/core/java/android/view/HapticFeedbackConstants.java
index 841066c..f936f65 100644
--- a/core/java/android/view/HapticFeedbackConstants.java
+++ b/core/java/android/view/HapticFeedbackConstants.java
@@ -24,9 +24,18 @@
 
     private HapticFeedbackConstants() {}
 
+    /**
+     * The user has performed a long press on an object that is resulting
+     * in an action being performed.
+     */
     public static final int LONG_PRESS = 0;
     
     /**
+     * The user has pressed on a virtual on-screen key.
+     */
+    public static final int VIRTUAL_KEY = 1;
+    
+    /**
      * Flag for {@link View#performHapticFeedback(int, int)
      * View.performHapticFeedback(int, int)}: Ignore the setting in the
      * view for whether to perform haptic feedback, do it always.
diff --git a/core/java/android/view/KeyEvent.java b/core/java/android/view/KeyEvent.java
index 6349288..f9b16fc 100644
--- a/core/java/android/view/KeyEvent.java
+++ b/core/java/android/view/KeyEvent.java
@@ -258,6 +258,25 @@
     public static final int FLAG_EDITOR_ACTION = 0x10;
     
     /**
+     * When associated with up key events, this indicates that the key press
+     * has been canceled.  Typically this is used with virtual touch screen
+     * keys, where the user can slide from the virtual key area on to the
+     * display: in that case, the application will receive a canceled up
+     * event and should not perform the action normally associated with the
+     * key.  Note that for this to work, the application can not perform an
+     * action for a key until it receives an up or the long press timeout has
+     * expired. 
+     */
+    public static final int FLAG_CANCELED = 0x20;
+    
+    /**
+     * This key event was generated by a virtual (on-screen) hard key area.
+     * Typically this is an area of the touchscreen, outside of the regular
+     * display, dedicated to "hardware" buttons.
+     */
+    public static final int FLAG_VIRTUAL_HARD_KEY = 0x40;
+    
+    /**
      * Returns the maximum keycode.
      */
     public static int getMaxKeyCode() {
@@ -694,6 +713,14 @@
     }
 
     /**
+     * For {@link #ACTION_UP} events, indicates that the event has been
+     * canceled as per {@link #FLAG_CANCELED}.
+     */
+    public final boolean isCanceled() {
+        return (mFlags&FLAG_CANCELED) != 0;
+    }
+    
+    /**
      * Retrieve the key code of the key event.  This is the physical key that
      * was pressed, <em>not</em> the Unicode character.
      * 
diff --git a/core/java/android/view/MotionEvent.java b/core/java/android/view/MotionEvent.java
index a224ed3..89b721d 100644
--- a/core/java/android/view/MotionEvent.java
+++ b/core/java/android/view/MotionEvent.java
@@ -19,7 +19,6 @@
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.SystemClock;
-import android.util.Config;
 
 /**
  * Object used to report movement (mouse, pen, finger, trackball) events.  This
@@ -28,16 +27,23 @@
  */
 public final class MotionEvent implements Parcelable {
     /**
+     * Bit mask of the parts of the action code that are the action itself.
+     */
+    public static final int ACTION_MASK             = 0xff;
+    
+    /**
      * Constant for {@link #getAction}: A pressed gesture has started, the
      * motion contains the initial starting location.
      */
     public static final int ACTION_DOWN             = 0;
+    
     /**
      * Constant for {@link #getAction}: A pressed gesture has finished, the
      * motion contains the final release location as well as any intermediate
      * points since the last down or move event.
      */
     public static final int ACTION_UP               = 1;
+    
     /**
      * Constant for {@link #getAction}: A change has happened during a
      * press gesture (between {@link #ACTION_DOWN} and {@link #ACTION_UP}).
@@ -45,12 +51,14 @@
      * points since the last down or move event.
      */
     public static final int ACTION_MOVE             = 2;
+    
     /**
      * Constant for {@link #getAction}: The current gesture has been aborted.
      * You will not receive any more points in it.  You should treat this as
      * an up event, but not perform any action that you normally would.
      */
     public static final int ACTION_CANCEL           = 3;
+    
     /**
      * Constant for {@link #getAction}: A movement has happened outside of the
      * normal bounds of the UI element.  This does not provide a full gesture,
@@ -58,6 +66,61 @@
      */
     public static final int ACTION_OUTSIDE          = 4;
 
+    /**
+     * A non-primary pointer has gone down.  The bits in
+     * {@link #ACTION_POINTER_MASK} indicate which pointer changed.
+     */
+    public static final int ACTION_POINTER_DOWN     = 5;
+    
+    /**
+     * The primary pointer has gone done.
+     */
+    public static final int ACTION_POINTER_1_DOWN   = ACTION_POINTER_DOWN | 0x0000;
+    
+    /**
+     * The secondary pointer has gone done.
+     */
+    public static final int ACTION_POINTER_2_DOWN   = ACTION_POINTER_DOWN | 0x0100;
+    
+    /**
+     * The tertiary pointer has gone done.
+     */
+    public static final int ACTION_POINTER_3_DOWN   = ACTION_POINTER_DOWN | 0x0200;
+    
+    /**
+     * A non-primary pointer has gone up.  The bits in
+     * {@link #ACTION_POINTER_MASK} indicate which pointer changed.
+     */
+    public static final int ACTION_POINTER_UP       = 6;
+    
+    /**
+     * The primary pointer has gone up.
+     */
+    public static final int ACTION_POINTER_1_UP     = ACTION_POINTER_UP | 0x0000;
+    
+    /**
+     * The secondary pointer has gone up.
+     */
+    public static final int ACTION_POINTER_2_UP     = ACTION_POINTER_UP | 0x0100;
+    
+    /**
+     * The tertiary pointer has gone up.
+     */
+    public static final int ACTION_POINTER_3_UP     = ACTION_POINTER_UP | 0x0200;
+    
+    /**
+     * Bits in the action code that represent a pointer ID, used with
+     * {@link #ACTION_POINTER_DOWN} and {@link #ACTION_POINTER_UP}.  Pointer IDs
+     * start at 0, with 0 being the primary (first) pointer in the motion.
+     */
+    public static final int ACTION_POINTER_MASK     = 0xff00;
+    
+    /**
+     * Bit shift for the action bits holding the pointer identifier as
+     * defined by {@link #ACTION_POINTER_MASK}.
+     */
+    public static final int ACTION_POINTER_SHIFT    = 8;
+    
     private static final boolean TRACK_RECYCLED_LOCATION = false;
 
     /**
@@ -80,34 +143,90 @@
      */
     public static final int EDGE_RIGHT = 0x00000008;
 
+    /**
+     * This is the part of the state data that holds the finger identifier
+     * for the sample.
+     */
+    static private final int STATE_FINGER_ID_MASK = 0xff;
+    
+    /**
+     * Special value for STATE_FINGER_ID_MASK indicating that the finger
+     * is not down in that sample.
+     */
+    static private final int STATE_FINGER_ID_NONE = 0xff;
+    
+    /**
+     * Offset for the sample's X coordinate.
+     * @hide
+     */
+    static public final int SAMPLE_X = 0;
+    
+    /**
+     * Offset for the sample's Y coordinate.
+     * @hide
+     */
+    static public final int SAMPLE_Y = 1;
+    
+    /**
+     * Offset for the sample's X coordinate.
+     * @hide
+     */
+    static public final int SAMPLE_PRESSURE = 2;
+    
+    /**
+     * Offset for the sample's X coordinate.
+     * @hide
+     */
+    static public final int SAMPLE_SIZE = 3;
+    
+    /**
+     * Number of data items for each sample.
+     * @hide
+     */
+    static public final int NUM_SAMPLE_DATA = 4;
+    
+    static private final int BASE_AVAIL_POINTERS = 2;
+    static private final int BASE_AVAIL_SAMPLES = 8;
+    
     static private final int MAX_RECYCLED = 10;
     static private Object gRecyclerLock = new Object();
     static private int gRecyclerUsed = 0;
     static private MotionEvent gRecyclerTop = null;
 
     private long mDownTime;
-    private long mEventTime;
+    private long mEventTimeNano;
     private int mAction;
-    private float mX;
-    private float mY;
     private float mRawX;
     private float mRawY;
-    private float mPressure;
-    private float mSize;
-    private int mMetaState;
-    private int mNumHistory;
-    private float[] mHistory;
-    private long[] mHistoryTimes;
     private float mXPrecision;
     private float mYPrecision;
     private int mDeviceId;
     private int mEdgeFlags;
+    private int mMetaState;
+    
+    // Here is the actual event data.  Note that the order of the array
+    // is a little odd: the first entry is the most recent, and the ones
+    // following it are the historical data from oldest to newest.  This
+    // allows us to easily retrieve the most recent data, without having
+    // to copy the arrays every time a new sample is added.
+    
+    private int mNumPointers;
+    private int mNumSamples;
+    // Array of (mNumSamples * mNumPointers) size of control data.
+    private int[] mStateSamples;
+    // Array of (mNumSamples * mNumPointers * NUM_SAMPLE_DATA) size of event data.
+    private float[] mDataSamples;
+    // Array of mNumSamples size of time stamps.
+    private long[] mTimeSamples;
 
     private MotionEvent mNext;
     private RuntimeException mRecycledLocation;
     private boolean mRecycled;
 
     private MotionEvent() {
+        mStateSamples = new int[BASE_AVAIL_POINTERS*BASE_AVAIL_SAMPLES];
+        mDataSamples = new float[BASE_AVAIL_POINTERS*BASE_AVAIL_SAMPLES*NUM_SAMPLE_DATA];
+        mTimeSamples = new long[BASE_AVAIL_SAMPLES];
     }
 
     static private MotionEvent obtain() {
@@ -127,6 +246,72 @@
     /**
      * Create a new MotionEvent, filling in all of the basic values that
      * define the motion.
+     * 
+     * @param downTime The time (in ms) when the user originally pressed down to start 
+     * a stream of position events.  This must be obtained from {@link SystemClock#uptimeMillis()}.
+     * @param eventTime  The the time (in ms) when this specific event was generated.  This 
+     * must be obtained from {@link SystemClock#uptimeMillis()}.
+     * @param eventTimeNano  The the time (in ns) when this specific event was generated.  This 
+     * must be obtained from {@link System#nanoTime()}.
+     * @param action The kind of action being performed -- one of either
+     * {@link #ACTION_DOWN}, {@link #ACTION_MOVE}, {@link #ACTION_UP}, or
+     * {@link #ACTION_CANCEL}.
+     * @param x The X coordinate of this event.
+     * @param y The Y coordinate of this event.
+     * @param pressure The current pressure of this event.  The pressure generally 
+     * ranges from 0 (no pressure at all) to 1 (normal pressure), however 
+     * values higher than 1 may be generated depending on the calibration of 
+     * the input device.
+     * @param size A scaled value of the approximate size of the area being pressed when
+     * touched with the finger. The actual value in pixels corresponding to the finger 
+     * touch is normalized with a device specific range of values
+     * and scaled to a value between 0 and 1.
+     * @param metaState The state of any meta / modifier keys that were in effect when
+     * the event was generated.
+     * @param xPrecision The precision of the X coordinate being reported.
+     * @param yPrecision The precision of the Y coordinate being reported.
+     * @param deviceId The id for the device that this event came from.  An id of
+     * zero indicates that the event didn't come from a physical device; other
+     * numbers are arbitrary and you shouldn't depend on the values.
+     * @param edgeFlags A bitfield indicating which edges, if any, where touched by this
+     * MotionEvent.
+     *
+     * @hide
+     */
+    static public MotionEvent obtainNano(long downTime, long eventTime, long eventTimeNano,
+            int action, int pointers, float[] inData, int metaState,
+            float xPrecision, float yPrecision, int deviceId, int edgeFlags) {
+        MotionEvent ev = obtain();
+        ev.mDeviceId = deviceId;
+        ev.mEdgeFlags = edgeFlags;
+        ev.mDownTime = downTime;
+        ev.mEventTimeNano = eventTimeNano;
+        ev.mAction = action;
+        ev.mMetaState = metaState;
+        ev.mRawX = inData[SAMPLE_X];
+        ev.mRawY = inData[SAMPLE_Y];
+        ev.mXPrecision = xPrecision;
+        ev.mYPrecision = yPrecision;
+        ev.mNumPointers = pointers;
+        ev.mNumSamples = 1;
+        
+        float[] data = ev.mDataSamples;
+        System.arraycopy(inData, 0, data, 0, pointers * NUM_SAMPLE_DATA);
+        
+        int[] state = ev.mStateSamples;
+        while (pointers > 0) {
+            pointers--;
+            state[pointers] = pointers;
+        }
+        
+        ev.mTimeSamples[0] = eventTime;
+
+        return ev;
+    }
+    
+    /**
+     * Create a new MotionEvent, filling in all of the basic values that
+     * define the motion.
      *
      * @param downTime The time (in ms) when the user originally pressed down to start
      * a stream of position events.  This must be obtained from {@link SystemClock#uptimeMillis()}.
@@ -162,16 +347,83 @@
         ev.mDeviceId = deviceId;
         ev.mEdgeFlags = edgeFlags;
         ev.mDownTime = downTime;
-        ev.mEventTime = eventTime;
+        ev.mEventTimeNano = eventTime * 1000000;
         ev.mAction = action;
-        ev.mX = ev.mRawX = x;
-        ev.mY = ev.mRawY = y;
-        ev.mPressure = pressure;
-        ev.mSize = size;
         ev.mMetaState = metaState;
         ev.mXPrecision = xPrecision;
         ev.mYPrecision = yPrecision;
 
+        ev.mNumPointers = 1;
+        ev.mNumSamples = 1;
+        int[] state = ev.mStateSamples;
+        state[0] = 0;
+        float[] data = ev.mDataSamples;
+        data[SAMPLE_X] = ev.mRawX = x;
+        data[SAMPLE_Y] = ev.mRawY = y;
+        data[SAMPLE_PRESSURE] = pressure;
+        data[SAMPLE_SIZE] = size;
+        ev.mTimeSamples[0] = eventTime;
+
+        return ev;
+    }
+
+    /**
+     * Create a new MotionEvent, filling in all of the basic values that
+     * define the motion.
+     *
+     * @param downTime The time (in ms) when the user originally pressed down to start
+     * a stream of position events.  This must be obtained from {@link SystemClock#uptimeMillis()}.
+     * @param eventTime  The the time (in ms) when this specific event was generated.  This
+     * must be obtained from {@link SystemClock#uptimeMillis()}.
+     * @param action The kind of action being performed -- one of either
+     * {@link #ACTION_DOWN}, {@link #ACTION_MOVE}, {@link #ACTION_UP}, or
+     * {@link #ACTION_CANCEL}.
+     * @param pointers The number of pointers that are active in this event.
+     * @param x The X coordinate of this event.
+     * @param y The Y coordinate of this event.
+     * @param pressure The current pressure of this event.  The pressure generally
+     * ranges from 0 (no pressure at all) to 1 (normal pressure), however
+     * values higher than 1 may be generated depending on the calibration of
+     * the input device.
+     * @param size A scaled value of the approximate size of the area being pressed when
+     * touched with the finger. The actual value in pixels corresponding to the finger
+     * touch is normalized with a device specific range of values
+     * and scaled to a value between 0 and 1.
+     * @param metaState The state of any meta / modifier keys that were in effect when
+     * the event was generated.
+     * @param xPrecision The precision of the X coordinate being reported.
+     * @param yPrecision The precision of the Y coordinate being reported.
+     * @param deviceId The id for the device that this event came from.  An id of
+     * zero indicates that the event didn't come from a physical device; other
+     * numbers are arbitrary and you shouldn't depend on the values.
+     * @param edgeFlags A bitfield indicating which edges, if any, where touched by this
+     * MotionEvent.
+     */
+    static public MotionEvent obtain(long downTime, long eventTime, int action,
+            int pointers, float x, float y, float pressure, float size, int metaState,
+            float xPrecision, float yPrecision, int deviceId, int edgeFlags) {
+        MotionEvent ev = obtain();
+        ev.mDeviceId = deviceId;
+        ev.mEdgeFlags = edgeFlags;
+        ev.mDownTime = downTime;
+        ev.mEventTimeNano = eventTime * 1000000;
+        ev.mAction = action;
+        ev.mNumPointers = pointers;
+        ev.mMetaState = metaState;
+        ev.mXPrecision = xPrecision;
+        ev.mYPrecision = yPrecision;
+
+        ev.mNumPointers = 1;
+        ev.mNumSamples = 1;
+        int[] state = ev.mStateSamples;
+        state[0] = 0;
+        float[] data = ev.mDataSamples;
+        data[SAMPLE_X] = ev.mRawX = x;
+        data[SAMPLE_Y] = ev.mRawY = y;
+        data[SAMPLE_PRESSURE] = pressure;
+        data[SAMPLE_SIZE] = size;
+        ev.mTimeSamples[0] = eventTime;
+
         return ev;
     }
 
@@ -198,16 +450,24 @@
         ev.mDeviceId = 0;
         ev.mEdgeFlags = 0;
         ev.mDownTime = downTime;
-        ev.mEventTime = eventTime;
+        ev.mEventTimeNano = eventTime * 1000000;
         ev.mAction = action;
-        ev.mX = ev.mRawX = x;
-        ev.mY = ev.mRawY = y;
-        ev.mPressure = 1.0f;
-        ev.mSize = 1.0f;
+        ev.mNumPointers = 1;
         ev.mMetaState = metaState;
         ev.mXPrecision = 1.0f;
         ev.mYPrecision = 1.0f;
 
+        ev.mNumPointers = 1;
+        ev.mNumSamples = 1;
+        int[] state = ev.mStateSamples;
+        state[0] = 0;
+        float[] data = ev.mDataSamples;
+        data[SAMPLE_X] = ev.mRawX = x;
+        data[SAMPLE_Y] = ev.mRawY = y;
+        data[SAMPLE_PRESSURE] = 1.0f;
+        data[SAMPLE_SIZE] = 1.0f;
+        ev.mTimeSamples[0] = eventTime;
+
         return ev;
     }
 
@@ -217,43 +477,17 @@
      * @hide
      */
     public void scale(float scale) {
-        mX *= scale;
-        mY *= scale;
         mRawX *= scale;
         mRawY *= scale;
-        mSize *= scale;
         mXPrecision *= scale;
         mYPrecision *= scale;
-        if (mHistory != null) {
-            float[] history = mHistory;
-            int length = history.length;
-            for (int i = 0; i < length; i += 4) {
-                history[i] *= scale;        // X
-                history[i + 1] *= scale;    // Y
-                // no need to scale pressure ([i+2])
-                history[i + 3] *= scale;    // Size, TODO: square this?
-            }
-        }
-    }
-
-    /**
-     * Translate the coordination of the event by given x and y.
-     *
-     * @hide
-     */
-    public void translate(float dx, float dy) {
-        mX += dx;
-        mY += dy;
-        mRawX += dx;
-        mRawY += dx;
-        if (mHistory != null) {
-            float[] history = mHistory;
-            int length = history.length;
-            for (int i = 0; i < length; i += 4) {
-                history[i] += dx;        // X
-                history[i + 1] += dy;    // Y
-                // no need to translate pressure (i+2) and size (i+3) 
-            }
+        float[] history = mDataSamples;
+        final int length = mNumPointers * mNumSamples * NUM_SAMPLE_DATA;
+        for (int i = 0; i < length; i += NUM_SAMPLE_DATA) {
+            history[i + SAMPLE_X] *= scale;
+            history[i + SAMPLE_Y] *= scale;
+            // no need to scale pressure
+            history[i + SAMPLE_SIZE] *= scale;    // TODO: square this?
         }
     }
 
@@ -265,24 +499,36 @@
         ev.mDeviceId = o.mDeviceId;
         ev.mEdgeFlags = o.mEdgeFlags;
         ev.mDownTime = o.mDownTime;
-        ev.mEventTime = o.mEventTime;
+        ev.mEventTimeNano = o.mEventTimeNano;
         ev.mAction = o.mAction;
-        ev.mX = o.mX;
+        ev.mNumPointers = o.mNumPointers;
         ev.mRawX = o.mRawX;
-        ev.mY = o.mY;
         ev.mRawY = o.mRawY;
-        ev.mPressure = o.mPressure;
-        ev.mSize = o.mSize;
         ev.mMetaState = o.mMetaState;
         ev.mXPrecision = o.mXPrecision;
         ev.mYPrecision = o.mYPrecision;
-        final int N = o.mNumHistory;
-        ev.mNumHistory = N;
-        if (N > 0) {
-            // could be more efficient about this...
-            ev.mHistory = (float[])o.mHistory.clone();
-            ev.mHistoryTimes = (long[])o.mHistoryTimes.clone();
+        
+        final int NT = ev.mNumSamples = o.mNumSamples;
+        if (ev.mTimeSamples.length < NT) {
+            System.arraycopy(o.mTimeSamples, 0, ev.mTimeSamples, 0, NT);
+        } else {
+            ev.mTimeSamples = (long[])o.mTimeSamples.clone();
         }
+        
+        final int NS = (ev.mNumPointers=o.mNumPointers) * NT;
+        if (ev.mStateSamples.length < NS) {
+            System.arraycopy(o.mStateSamples, 0, ev.mStateSamples, 0, NS);
+        } else {
+            ev.mStateSamples = (int[])o.mStateSamples.clone();
+        }
+        
+        final int ND = NS * NUM_SAMPLE_DATA;
+        if (ev.mDataSamples.length < ND) {
+            System.arraycopy(o.mDataSamples, 0, ev.mDataSamples, 0, ND);
+        } else {
+            ev.mDataSamples = (float[])o.mDataSamples.clone();
+        }
+        
         return ev;
     }
 
@@ -305,7 +551,7 @@
         synchronized (gRecyclerLock) {
             if (gRecyclerUsed < MAX_RECYCLED) {
                 gRecyclerUsed++;
-                mNumHistory = 0;
+                mNumSamples = 0;
                 mNext = gRecyclerTop;
                 gRecyclerTop = this;
             }
@@ -333,44 +579,102 @@
      * Returns the time (in ms) when this specific event was generated.
      */
     public final long getEventTime() {
-        return mEventTime;
+        return mTimeSamples[0];
     }
 
     /**
-     * Returns the X coordinate of this event.  Whole numbers are pixels; the
-     * value may have a fraction for input devices that are sub-pixel precise.
+     * Returns the time (in ns) when this specific event was generated.
+     * The value is in nanosecond precision but it may not have nanosecond accuracy.
+     *
+     * @hide
+     */
+    public final long getEventTimeNano() {
+        return mEventTimeNano;
+    }
+
+    /**
+     * The number of pointers of data contained in this event.  Always
+     * >= 1.
+     */
+    public final int getPointerCount() {
+        return mNumPointers;
+    }
+    
+    /**
+     * {@link #getX(int)} for the first pointer (pointer 0).
      */
     public final float getX() {
-        return mX;
+        return mDataSamples[SAMPLE_X];
     }
 
     /**
-     * Returns the Y coordinate of this event.  Whole numbers are pixels; the
-     * value may have a fraction for input devices that are sub-pixel precise.
+     * {@link #getY(int)} for the first pointer (pointer 0).
      */
     public final float getY() {
-        return mY;
+        return mDataSamples[SAMPLE_Y];
     }
 
     /**
-     * Returns the current pressure of this event.  The pressure generally
+     * {@link #getPressure(int)} for the first pointer (pointer 0).
+     */
+    public final float getPressure() {
+        return mDataSamples[SAMPLE_PRESSURE];
+    }
+
+    /**
+     * {@link #getSize(int)} for the first pointer (pointer 0).
+     */
+    public final float getSize() {
+        return mDataSamples[SAMPLE_SIZE];
+    }
+
+    /**
+     * Returns the X coordinate of this event for the given pointer.
+     * Whole numbers are pixels; the 
+     * value may have a fraction for input devices that are sub-pixel precise. 
+     * @param pointer The desired pointer to retrieve.  Value may be from 0
+     * (the first pointer) to {@link #getPointerCount()}-1.
+     */
+    public final float getX(int pointer) {
+        return mDataSamples[(pointer*NUM_SAMPLE_DATA) + SAMPLE_X];
+    }
+
+    /**
+     * Returns the Y coordinate of this event for the given pointer.
+     * Whole numbers are pixels; the
+     * value may have a fraction for input devices that are sub-pixel precise.
+     * @param pointer The desired pointer to retrieve.  Value may be from 0
+     * (the first pointer) to {@link #getPointerCount()}-1.
+     */
+    public final float getY(int pointer) {
+        return mDataSamples[(pointer*NUM_SAMPLE_DATA) + SAMPLE_Y];
+    }
+
+    /**
+     * Returns the current pressure of this event for the given pointer.
+     * The pressure generally
      * ranges from 0 (no pressure at all) to 1 (normal pressure), however
      * values higher than 1 may be generated depending on the calibration of
      * the input device.
+     * @param pointer The desired pointer to retrieve.  Value may be from 0
+     * (the first pointer) to {@link #getPointerCount()}-1.
      */
-    public final float getPressure() {
-        return mPressure;
+    public final float getPressure(int pointer) {
+        return mDataSamples[(pointer*NUM_SAMPLE_DATA) + SAMPLE_PRESSURE];
     }
 
     /**
-     * Returns a scaled value of the approximate size, of the area being pressed when
-     * touched with the finger. The actual value in pixels corresponding to the finger
-     * touch  is normalized with the device specific range of values
+     * Returns a scaled value of the approximate size for the given pointer,
+     * representing the area of the screen being pressed.
+     * The actual value in pixels corresponding to the
+     * touch is normalized with the device specific range of values
      * and scaled to a value between 0 and 1. The value of size can be used to
      * determine fat touch events.
+     * @param pointer The desired pointer to retrieve.  Value may be from 0
+     * (the first pointer) to {@link #getPointerCount()}-1.
      */
-    public final float getSize() {
-        return mSize;
+    public final float getSize(int pointer) {
+        return mDataSamples[(pointer*NUM_SAMPLE_DATA) + SAMPLE_SIZE];
     }
 
     /**
@@ -436,7 +740,7 @@
      * @return Returns the number of historical points in the event.
      */
     public final int getHistorySize() {
-        return mNumHistory;
+        return mNumSamples - 1;
     }
 
     /**
@@ -450,63 +754,103 @@
      * @see #getEventTime
      */
     public final long getHistoricalEventTime(int pos) {
-        return mHistoryTimes[pos];
+        return mTimeSamples[pos + 1];
+    }
+
+    /**
+     * {@link #getHistoricalX(int)} for the first pointer (pointer 0).
+     */
+    public final float getHistoricalX(int pos) {
+        return mDataSamples[((pos + 1) * NUM_SAMPLE_DATA * mNumPointers) + SAMPLE_X];
+    }
+
+    /**
+     * {@link #getHistoricalY(int)} for the first pointer (pointer 0).
+     */
+    public final float getHistoricalY(int pos) {
+        return mDataSamples[((pos + 1) * NUM_SAMPLE_DATA * mNumPointers) + SAMPLE_Y];
+    }
+
+    /**
+     * {@link #getHistoricalPressure(int)} for the first pointer (pointer 0).
+     */
+    public final float getHistoricalPressure(int pos) {
+        return mDataSamples[((pos + 1) * NUM_SAMPLE_DATA * mNumPointers) + SAMPLE_PRESSURE];
+    }
+
+    /**
+     * {@link #getHistoricalSize(int)} for the first pointer (pointer 0).
+     */
+    public final float getHistoricalSize(int pos) {
+        return mDataSamples[((pos + 1) * NUM_SAMPLE_DATA * mNumPointers) + SAMPLE_SIZE];
     }
 
     /**
      * Returns a historical X coordinate that occurred between this event
-     * and the previous event.  Only applies to ACTION_MOVE events.
+     * and the previous event for the given pointer.  Only applies to ACTION_MOVE events.
      *
+     * @param pointer The desired pointer to retrieve.  Value may be from 0
+     * (the first pointer) to {@link #getPointerCount()}-1.
      * @param pos Which historical value to return; must be less than
      * {@link #getHistorySize}
      *
      * @see #getHistorySize
      * @see #getX
      */
-    public final float getHistoricalX(int pos) {
-        return mHistory[pos*4];
+    public final float getHistoricalX(int pointer, int pos) {
+        return mDataSamples[((pos + 1) * NUM_SAMPLE_DATA * mNumPointers)
+                            + (pointer * NUM_SAMPLE_DATA) + SAMPLE_X];
     }
 
     /**
      * Returns a historical Y coordinate that occurred between this event
-     * and the previous event.  Only applies to ACTION_MOVE events.
+     * and the previous event for the given pointer.  Only applies to ACTION_MOVE events.
      *
+     * @param pointer The desired pointer to retrieve.  Value may be from 0
+     * (the first pointer) to {@link #getPointerCount()}-1.
      * @param pos Which historical value to return; must be less than
      * {@link #getHistorySize}
      *
      * @see #getHistorySize
      * @see #getY
      */
-    public final float getHistoricalY(int pos) {
-        return mHistory[pos*4 + 1];
+    public final float getHistoricalY(int pointer, int pos) {
+        return mDataSamples[((pos + 1) * NUM_SAMPLE_DATA * mNumPointers)
+                            + (pointer * NUM_SAMPLE_DATA) + SAMPLE_Y];
     }
 
     /**
      * Returns a historical pressure coordinate that occurred between this event
-     * and the previous event.  Only applies to ACTION_MOVE events.
+     * and the previous event for the given pointer.  Only applies to ACTION_MOVE events.
      *
      * @param pos Which historical value to return; must be less than
      * {@link #getHistorySize}
      *
+     * @param pointer The desired pointer to retrieve.  Value may be from 0
+     * (the first pointer) to {@link #getPointerCount()}-1.
      * @see #getHistorySize
      * @see #getPressure
      */
-    public final float getHistoricalPressure(int pos) {
-        return mHistory[pos*4 + 2];
+    public final float getHistoricalPressure(int pointer, int pos) {
+        return mDataSamples[((pos + 1) * NUM_SAMPLE_DATA * mNumPointers)
+                            + (pointer * NUM_SAMPLE_DATA) + SAMPLE_PRESSURE];
     }
 
     /**
      * Returns a historical size coordinate that occurred between this event
-     * and the previous event.  Only applies to ACTION_MOVE events.
+     * and the previous event for the given pointer.  Only applies to ACTION_MOVE events.
      *
      * @param pos Which historical value to return; must be less than
      * {@link #getHistorySize}
      *
+     * @param pointer The desired pointer to retrieve.  Value may be from 0
+     * (the first pointer) to {@link #getPointerCount()}-1.
      * @see #getHistorySize
      * @see #getSize
      */
-    public final float getHistoricalSize(int pos) {
-        return mHistory[pos*4 + 3];
+    public final float getHistoricalSize(int pointer, int pos) {
+        return mDataSamples[((pos + 1) * NUM_SAMPLE_DATA * mNumPointers)
+                            + (pointer * NUM_SAMPLE_DATA) + SAMPLE_SIZE];
     }
 
     /**
@@ -556,16 +900,11 @@
      * @param deltaY Amount to add to the current Y coordinate of the event.
      */
     public final void offsetLocation(float deltaX, float deltaY) {
-        mX += deltaX;
-        mY += deltaY;
-        final int N = mNumHistory*4;
-        if (N <= 0) {
-            return;
-        }
-        final float[] pos = mHistory;
-        for (int i=0; i<N; i+=4) {
-            pos[i] += deltaX;
-            pos[i+1] += deltaY;
+        final int N = mNumPointers*mNumSamples*4;
+        final float[] pos = mDataSamples;
+        for (int i=0; i<N; i+=NUM_SAMPLE_DATA) {
+            pos[i+SAMPLE_X] += deltaX;
+            pos[i+SAMPLE_Y] += deltaY;
         }
     }
 
@@ -577,8 +916,8 @@
      * @param y New absolute Y location.
      */
     public final void setLocation(float x, float y) {
-        float deltaX = x-mX;
-        float deltaY = y-mY;
+        float deltaX = x-mDataSamples[SAMPLE_X];
+        float deltaY = y-mDataSamples[SAMPLE_Y];
         if (deltaX != 0 || deltaY != 0) {
             offsetLocation(deltaX, deltaY);
         }
@@ -590,58 +929,118 @@
      * the future, the current values in the event will be added to a list of
      * historic values.
      *
+     * @param eventTime The time stamp for this data.
      * @param x The new X position.
      * @param y The new Y position.
      * @param pressure The new pressure.
      * @param size The new size.
+     * @param metaState Meta key state.
      */
     public final void addBatch(long eventTime, float x, float y,
             float pressure, float size, int metaState) {
-        float[] history = mHistory;
-        long[] historyTimes = mHistoryTimes;
-        int N;
-        int avail;
-        if (history == null) {
-            mHistory = history = new float[8*4];
-            mHistoryTimes = historyTimes = new long[8];
-            mNumHistory = N = 0;
-            avail = 8;
-        } else {
-            N = mNumHistory;
-            avail = history.length/4;
-            if (N == avail) {
-                avail += 8;
-                float[] newHistory = new float[avail*4];
-                System.arraycopy(history, 0, newHistory, 0, N*4);
-                mHistory = history = newHistory;
-                long[] newHistoryTimes = new long[avail];
-                System.arraycopy(historyTimes, 0, newHistoryTimes, 0, N);
-                mHistoryTimes = historyTimes = newHistoryTimes;
-            }
+        int[] states = mStateSamples;
+        float[] data = mDataSamples;
+        long[] times = mTimeSamples;
+        
+        final int NP = mNumPointers;
+        final int NS = mNumSamples;
+        final int NI = NP*NS;
+        final int ND = NI * NUM_SAMPLE_DATA;
+        if (states.length < (NI+NP)) {
+            // The state and data arrays are sized together, since their
+            // size is always a fixed factor from each other.
+            final int NEW_NI = NP * (NS+BASE_AVAIL_SAMPLES);
+            int[] newState = new int[NEW_NI];
+            System.arraycopy(states, 0, newState, 0, NI);
+            mStateSamples = states = newState;
+            final int NEW_ND = NEW_NI * NUM_SAMPLE_DATA;
+            float[] newData = new float[NEW_ND];
+            System.arraycopy(data, 0, newData, 0, ND);
+            mDataSamples = data = newData;
         }
+        if (times.length <= NS) {
+            final int NEW_NS = NS + BASE_AVAIL_SAMPLES;
+            long[] newHistoryTimes = new long[NEW_NS];
+            System.arraycopy(times, 0, newHistoryTimes, 0, NS);
+            mTimeSamples = times = newHistoryTimes;
+        }
+        
+        times[NS] = times[0];
+        times[0] = eventTime;
+        
+        final int pos = NS*NUM_SAMPLE_DATA;
+        data[pos+SAMPLE_X] = data[SAMPLE_X];
+        data[pos+SAMPLE_Y] = data[SAMPLE_Y];
+        data[pos+SAMPLE_PRESSURE] = data[SAMPLE_PRESSURE];
+        data[pos+SAMPLE_SIZE] = data[SAMPLE_SIZE];
+        data[SAMPLE_X] = x;
+        data[SAMPLE_Y] = y;
+        data[SAMPLE_PRESSURE] = pressure;
+        data[SAMPLE_SIZE] = size;
+        mNumSamples = NS+1;
 
-        historyTimes[N] = mEventTime;
+        mRawX = x;
+        mRawY = y;
+        mMetaState |= metaState;
+    }
 
-        final int pos = N*4;
-        history[pos] = mX;
-        history[pos+1] = mY;
-        history[pos+2] = mPressure;
-        history[pos+3] = mSize;
-        mNumHistory = N+1;
+    /**
+     * Add a new movement to the batch of movements in this event.  The
+     * input data must contain (NUM_SAMPLE_DATA * {@link #getPointerCount()})
+     * samples of data.
+     *
+     * @param eventTime The time stamp for this data.
+     * @param inData The actual data.
+     * @param metaState Meta key state.
+     * 
+     * @hide
+     */
+    public final void addBatch(long eventTime, float[] inData, int metaState) {
+        int[] states = mStateSamples;
+        float[] data = mDataSamples;
+        long[] times = mTimeSamples;
+        
+        final int NP = mNumPointers;
+        final int NS = mNumSamples;
+        final int NI = NP*NS;
+        final int ND = NI * NUM_SAMPLE_DATA;
+        if (states.length < (NI+NP)) {
+            // The state and data arrays are sized together, since their
+            // size is always a fixed factor from each other.
+            final int NEW_NI = NP * (NS+BASE_AVAIL_SAMPLES);
+            int[] newState = new int[NEW_NI];
+            System.arraycopy(states, 0, newState, 0, NI);
+            mStateSamples = states = newState;
+            final int NEW_ND = NEW_NI * NUM_SAMPLE_DATA;
+            float[] newData = new float[NEW_ND];
+            System.arraycopy(data, 0, newData, 0, ND);
+            mDataSamples = data = newData;
+        }
+        if (times.length <= NS) {
+            final int NEW_NS = NS + BASE_AVAIL_SAMPLES;
+            long[] newHistoryTimes = new long[NEW_NS];
+            System.arraycopy(times, 0, newHistoryTimes, 0, NS);
+            mTimeSamples = times = newHistoryTimes;
+        }
+        
+        times[NS] = times[0];
+        times[0] = eventTime;
+        
+        System.arraycopy(data, 0, data, ND, mNumPointers*NUM_SAMPLE_DATA);
+        System.arraycopy(inData, 0, data, 0, mNumPointers*NUM_SAMPLE_DATA);
+        
+        mNumSamples = NS+1;
 
-        mEventTime = eventTime;
-        mX = mRawX = x;
-        mY = mRawY = y;
-        mPressure = pressure;
-        mSize = size;
+        mRawX = inData[SAMPLE_X];
+        mRawY = inData[SAMPLE_Y];
         mMetaState |= metaState;
     }
 
     @Override
     public String toString() {
         return "MotionEvent{" + Integer.toHexString(System.identityHashCode(this))
-            + " action=" + mAction + " x=" + mX
-            + " y=" + mY + " pressure=" + mPressure + " size=" + mSize + "}";
+            + " action=" + mAction + " x=" + getX()
+            + " y=" + getY() + " pressure=" + getPressure() + " size=" + getSize() + "}";
     }
 
     public static final Parcelable.Creator<MotionEvent> CREATOR
@@ -663,26 +1062,29 @@
 
     public void writeToParcel(Parcel out, int flags) {
         out.writeLong(mDownTime);
-        out.writeLong(mEventTime);
+        out.writeLong(mEventTimeNano);
         out.writeInt(mAction);
-        out.writeFloat(mX);
-        out.writeFloat(mY);
-        out.writeFloat(mPressure);
-        out.writeFloat(mSize);
         out.writeInt(mMetaState);
         out.writeFloat(mRawX);
         out.writeFloat(mRawY);
-        final int N = mNumHistory;
-        out.writeInt(N);
-        if (N > 0) {
-            final int N4 = N*4;
+        final int NP = mNumPointers;
+        out.writeInt(NP);
+        final int NS = mNumSamples;
+        out.writeInt(NS);
+        final int NI = NP*NS;
+        if (NI > 0) {
             int i;
-            float[] history = mHistory;
-            for (i=0; i<N4; i++) {
+            int[] state = mStateSamples;
+            for (i=0; i<NI; i++) {
+                out.writeInt(state[i]);
+            }
+            final int NI4 = NI*NUM_SAMPLE_DATA;
+            float[] history = mDataSamples;
+            for (i=0; i<NI4; i++) {
                 out.writeFloat(history[i]);
             }
-            long[] times = mHistoryTimes;
-            for (i=0; i<N; i++) {
+            long[] times = mTimeSamples;
+            for (i=0; i<NS; i++) {
                 out.writeLong(times[i]);
             }
         }
@@ -694,30 +1096,37 @@
 
     private void readFromParcel(Parcel in) {
         mDownTime = in.readLong();
-        mEventTime = in.readLong();
+        mEventTimeNano = in.readLong();
         mAction = in.readInt();
-        mX = in.readFloat();
-        mY = in.readFloat();
-        mPressure = in.readFloat();
-        mSize = in.readFloat();
         mMetaState = in.readInt();
         mRawX = in.readFloat();
         mRawY = in.readFloat();
-        final int N = in.readInt();
-        if ((mNumHistory=N) > 0) {
-            final int N4 = N*4;
-            float[] history = mHistory;
-            if (history == null || history.length < N4) {
-                mHistory = history = new float[N4 + (4*4)];
+        final int NP = in.readInt();
+        mNumPointers = NP;
+        final int NS = in.readInt();
+        mNumSamples = NS;
+        final int NI = NP*NS;
+        if (NI > 0) {
+            final int NI4 = NI*4;
+            int[] state = mStateSamples;
+            if (state.length < NI) {
+                mStateSamples = state = new int[NI];
             }
-            for (int i=0; i<N4; i++) {
+            for (int i=0; i<NI; i++) {
+                state[i] = in.readInt();
+            }
+            float[] history = mDataSamples;
+            if (history.length < NI4) {
+                mDataSamples = history = new float[NI4];
+            }
+            for (int i=0; i<NI4; i++) {
                 history[i] = in.readFloat();
             }
-            long[] times = mHistoryTimes;
-            if (times == null || times.length < N) {
-                mHistoryTimes = times = new long[N + 4];
+            long[] times = mTimeSamples;
+            if (times == null || times.length < NS) {
+                mTimeSamples = times = new long[NS];
             }
-            for (int i=0; i<N; i++) {
+            for (int i=0; i<NS; i++) {
                 times[i] = in.readLong();
             }
         }
diff --git a/core/java/android/view/Surface.java b/core/java/android/view/Surface.java
index 4bc929b..9178131 100644
--- a/core/java/android/view/Surface.java
+++ b/core/java/android/view/Surface.java
@@ -129,6 +129,8 @@
     @SuppressWarnings("unused")
     private int mSurface;
     @SuppressWarnings("unused")
+    private int mSurfaceControl;
+    @SuppressWarnings("unused")
     private int mSaveCount;
     @SuppressWarnings("unused")
     private Canvas mCanvas;
@@ -343,7 +345,7 @@
 
     @Override
     public String toString() {
-        return "Surface(native-token=" + mSurface + ")";
+        return "Surface(native-token=" + mSurfaceControl + ")";
     }
 
     private Surface(Parcel source) throws OutOfResourcesException {
@@ -356,7 +358,7 @@
 
     public native   void readFromParcel(Parcel source);
     public native   void writeToParcel(Parcel dest, int flags);
-
+    
     public static final Parcelable.Creator<Surface> CREATOR
             = new Parcelable.Creator<Surface>()
     {
@@ -377,7 +379,7 @@
     /* no user serviceable parts here ... */
     @Override
     protected void finalize() throws Throwable {
-        clear();
+        release();
     }
     
     private native void init(SurfaceSession s,
@@ -385,4 +387,6 @@
             throws OutOfResourcesException;
 
     private native void init(Parcel source);
+    
+    private native void release();
 }
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 9cf7092..4546572 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -32,8 +32,9 @@
 import android.util.AttributeSet;
 import android.util.Config;
 import android.util.Log;
-import java.util.ArrayList;
 
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
 import java.util.concurrent.locks.ReentrantLock;
 import java.lang.ref.WeakReference;
 
diff --git a/core/java/android/view/ViewRoot.java b/core/java/android/view/ViewRoot.java
index b6119aa..884950f 100644
--- a/core/java/android/view/ViewRoot.java
+++ b/core/java/android/view/ViewRoot.java
@@ -80,6 +80,9 @@
     private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
     private static final boolean WATCH_POINTER = false;
 
+    private static final boolean MEASURE_LATENCY = false;
+    private static LatencyTimer lt;
+
     /**
      * Maximum time we allow the user to roll the trackball enough to generate
      * a key event, before resetting the counters.
@@ -149,7 +152,8 @@
     boolean mWindowAttributesChanged = false;
 
     // These can be accessed by any thread, must be protected with a lock.
-    Surface mSurface;
+    // Surface can never be reassigned or cleared (use Surface.clear()).
+    private final Surface mSurface = new Surface();
 
     boolean mAdded;
     boolean mAddedTouchMode;
@@ -192,6 +196,10 @@
     public ViewRoot(Context context) {
         super();
 
+        if (MEASURE_LATENCY && lt == null) {
+            lt = new LatencyTimer(100, 1000);
+        }
+
         ++sInstanceCount;
 
         // Initialize the statics when this class is first instantiated. This is
@@ -225,7 +233,6 @@
         mTransparentRegion = new Region();
         mPreviousTransparentRegion = new Region();
         mFirst = true; // true for the first time the view is added
-        mSurface = new Surface();
         mAdded = false;
         mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
         mViewConfiguration = ViewConfiguration.get(context);
@@ -1547,10 +1554,12 @@
 
         mView = null;
         mAttachInfo.mRootView = null;
+        mAttachInfo.mSurface = null;
 
         if (mUseGL) {
             destroyGL();
         }
+        mSurface.clear();
 
         try {
             sWindowSession.remove(mWindow);
@@ -1624,7 +1633,17 @@
             boolean didFinish;
             if (event == null) {
                 try {
+                    long timeBeforeGettingEvents;
+                    if (MEASURE_LATENCY) {
+                        timeBeforeGettingEvents = System.nanoTime();
+                    }
+
                     event = sWindowSession.getPendingPointerMove(mWindow);
+
+                    if (MEASURE_LATENCY && event != null) {
+                        lt.sample("9 Client got events      ", System.nanoTime() - event.getEventTimeNano());
+                        lt.sample("8 Client getting events  ", timeBeforeGettingEvents - event.getEventTimeNano());
+                    }
                 } catch (RemoteException e) {
                 }
                 didFinish = true;
@@ -1646,8 +1665,16 @@
                     if(Config.LOGV) {
                         captureMotionLog("captureDispatchPointer", event);
                     }
-                    event.offsetLocation(0, mCurScrollY);
+                    if (mCurScrollY != 0) {
+                        event.offsetLocation(0, mCurScrollY);
+                    }
+                    if (MEASURE_LATENCY) {
+                        lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
+                    }
                     handled = mView.dispatchTouchEvent(event);
+                    if (MEASURE_LATENCY) {
+                        lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
+                    }
                     if (!handled && isDown) {
                         int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
 
@@ -2494,7 +2521,7 @@
                     }
                 }
 
-                mSurface = null;
+                mSurface.clear();
             }
             if (mAdded) {
                 mAdded = false;
@@ -2739,7 +2766,11 @@
 
         public void dispatchPointer(MotionEvent event, long eventTime) {
             final ViewRoot viewRoot = mViewRoot.get();
-            if (viewRoot != null) {
+            if (viewRoot != null) {                
+                if (MEASURE_LATENCY) {
+                    // Note: eventTime is in milliseconds
+                    ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
+                }
                 viewRoot.dispatchPointer(event, eventTime);
             } else {
                 new EventCompletion(mMainLooper, this, null, true, event);
diff --git a/core/java/android/view/ViewStub.java b/core/java/android/view/ViewStub.java
index e159de4..703a38f 100644
--- a/core/java/android/view/ViewStub.java
+++ b/core/java/android/view/ViewStub.java
@@ -23,6 +23,8 @@
 
 import com.android.internal.R;
 
+import java.lang.ref.WeakReference;
+
 /**
  * A ViewStub is an invisible, zero-sized View that can be used to lazily inflate
  * layout resources at runtime.
@@ -68,6 +70,8 @@
     private int mLayoutResource = 0;
     private int mInflatedId;
 
+    private WeakReference<View> mInflatedViewRef;
+
     private OnInflateListener mInflateListener;
 
     public ViewStub(Context context) {
@@ -196,9 +200,15 @@
      */
     @Override
     public void setVisibility(int visibility) {
-        super.setVisibility(visibility);
-
-        if (visibility == VISIBLE || visibility == INVISIBLE) {
+        if (mInflatedViewRef != null) {
+            View view = mInflatedViewRef.get();
+            if (view != null) {
+                view.setVisibility(visibility);
+            } else {
+                throw new IllegalStateException("setVisibility called on un-referenced view");
+            }
+        } else if (visibility == VISIBLE || visibility == INVISIBLE) {
+            super.setVisibility(visibility);
             inflate();
         }
     }
@@ -234,6 +244,8 @@
                     parent.addView(view, index);
                 }
 
+                mInflatedViewRef = new WeakReference(view);
+
                 if (mInflateListener != null) {
                     mInflateListener.onInflate(this, view);
                 }
diff --git a/core/java/android/view/Window.java b/core/java/android/view/Window.java
index 576c8c1..02e0515 100644
--- a/core/java/android/view/Window.java
+++ b/core/java/android/view/Window.java
@@ -56,11 +56,11 @@
     public static final int FEATURE_CONTEXT_MENU = 6;
     /** Flag for custom title. You cannot combine this feature with other title features. */
     public static final int FEATURE_CUSTOM_TITLE = 7;
-    /*  Flag for asking for an OpenGL enabled window.
+    /** Flag for asking for an OpenGL enabled window.
         All 2D graphics will be handled by OpenGL ES.
-        Private for now, until it is better tested (not shipping in 1.0)
+        @hide
     */
-    private static final int FEATURE_OPENGL = 8;
+    public static final int FEATURE_OPENGL = 8;
     /** Flag for setting the progress bar's visibility to VISIBLE */
     public static final int PROGRESS_VISIBILITY_ON = -1;
     /** Flag for setting the progress bar's visibility to GONE */
diff --git a/core/java/android/view/WindowManagerPolicy.java b/core/java/android/view/WindowManagerPolicy.java
index 1371932..f4e9900 100644
--- a/core/java/android/view/WindowManagerPolicy.java
+++ b/core/java/android/view/WindowManagerPolicy.java
@@ -533,14 +533,15 @@
      * @param win The window that currently has focus.  This is where the key
      *            event will normally go.
      * @param code Key code.
-     * @param metaKeys TODO
+     * @param metaKeys bit mask of meta keys that are held.
      * @param down Is this a key press (true) or release (false)?
      * @param repeatCount Number of times a key down has repeated.
+     * @param flags event's flags.
      * @return Returns true if the policy consumed the event and it should
      * not be further dispatched.
      */
     public boolean interceptKeyTi(WindowState win, int code,
-                               int metaKeys, boolean down, int repeatCount);
+                               int metaKeys, boolean down, int repeatCount, int flags);
 
     /**
      * Called when layout of the windows is about to start.
@@ -792,6 +793,13 @@
     public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always);
     
     /**
+     * A special function that is called from the very low-level input queue
+     * to provide feedback to the user.  Currently only called for virtual
+     * keys.
+     */
+    public void keyFeedbackFromInput(KeyEvent event);
+    
+    /**
      * Called when we have stopped keeping the screen on because a window
      * requesting this is no longer visible.
      */
diff --git a/core/java/android/webkit/BrowserFrame.java b/core/java/android/webkit/BrowserFrame.java
index dbd2682..e6ccd70 100644
--- a/core/java/android/webkit/BrowserFrame.java
+++ b/core/java/android/webkit/BrowserFrame.java
@@ -109,6 +109,8 @@
             CacheManager.init(context);
             // create CookieSyncManager with current Context
             CookieSyncManager.createInstance(context);
+            // create PluginManager with current Context
+            PluginManager.getInstance(context);
         }
         AssetManager am = context.getAssets();
         nativeCreateFrame(w, am, proxy.getBackForwardList());
@@ -119,7 +121,7 @@
         mDatabase = WebViewDatabase.getInstance(context);
         mWebViewCore = w;
 
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.BROWSER_FRAME) {
             Log.v(LOGTAG, "BrowserFrame constructor: this=" + this);
         }
     }
@@ -341,7 +343,7 @@
         switch (msg.what) {
             case FRAME_COMPLETED: {
                 if (mSettings.getSavePassword() && hasPasswordField()) {
-                    if (WebView.DEBUG) {
+                    if (DebugFlags.BROWSER_FRAME) {
                         Assert.assertNotNull(mCallbackProxy.getBackForwardList()
                                 .getCurrentItem());
                     }
@@ -463,8 +465,6 @@
      * @param postData If the method is "POST" postData is sent as the request
      *                 body. Is null when empty.
      * @param cacheMode The cache mode to use when loading this resource.
-     * @param isHighPriority True if this resource needs to be put at the front
-     *                       of the network queue.
      * @param synchronous True if the load is synchronous.
      * @return A newly created LoadListener object.
      */
@@ -474,7 +474,6 @@
                                               HashMap headers,
                                               byte[] postData,
                                               int cacheMode,
-                                              boolean isHighPriority,
                                               boolean synchronous) {
         PerfChecker checker = new PerfChecker();
 
@@ -490,7 +489,7 @@
             }
             if (mSettings.getSavePassword() && hasPasswordField()) {
                 try {
-                    if (WebView.DEBUG) {
+                    if (DebugFlags.BROWSER_FRAME) {
                         Assert.assertNotNull(mCallbackProxy.getBackForwardList()
                                 .getCurrentItem());
                     }
@@ -538,10 +537,10 @@
         // is this resource the main-frame top-level page?
         boolean isMainFramePage = mIsMainFrame;
 
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.BROWSER_FRAME) {
             Log.v(LOGTAG, "startLoadingResource: url=" + url + ", method="
-                    + method + ", postData=" + postData + ", isHighPriority="
-                    + isHighPriority + ", isMainFramePage=" + isMainFramePage);
+                    + method + ", postData=" + postData + ", isMainFramePage="
+                    + isMainFramePage);
         }
 
         // Create a LoadListener
@@ -551,12 +550,14 @@
         mCallbackProxy.onLoadResource(url);
 
         if (LoadListener.getNativeLoaderCount() > MAX_OUTSTANDING_REQUESTS) {
+            // send an error message, so that loadListener can be deleted
+            // after this is returned. This is important as LoadListener's 
+            // nativeError will remove the request from its DocLoader's request
+            // list. But the set up is not done until this method is returned.
             loadListener.error(
                     android.net.http.EventHandler.ERROR, mContext.getString(
                             com.android.internal.R.string.httpErrorTooManyRequests));
-            loadListener.notifyError();
-            loadListener.tearDown();
-            return null;
+            return loadListener;
         }
 
         // during synchronous load, the WebViewCore thread is blocked, so we
@@ -566,8 +567,7 @@
             CacheManager.endCacheTransaction();
         }
 
-        FrameLoader loader = new FrameLoader(loadListener, mSettings,
-                method, isHighPriority);
+        FrameLoader loader = new FrameLoader(loadListener, mSettings, method);
         loader.setHeaders(headers);
         loader.setPostData(postData);
         // Set the load mode to the mode used for the current page.
diff --git a/core/java/android/webkit/CacheLoader.java b/core/java/android/webkit/CacheLoader.java
index 3e1b602..de8f888 100644
--- a/core/java/android/webkit/CacheLoader.java
+++ b/core/java/android/webkit/CacheLoader.java
@@ -17,6 +17,7 @@
 package android.webkit;
 
 import android.net.http.Headers;
+import android.text.TextUtils;
 
 /**
  * This class is a concrete implementation of StreamLoader that uses a
@@ -49,17 +50,22 @@
     @Override
     protected void buildHeaders(Headers headers) {
         StringBuilder sb = new StringBuilder(mCacheResult.mimeType);
-        if (mCacheResult.encoding != null &&
-                mCacheResult.encoding.length() > 0) {
+        if (!TextUtils.isEmpty(mCacheResult.encoding)) {
             sb.append(';');
             sb.append(mCacheResult.encoding);
         }
         headers.setContentType(sb.toString());
 
-        if (mCacheResult.location != null &&
-                mCacheResult.location.length() > 0) {
+        if (!TextUtils.isEmpty(mCacheResult.location)) {
             headers.setLocation(mCacheResult.location);
         }
-    }
 
+        if (!TextUtils.isEmpty(mCacheResult.expiresString)) {
+            headers.setExpires(mCacheResult.expiresString);
+        }
+
+        if (!TextUtils.isEmpty(mCacheResult.contentdisposition)) {
+            headers.setContentDisposition(mCacheResult.contentdisposition);
+        }
+    }
 }
diff --git a/core/java/android/webkit/CacheManager.java b/core/java/android/webkit/CacheManager.java
index 7897435..9a02fbe 100644
--- a/core/java/android/webkit/CacheManager.java
+++ b/core/java/android/webkit/CacheManager.java
@@ -51,7 +51,6 @@
 
     private static final String NO_STORE = "no-store";
     private static final String NO_CACHE = "no-cache";
-    private static final String PRIVATE  = "private";
     private static final String MAX_AGE = "max-age";
 
     private static long CACHE_THRESHOLD = 6 * 1024 * 1024;
@@ -80,12 +79,14 @@
         int httpStatusCode;
         long contentLength;
         long expires;
+        String expiresString;
         String localPath;
         String lastModified;
         String etag;
         String mimeType;
         String location;
         String encoding;
+        String contentdisposition;
 
         // these fields are NOT saved to the database
         InputStream inStream;
@@ -108,6 +109,13 @@
             return expires;
         }
 
+        /**
+         * @hide Pending API council approval
+         */
+        public String getExpiresString() {
+            return expiresString;
+        }
+
         public String getLastModified() {
             return lastModified;
         }
@@ -128,6 +136,13 @@
             return encoding;
         }
 
+        /**
+         * @hide Pending API council approval
+         */
+        public String getContentDisposition() {
+            return contentdisposition;
+        }
+
         // For out-of-package access to the underlying streams.
         public InputStream getInputStream() {
             return inStream;
@@ -321,7 +336,7 @@
             }
         }
 
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.CACHE_MANAGER) {
             Log.v(LOGTAG, "getCacheFile for url " + url);
         }
 
@@ -340,7 +355,7 @@
      * @hide - hide createCacheFile since it has a parameter of type headers, which is
      * in a hidden package.
      */
-    // can be called from any thread
+    // only called from WebCore thread
     public static CacheResult createCacheFile(String url, int statusCode,
             Headers headers, String mimeType, boolean forceCache) {
         if (!forceCache && mDisabled) {
@@ -349,17 +364,25 @@
 
         // according to the rfc 2616, the 303 response MUST NOT be cached.
         if (statusCode == 303) {
+            // remove the saved cache if there is any
+            mDataBase.removeCache(url);
             return null;
         }
 
         // like the other browsers, do not cache redirects containing a cookie
         // header.
         if (checkCacheRedirect(statusCode) && !headers.getSetCookie().isEmpty()) {
+            // remove the saved cache if there is any
+            mDataBase.removeCache(url);
             return null;
         }
 
         CacheResult ret = parseHeaders(statusCode, headers, mimeType);
-        if (ret != null) {
+        if (ret == null) {
+            // this should only happen if the headers has "no-store" in the
+            // cache-control. remove the saved cache if there is any
+            mDataBase.removeCache(url);
+        } else {
             setupFiles(url, ret);
             try {
                 ret.outStream = new FileOutputStream(ret.outFile);
@@ -415,7 +438,7 @@
 
         mDataBase.addCache(url, cacheRet);
 
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.CACHE_MANAGER) {
             Log.v(LOGTAG, "saveCacheFile for url " + url);
         }
     }
@@ -596,21 +619,27 @@
         if (location != null) ret.location = location;
 
         ret.expires = -1;
-        String expires = headers.getExpires();
-        if (expires != null) {
+        ret.expiresString = headers.getExpires();
+        if (ret.expiresString != null) {
             try {
-                ret.expires = HttpDateTime.parse(expires);
+                ret.expires = HttpDateTime.parse(ret.expiresString);
             } catch (IllegalArgumentException ex) {
                 // Take care of the special "-1" and "0" cases
-                if ("-1".equals(expires) || "0".equals(expires)) {
+                if ("-1".equals(ret.expiresString)
+                        || "0".equals(ret.expiresString)) {
                     // make it expired, but can be used for history navigation
                     ret.expires = 0;
                 } else {
-                    Log.e(LOGTAG, "illegal expires: " + expires);
+                    Log.e(LOGTAG, "illegal expires: " + ret.expiresString);
                 }
             }
         }
 
+        String contentDisposition = headers.getContentDisposition();
+        if (contentDisposition != null) {
+            ret.contentdisposition = contentDisposition;
+        }
+
         String lastModified = headers.getLastModified();
         if (lastModified != null) ret.lastModified = lastModified;
 
@@ -628,7 +657,7 @@
                 // must be re-validated on every load. It does not mean that
                 // the content can not be cached. set to expire 0 means it
                 // can only be used in CACHE_MODE_CACHE_ONLY case
-                if (NO_CACHE.equals(controls[i]) || PRIVATE.equals(controls[i])) {
+                if (NO_CACHE.equals(controls[i])) {
                     ret.expires = 0;
                 } else if (controls[i].startsWith(MAX_AGE)) {
                     int separator = controls[i].indexOf('=');
diff --git a/core/java/android/webkit/CallbackProxy.java b/core/java/android/webkit/CallbackProxy.java
index 17d3f94..3b67fb6 100644
--- a/core/java/android/webkit/CallbackProxy.java
+++ b/core/java/android/webkit/CallbackProxy.java
@@ -72,36 +72,38 @@
     private final Context mContext;
 
     // Message Ids
-    private static final int PAGE_STARTED         = 100;
-    private static final int RECEIVED_ICON        = 101;
-    private static final int RECEIVED_TITLE       = 102;
-    private static final int OVERRIDE_URL         = 103;
-    private static final int AUTH_REQUEST         = 104;
-    private static final int SSL_ERROR            = 105;
-    private static final int PROGRESS             = 106;
-    private static final int UPDATE_VISITED       = 107;
-    private static final int LOAD_RESOURCE        = 108;
-    private static final int CREATE_WINDOW        = 109;
-    private static final int CLOSE_WINDOW         = 110;
-    private static final int SAVE_PASSWORD        = 111;
-    private static final int JS_ALERT             = 112;
-    private static final int JS_CONFIRM           = 113;
-    private static final int JS_PROMPT            = 114;
-    private static final int JS_UNLOAD            = 115;
-    private static final int ASYNC_KEYEVENTS      = 116;
-    private static final int TOO_MANY_REDIRECTS   = 117;
-    private static final int DOWNLOAD_FILE        = 118;
-    private static final int REPORT_ERROR         = 119;
-    private static final int RESEND_POST_DATA     = 120;
-    private static final int PAGE_FINISHED        = 121;
-    private static final int REQUEST_FOCUS        = 122;
-    private static final int SCALE_CHANGED        = 123;
-    private static final int RECEIVED_CERTIFICATE = 124;
-    private static final int SWITCH_OUT_HISTORY   = 125;
-    private static final int JS_TIMEOUT           = 126;
+    private static final int PAGE_STARTED              = 100;
+    private static final int RECEIVED_ICON             = 101;
+    private static final int RECEIVED_TITLE            = 102;
+    private static final int OVERRIDE_URL              = 103;
+    private static final int AUTH_REQUEST              = 104;
+    private static final int SSL_ERROR                 = 105;
+    private static final int PROGRESS                  = 106;
+    private static final int UPDATE_VISITED            = 107;
+    private static final int LOAD_RESOURCE             = 108;
+    private static final int CREATE_WINDOW             = 109;
+    private static final int CLOSE_WINDOW              = 110;
+    private static final int SAVE_PASSWORD             = 111;
+    private static final int JS_ALERT                  = 112;
+    private static final int JS_CONFIRM                = 113;
+    private static final int JS_PROMPT                 = 114;
+    private static final int JS_UNLOAD                 = 115;
+    private static final int ASYNC_KEYEVENTS           = 116;
+    private static final int TOO_MANY_REDIRECTS        = 117;
+    private static final int DOWNLOAD_FILE             = 118;
+    private static final int REPORT_ERROR              = 119;
+    private static final int RESEND_POST_DATA          = 120;
+    private static final int PAGE_FINISHED             = 121;
+    private static final int REQUEST_FOCUS             = 122;
+    private static final int SCALE_CHANGED             = 123;
+    private static final int RECEIVED_CERTIFICATE      = 124;
+    private static final int SWITCH_OUT_HISTORY        = 125;
+    private static final int EXCEEDED_DATABASE_QUOTA   = 126;
+    private static final int JS_TIMEOUT                = 127;
+    private static final int ADD_MESSAGE_TO_CONSOLE    = 128;
 
     // Message triggered by the client to resume execution
-    private static final int NOTIFY               = 200;
+    private static final int NOTIFY                    = 200;
 
     // Result transportation object for returning results across thread
     // boundaries.
@@ -145,6 +147,16 @@
     }
 
     /**
+     * Get the WebChromeClient.
+     * @return the current WebChromeClient instance.
+     *
+     *@hide pending API council approval.
+     */
+    public WebChromeClient getWebChromeClient() {
+       return mWebChromeClient;
+    }
+
+    /**
      * Set the client DownloadListener.
      * @param client An implementation of DownloadListener.
      */
@@ -389,6 +401,23 @@
                 }
                 break;
 
+            case EXCEEDED_DATABASE_QUOTA:
+                if (mWebChromeClient != null) {
+                    HashMap<String, Object> map =
+                            (HashMap<String, Object>) msg.obj;
+                    String databaseIdentifier =
+                            (String) map.get("databaseIdentifier");
+                    String url = (String) map.get("url");
+                    long currentQuota =
+                            ((Long) map.get("currentQuota")).longValue();
+                    WebStorage.QuotaUpdater quotaUpdater =
+                        (WebStorage.QuotaUpdater) map.get("quotaUpdater");
+
+                    mWebChromeClient.onExceededDatabaseQuota(url,
+                            databaseIdentifier, currentQuota, quotaUpdater);
+                }
+                break;
+
             case JS_ALERT:
                 if (mWebChromeClient != null) {
                     final JsResult res = (JsResult) msg.obj;
@@ -563,6 +592,13 @@
             case SWITCH_OUT_HISTORY:
                 mWebView.switchOutDrawHistory();
                 break;
+
+            case ADD_MESSAGE_TO_CONSOLE:
+                String message = msg.getData().getString("message");
+                String sourceID = msg.getData().getString("sourceID");
+                int lineNumber = msg.getData().getInt("lineNumber");
+                mWebChromeClient.addMessageToConsole(message, lineNumber, sourceID);
+                break;
         }
     }
 
@@ -605,7 +641,40 @@
     //--------------------------------------------------------------------------
 
     // Performance probe
+    private static final boolean PERF_PROBE = false;
     private long mWebCoreThreadTime;
+    private long mWebCoreIdleTime;
+
+    /*
+     * If PERF_PROBE is true, this block needs to be added to MessageQueue.java.
+     * startWait() and finishWait() should be called before and after wait().
+
+    private WaitCallback mWaitCallback = null;
+    public static interface WaitCallback {
+        void startWait();
+        void finishWait();
+    }
+    public final void setWaitCallback(WaitCallback callback) {
+        mWaitCallback = callback;
+    }
+    */
+
+    // un-comment this block if PERF_PROBE is true
+    /*
+    private IdleCallback mIdleCallback = new IdleCallback();
+
+    private final class IdleCallback implements MessageQueue.WaitCallback {
+        private long mStartTime = 0;
+
+        public void finishWait() {
+            mWebCoreIdleTime += SystemClock.uptimeMillis() - mStartTime;
+        }
+
+        public void startWait() {
+            mStartTime = SystemClock.uptimeMillis();
+        }
+    }
+    */
 
     public void onPageStarted(String url, Bitmap favicon) {
         // Do an unsynchronized quick check to avoid posting if no callback has
@@ -614,9 +683,12 @@
             return;
         }
         // Performance probe
-        if (false) {
+        if (PERF_PROBE) {
             mWebCoreThreadTime = SystemClock.currentThreadTimeMillis();
+            mWebCoreIdleTime = 0;
             Network.getInstance(mContext).startTiming();
+            // un-comment this if PERF_PROBE is true
+//            Looper.myQueue().setWaitCallback(mIdleCallback);
         }
         Message msg = obtainMessage(PAGE_STARTED);
         msg.obj = favicon;
@@ -631,10 +703,12 @@
             return;
         }
         // Performance probe
-        if (false) {
+        if (PERF_PROBE) {
+            // un-comment this if PERF_PROBE is true
+//            Looper.myQueue().setWaitCallback(null);
             Log.d("WebCore", "WebCore thread used " + 
                     (SystemClock.currentThreadTimeMillis() - mWebCoreThreadTime)
-                    + " ms");
+                    + " ms and idled " + mWebCoreIdleTime + " ms");
             Network.getInstance(mContext).stopTiming();
         }
         Message msg = obtainMessage(PAGE_FINISHED, url);
@@ -834,7 +908,7 @@
             String password, Message resumeMsg) {
         // resumeMsg should be null at this point because we want to create it
         // within the CallbackProxy.
-        if (WebView.DEBUG) {
+        if (DebugFlags.CALLBACK_PROXY) {
             junit.framework.Assert.assertNull(resumeMsg);
         }
         resumeMsg = obtainMessage(NOTIFY);
@@ -1037,6 +1111,60 @@
     }
 
     /**
+     * Called by WebViewCore to inform the Java side that the current origin
+     * has overflowed it's database quota. Called in the WebCore thread so
+     * posts a message to the UI thread that will prompt the WebChromeClient
+     * for what to do. On return back to C++ side, the WebCore thread will
+     * sleep pending a new quota value.
+     * @param url The URL that caused the quota overflow.
+     * @param databaseIdentifier The identifier of the database that the
+     *     transaction that caused the overflow was running on.
+     * @param currentQuota The current quota the origin is allowed.
+     * @param quotaUpdater An instance of a class encapsulating a callback
+     *     to WebViewCore to run when the decision to allow or deny more
+     *     quota has been made.
+     */
+    public void onExceededDatabaseQuota(
+            String url, String databaseIdentifier, long currentQuota,
+            WebStorage.QuotaUpdater quotaUpdater) {
+        if (mWebChromeClient == null) {
+            quotaUpdater.updateQuota(currentQuota);
+            return;
+        }
+
+        Message exceededQuota = obtainMessage(EXCEEDED_DATABASE_QUOTA);
+        HashMap<String, Object> map = new HashMap();
+        map.put("databaseIdentifier", databaseIdentifier);
+        map.put("url", url);
+        map.put("currentQuota", currentQuota);
+        map.put("quotaUpdater", quotaUpdater);
+        exceededQuota.obj = map;
+        sendMessage(exceededQuota);
+    }
+
+    /**
+     * Called by WebViewCore when we have a message to be added to the JavaScript
+     * error console. Sends a message to the Java side with the details.
+     * @param message The message to add to the console.
+     * @param lineNumber The lineNumber of the source file on which the error
+     *     occurred.
+     * @param sourceID The filename of the source file in which the error
+     *     occurred.
+     * @hide pending API counsel.
+     */
+    public void addMessageToConsole(String message, int lineNumber, String sourceID) {
+        if (mWebChromeClient == null) {
+            return;
+        }
+
+        Message msg = obtainMessage(ADD_MESSAGE_TO_CONSOLE);
+        msg.getData().putString("message", message);
+        msg.getData().putString("sourceID", sourceID);
+        msg.getData().putInt("lineNumber", lineNumber);
+        sendMessage(msg);
+    }
+
+    /**
      * @hide pending API council approval
      */
     public boolean onJsTimeout() {
diff --git a/core/java/android/webkit/CookieManager.java b/core/java/android/webkit/CookieManager.java
index e8c2279..7b91724 100644
--- a/core/java/android/webkit/CookieManager.java
+++ b/core/java/android/webkit/CookieManager.java
@@ -262,7 +262,7 @@
         if (!mAcceptCookie || uri == null) {
             return;
         }
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.COOKIE_MANAGER) {
             Log.v(LOGTAG, "setCookie: uri: " + uri + " value: " + value);
         }
 
@@ -427,12 +427,12 @@
             }
         }
         if (ret.length() > 0) {
-            if (WebView.LOGV_ENABLED) {
+            if (DebugFlags.COOKIE_MANAGER) {
                 Log.v(LOGTAG, "getCookie: uri: " + uri + " value: " + ret);
             }
             return ret.toString();
         } else {
-            if (WebView.LOGV_ENABLED) {
+            if (DebugFlags.COOKIE_MANAGER) {
                 Log.v(LOGTAG, "getCookie: uri: " + uri
                         + " But can't find cookie.");
             }
@@ -588,7 +588,7 @@
             Iterator<ArrayList<Cookie>> listIter = cookieLists.iterator();
             while (listIter.hasNext() && count < MAX_RAM_COOKIES_COUNT) {
                 ArrayList<Cookie> list = listIter.next();
-                if (WebView.DEBUG) {
+                if (DebugFlags.COOKIE_MANAGER) {
                     Iterator<Cookie> iter = list.iterator();
                     while (iter.hasNext() && count < MAX_RAM_COOKIES_COUNT) {
                         Cookie cookie = iter.next();
@@ -608,7 +608,7 @@
 
         ArrayList<Cookie> retlist = new ArrayList<Cookie>();
         if (mapSize >= MAX_RAM_DOMAIN_COUNT || count >= MAX_RAM_COOKIES_COUNT) {
-            if (WebView.DEBUG) {
+            if (DebugFlags.COOKIE_MANAGER) {
                 Log.v(LOGTAG, count + " cookies used " + byteCount
                         + " bytes with " + mapSize + " domains");
             }
@@ -616,7 +616,7 @@
             int toGo = mapSize / 10 + 1;
             while (toGo-- > 0){
                 String domain = domains[toGo].toString();
-                if (WebView.LOGV_ENABLED) {
+                if (DebugFlags.COOKIE_MANAGER) {
                     Log.v(LOGTAG, "delete domain: " + domain
                             + " from RAM cache");
                 }
diff --git a/core/java/android/webkit/CookieSyncManager.java b/core/java/android/webkit/CookieSyncManager.java
index 8d66529..14375d2 100644
--- a/core/java/android/webkit/CookieSyncManager.java
+++ b/core/java/android/webkit/CookieSyncManager.java
@@ -24,30 +24,39 @@
 import java.util.Iterator;
 
 /**
- * The class CookieSyncManager is used to synchronize the browser cookies
- * between RAM and FLASH. To get the best performance, browser cookie is saved
- * in RAM. We use a separate thread to sync the cookies between RAM and FLASH on
- * a timer base.
+ * The CookieSyncManager is used to synchronize the browser cookie store
+ * between RAM and permanent storage. To get the best performance, browser cookies are
+ * saved in RAM. A separate thread saves the cookies between, driven by a timer.
  * <p>
+ *
  * To use the CookieSyncManager, the host application has to call the following
- * when the application starts.
+ * when the application starts:
  * <p>
- * CookieSyncManager.createInstance(context)
+ *
+ * <pre class="prettyprint">CookieSyncManager.createInstance(context)</pre><p>
+ *
+ * To set up for sync, the host application has to call<p>
+ * <pre class="prettyprint">CookieSyncManager.getInstance().startSync()</pre><p>
+ *
+ * in Activity.onResume(), and call
  * <p>
- * To set up for sync, the host application has to call
- * <p>
- * CookieSyncManager.getInstance().startSync()
- * <p>
- * in its Activity.onResume(), and call
- * <p>
+ *
+ * <pre class="prettyprint">
  * CookieSyncManager.getInstance().stopSync()
- * <p>
- * in its Activity.onStop().
- * <p>
+ * </pre><p>
+ *
+ * in Activity.onPause().<p>
+ *
  * To get instant sync instead of waiting for the timer to trigger, the host can
  * call
  * <p>
- * CookieSyncManager.getInstance().sync()
+ * <pre class="prettyprint">CookieSyncManager.getInstance().sync()</pre><p>
+ *
+ * The sync interval is 5 minutes, so you will want to force syncs
+ * manually anyway, for instance in {@link
+ * WebViewClient#onPageFinished}. Note that even sync() happens
+ * asynchronously, so don't do it just as your activity is shutting
+ * down.
  */
 public final class CookieSyncManager extends WebSyncManager {
 
@@ -90,7 +99,7 @@
     }
 
     /**
-     * Package level api, called from CookieManager Get all the cookies which
+     * Package level api, called from CookieManager. Get all the cookies which
      * matches a given base domain.
      * @param domain
      * @return A list of Cookie
@@ -161,7 +170,7 @@
     }
 
     protected void syncFromRamToFlash() {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.COOKIE_SYNC_MANAGER) {
             Log.v(LOGTAG, "CookieSyncManager::syncFromRamToFlash STARTS");
         }
 
@@ -178,7 +187,7 @@
                 CookieManager.getInstance().deleteLRUDomain();
         syncFromRamToFlash(lruList);
 
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.COOKIE_SYNC_MANAGER) {
             Log.v(LOGTAG, "CookieSyncManager::syncFromRamToFlash DONE");
         }
     }
diff --git a/core/java/android/webkit/DataLoader.java b/core/java/android/webkit/DataLoader.java
index dcdc949..6c5d10d 100644
--- a/core/java/android/webkit/DataLoader.java
+++ b/core/java/android/webkit/DataLoader.java
@@ -16,12 +16,10 @@
 
 package android.webkit;
 
-import org.apache.http.protocol.HTTP;
-
-import android.net.http.Headers;
-
 import java.io.ByteArrayInputStream;
 
+import org.apache.harmony.luni.util.Base64;
+
 /**
  * This class is a concrete implementation of StreamLoader that uses the
  * content supplied as a URL as the source for the stream. The mimetype
@@ -30,8 +28,6 @@
  */
 class DataLoader extends StreamLoader {
 
-    private String mContentType;  // Content mimetype, if supplied in URL
-
     /**
      * Constructor uses the dataURL as the source for an InputStream
      * @param dataUrl data: URL string optionally containing a mimetype
@@ -41,16 +37,20 @@
         super(loadListener);
 
         String url = dataUrl.substring("data:".length());
-        String content;
+        byte[] data = null;
         int commaIndex = url.indexOf(',');
         if (commaIndex != -1) {
-            mContentType = url.substring(0, commaIndex);
-            content = url.substring(commaIndex + 1);
+            String contentType = url.substring(0, commaIndex);
+            data = url.substring(commaIndex + 1).getBytes();
+            loadListener.parseContentTypeHeader(contentType);
+            if ("base64".equals(loadListener.transferEncoding())) {
+                data = Base64.decode(data);
+            }
         } else {
-            content = url;
+            data = url.getBytes();
         }
-        mDataStream = new ByteArrayInputStream(content.getBytes());
-        mContentLength = content.length();
+        mDataStream = new ByteArrayInputStream(data);
+        mContentLength = data.length;
     }
 
     @Override
@@ -60,10 +60,7 @@
     }
 
     @Override
-    protected void buildHeaders(Headers headers) {
-        if (mContentType != null) {
-            headers.setContentType(mContentType);
-        }
+    protected void buildHeaders(android.net.http.Headers h) {
     }
 
     /**
diff --git a/core/java/android/webkit/DebugFlags.java b/core/java/android/webkit/DebugFlags.java
new file mode 100644
index 0000000..8e25395
--- /dev/null
+++ b/core/java/android/webkit/DebugFlags.java
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+package android.webkit;
+
+/**
+ * This class is a container for all of the debug flags used in the Java
+ * components of webkit.  These flags must be final in order to ensure that
+ * the compiler optimizes the code that uses them out of the final executable.
+ *
+ * The name of each flags maps directly to the name of the class in which that
+ * flag is used.
+ *
+ */
+class DebugFlags {
+
+    public static final boolean BROWSER_FRAME = false;
+    public static final boolean CACHE_MANAGER = false;
+    public static final boolean CALLBACK_PROXY = false;
+    public static final boolean COOKIE_MANAGER = false;
+    public static final boolean COOKIE_SYNC_MANAGER = false;
+    public static final boolean FRAME_LOADER = false;
+    public static final boolean J_WEB_CORE_JAVA_BRIDGE = false;// HIGHLY VERBOSE
+    public static final boolean LOAD_LISTENER = false;
+    public static final boolean NETWORK = false;
+    public static final boolean SSL_ERROR_HANDLER = false;
+    public static final boolean STREAM_LOADER = false;
+    public static final boolean URL_UTIL = false;
+    public static final boolean WEB_BACK_FORWARD_LIST = false;
+    public static final boolean WEB_SETTINGS = false;
+    public static final boolean WEB_SYNC_MANAGER = false;
+    public static final boolean WEB_TEXT_VIEW = false;
+    public static final boolean WEB_VIEW = false;
+    public static final boolean WEB_VIEW_CORE = false;
+
+}
diff --git a/core/java/android/webkit/FrameLoader.java b/core/java/android/webkit/FrameLoader.java
index 66ab021..8298729 100644
--- a/core/java/android/webkit/FrameLoader.java
+++ b/core/java/android/webkit/FrameLoader.java
@@ -28,7 +28,6 @@
 
     private final LoadListener mListener;
     private final String mMethod;
-    private final boolean mIsHighPriority;
     private final WebSettings mSettings;
     private Map<String, String> mHeaders;
     private byte[] mPostData;
@@ -52,11 +51,10 @@
     private static final String LOGTAG = "webkit";
     
     FrameLoader(LoadListener listener, WebSettings settings,
-            String method, boolean highPriority) {
+            String method) {
         mListener = listener;
         mHeaders = null;
         mMethod = method;
-        mIsHighPriority = highPriority;
         mCacheMode = WebSettings.LOAD_NORMAL;
         mSettings = settings;
     }
@@ -120,7 +118,7 @@
         } else if (handleLocalFile(url, mListener, mSettings)) {
             return true;
         }
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.FRAME_LOADER) {
             Log.v(LOGTAG, "FrameLoader.executeLoad: url protocol not supported:"
                     + mListener.url());
         }
@@ -175,12 +173,11 @@
             // as response from the cache could be a redirect
             // and we may need to initiate a network request if the cache
             // can't satisfy redirect URL
-            mListener.setRequestData(mMethod, mHeaders, mPostData, 
-                    mIsHighPriority);
+            mListener.setRequestData(mMethod, mHeaders, mPostData);
             return true;
         }
 
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.FRAME_LOADER) {
             Log.v(LOGTAG, "FrameLoader: http " + mMethod + " load for: "
                     + mListener.url());
         }
@@ -190,7 +187,7 @@
         
         try {
             ret = mNetwork.requestURL(mMethod, mHeaders,
-                    mPostData, mListener, mIsHighPriority);
+                    mPostData, mListener);
         } catch (android.net.ParseException ex) {
             error = EventHandler.ERROR_BAD_URL;
         } catch (java.lang.RuntimeException ex) {
@@ -211,7 +208,7 @@
      * setup a load from the byte stream in a CacheResult.
      */
     private void startCacheLoad(CacheResult result) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.FRAME_LOADER) {
             Log.v(LOGTAG, "FrameLoader: loading from cache: "
                   + mListener.url());
         }
@@ -285,7 +282,7 @@
             // of it's state. If it is not in the cache, then go to the 
             // network.
             case WebSettings.LOAD_CACHE_ELSE_NETWORK: {
-                if (WebView.LOGV_ENABLED) {
+                if (DebugFlags.FRAME_LOADER) {
                     Log.v(LOGTAG, "FrameLoader: checking cache: "
                             + mListener.url());
                 }
diff --git a/core/java/android/webkit/GearsPermissionsManager.java b/core/java/android/webkit/GearsPermissionsManager.java
deleted file mode 100644
index e70e449..0000000
--- a/core/java/android/webkit/GearsPermissionsManager.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * 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.
- */
-
-package android.webkit;
-
-import android.content.ContentResolver;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-import android.database.ContentObserver;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteException;
-import android.database.sqlite.SQLiteStatement;
-import android.os.Handler;
-import android.preference.PreferenceManager;
-import android.provider.Settings;
-import android.util.Log;
-
-import java.io.File;
-import java.util.HashSet;
-
-/**
- *  Donut-specific hack to keep Gears permissions in sync with the
- *  system location setting.
- */
-class GearsPermissionsManager {
-    // The application context.
-    Context mContext;
-    // The path to gears.so.
-    private String mGearsPath;
-
-    // The Gears permissions database directory.
-    private final static String GEARS_DATABASE_DIR = "gears";
-    // The Gears permissions database file name.
-    private final static String GEARS_DATABASE_FILE = "permissions.db";
-    // The Gears location permissions table.
-    private final static String GEARS_LOCATION_ACCESS_TABLE_NAME =
-        "LocationAccess";
-    // The Gears storage access permissions table.
-    private final static String GEARS_STORAGE_ACCESS_TABLE_NAME = "Access";
-    // The Gears permissions db schema version table.
-    private final static String GEARS_SCHEMA_VERSION_TABLE_NAME =
-        "VersionInfo";
-    // The Gears permission value that denotes "allow access to location".
-    private static final int GEARS_ALLOW_LOCATION_ACCESS = 1;
-    // The shared pref name.
-    private static final String LAST_KNOWN_LOCATION_SETTING =
-        "lastKnownLocationSystemSetting";
-    // The Browser package name.
-    private static final String BROWSER_PACKAGE_NAME = "com.android.browser";
-    // The Secure Settings observer that will be notified when the system
-    // location setting changes.
-    private SecureSettingsObserver mSettingsObserver;
-    // The Google URLs whitelisted for Gears location access.
-    private static HashSet<String> sGearsWhiteList;
-
-    static {
-        sGearsWhiteList = new HashSet<String>();
-        // NOTE: DO NOT ADD A "/" AT THE END!
-        sGearsWhiteList.add("http://www.google.com");
-        sGearsWhiteList.add("http://www.google.co.uk");
-    }
-
-    private static final String LOGTAG = "webcore";
-    static final boolean DEBUG = false;
-    static final boolean LOGV_ENABLED = DEBUG;
-
-    GearsPermissionsManager(Context context, String gearsPath) {
-        mContext = context;
-        mGearsPath = gearsPath;
-    }
-
-    public void doCheckAndStartObserver() {
-     // Are we running in the browser?
-        if (!BROWSER_PACKAGE_NAME.equals(mContext.getPackageName())) {
-            return;
-        }
-        // Do the check.
-        checkGearsPermissions();
-        // Install the observer.
-        mSettingsObserver = new SecureSettingsObserver();
-        mSettingsObserver.observe();
-    }
-
-    private void checkGearsPermissions() {
-        // Get the current system settings.
-        int setting = Settings.Secure.getInt(mContext.getContentResolver(),
-                Settings.Secure.USE_LOCATION_FOR_SERVICES, -1);
-        // Check if we need to set the Gears permissions.
-        if (setting != -1 && locationSystemSettingChanged(setting)) {
-            setGearsPermissionForGoogleDomains(setting);
-        }
-    }
-
-    private boolean locationSystemSettingChanged(int newSetting) {
-        SharedPreferences prefs =
-            PreferenceManager.getDefaultSharedPreferences(mContext);
-        int oldSetting = 0;
-        oldSetting = prefs.getInt(LAST_KNOWN_LOCATION_SETTING, oldSetting);
-        if (oldSetting == newSetting) {
-            return false;
-        }
-        Editor ed = prefs.edit();
-        ed.putInt(LAST_KNOWN_LOCATION_SETTING, newSetting);
-        ed.commit();
-        return true;
-    }
-
-    private void setGearsPermissionForGoogleDomains(int systemPermission) {
-        // Transform the system permission into a boolean flag. When this
-        // flag is true, it means the origins in gGearsWhiteList are added
-        // to the Gears location permission table with permission 1 (allowed).
-        // When the flag is false, the origins in gGearsWhiteList are removed
-        // from the Gears location permission table. Next time the user
-        // navigates to one of these origins, she will see the normal Gears
-        // permission prompt.
-        boolean addToGearsLocationTable = (systemPermission == 1 ? true : false);
-        // Build the path to the Gears library.
-
-        File file = new File(mGearsPath).getParentFile();
-        if (file == null) {
-            return;
-        }
-        // Build the Gears database file name.
-        file = new File(file.getAbsolutePath() + File.separator
-                + GEARS_DATABASE_DIR + File.separator + GEARS_DATABASE_FILE);
-        // Remember whether or not we need to create the LocationAccess table.
-        boolean needToCreateTables = !file.exists();
-        // If the database file does not yet exist and the system location
-        // setting says that the Gears origins need to be removed from the
-        // location permission table, it means that we don't actually need
-        // to do anything at all.
-        if (needToCreateTables && !addToGearsLocationTable) {
-            return;
-        }
-        // Try opening the Gears database.
-        SQLiteDatabase permissions;
-        try {
-            permissions = SQLiteDatabase.openOrCreateDatabase(file, null);
-        } catch (SQLiteException e) {
-            if (LOGV_ENABLED) {
-                Log.v(LOGTAG, "Could not open Gears permission DB: "
-                        + e.getMessage());
-            }
-            // Just bail out.
-            return;
-        }
-        // We now have a database open. Begin a transaction.
-        permissions.beginTransaction();
-        try {
-            if (needToCreateTables) {
-                // Create the tables. Note that this creates the
-                // Gears tables for the permissions DB schema version 2.
-                // The Gears schema upgrade process will take care of the rest.
-                // First, the storage access table.
-                SQLiteStatement statement = permissions.compileStatement(
-                        "CREATE TABLE IF NOT EXISTS "
-                        + GEARS_STORAGE_ACCESS_TABLE_NAME
-                        + " (Name TEXT UNIQUE, Value)");
-                statement.execute();
-                // Next the location access table.
-                statement = permissions.compileStatement(
-                        "CREATE TABLE IF NOT EXISTS "
-                        + GEARS_LOCATION_ACCESS_TABLE_NAME
-                        + " (Name TEXT UNIQUE, Value)");
-                statement.execute();
-                // Finally, the schema version table.
-                statement = permissions.compileStatement(
-                        "CREATE TABLE IF NOT EXISTS "
-                        + GEARS_SCHEMA_VERSION_TABLE_NAME
-                        + " (Name TEXT UNIQUE, Value)");
-                statement.execute();
-                // Set the schema version to 2.
-                ContentValues schema = new ContentValues();
-                schema.put("Name", "Version");
-                schema.put("Value", 2);
-                permissions.insert(GEARS_SCHEMA_VERSION_TABLE_NAME, null,
-                        schema);
-            }
-
-            if (addToGearsLocationTable) {
-                ContentValues permissionValues = new ContentValues();
-
-                for (String url : sGearsWhiteList) {
-                    permissionValues.put("Name", url);
-                    permissionValues.put("Value", GEARS_ALLOW_LOCATION_ACCESS);
-                    permissions.replace(GEARS_LOCATION_ACCESS_TABLE_NAME, null,
-                            permissionValues);
-                    permissionValues.clear();
-                }
-            } else {
-                for (String url : sGearsWhiteList) {
-                    permissions.delete(GEARS_LOCATION_ACCESS_TABLE_NAME, "Name=?",
-                            new String[] { url });
-                }
-            }
-            // Commit the transaction.
-            permissions.setTransactionSuccessful();
-        } catch (SQLiteException e) {
-            if (LOGV_ENABLED) {
-                Log.v(LOGTAG, "Could not set the Gears permissions: "
-                        + e.getMessage());
-            }
-        } finally {
-            permissions.endTransaction();
-            permissions.close();
-        }
-    }
-
-    class SecureSettingsObserver extends ContentObserver {
-        SecureSettingsObserver() {
-            super(new Handler());
-        }
-
-        void observe() {
-            ContentResolver resolver = mContext.getContentResolver();
-            resolver.registerContentObserver(Settings.Secure.getUriFor(
-                    Settings.Secure.USE_LOCATION_FOR_SERVICES), false, this);
-        }
-
-        @Override
-        public void onChange(boolean selfChange) {
-            checkGearsPermissions();
-        }
-    }
-}
diff --git a/core/java/android/webkit/HTML5VideoViewProxy.java b/core/java/android/webkit/HTML5VideoViewProxy.java
new file mode 100644
index 0000000..5a164f8
--- /dev/null
+++ b/core/java/android/webkit/HTML5VideoViewProxy.java
@@ -0,0 +1,232 @@
+/*
+ * 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.
+ */
+
+package android.webkit;
+
+import android.content.Context;
+import android.media.MediaPlayer;
+import android.media.MediaPlayer.OnPreparedListener;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.ViewGroup;
+import android.webkit.ViewManager.ChildView;
+import android.widget.AbsoluteLayout;
+import android.widget.MediaController;
+import android.widget.VideoView;
+
+import java.util.HashMap;
+
+/**
+ * <p>Proxy for HTML5 video views.
+ */
+class HTML5VideoViewProxy extends Handler {
+    // Logging tag.
+    private static final String LOGTAG = "HTML5VideoViewProxy";
+
+    // Message Ids for WebCore thread -> UI thread communication.
+    private static final int INIT              = 100;
+    private static final int PLAY              = 101;
+
+    // The WebView instance that created this view.
+    private WebView mWebView;
+    // The ChildView instance used by the ViewManager.
+    private ChildView mChildView;
+    // The VideoView instance. Note that we could
+    // also access this via mChildView.mView but it would
+    // always require cast, so it is more convenient to store
+    // it here as well.
+    private HTML5VideoView mVideoView;
+
+    // A VideoView subclass that responds to double-tap
+    // events by going fullscreen.
+    class HTML5VideoView extends VideoView {
+        // Used to save the layout parameters if the view
+        // is changed to fullscreen.
+        private AbsoluteLayout.LayoutParams mEmbeddedLayoutParams;
+        // Flag that denotes whether the view is fullscreen or not.
+        private boolean mIsFullscreen;
+        // Used to save the current playback position when
+        // transitioning to/from fullscreen.
+        private int mPlaybackPosition;
+        // The callback object passed to the host application. This callback
+        // is invoked when the host application dismisses our VideoView
+        // (e.g. the user presses the back key).
+        private WebChromeClient.CustomViewCallback mCallback =
+                new WebChromeClient.CustomViewCallback() {
+            public void onCustomViewHidden() {
+                playEmbedded();
+            }
+        };
+
+        // The OnPreparedListener, used to automatically resume
+        // playback when transitioning to/from fullscreen.
+        private MediaPlayer.OnPreparedListener mPreparedListener =
+                new MediaPlayer.OnPreparedListener() {
+            public void onPrepared(MediaPlayer mp) {
+                resumePlayback();
+            }
+        };
+
+        HTML5VideoView(Context context) {
+            super(context);
+        }
+
+        void savePlaybackPosition() {
+            if (isPlaying()) {
+                mPlaybackPosition = getCurrentPosition();
+            }
+        }
+
+        void resumePlayback() {
+            seekTo(mPlaybackPosition);
+            start();
+            setOnPreparedListener(null);
+        }
+
+        void playEmbedded() {
+            // Attach to the WebView.
+            mChildView.attachViewOnUIThread(mEmbeddedLayoutParams);
+            // Make sure we're visible
+            setVisibility(View.VISIBLE);
+            // Set the onPrepared listener so we start
+            // playing when the video view is reattached
+            // and its surface is recreated.
+            setOnPreparedListener(mPreparedListener);
+            mIsFullscreen = false;
+        }
+
+        void playFullScreen() {
+            WebChromeClient client = mWebView.getWebChromeClient();
+            if (client == null) {
+                return;
+            }
+            // Save the current layout params.
+            mEmbeddedLayoutParams =
+                    (AbsoluteLayout.LayoutParams) getLayoutParams();
+            // Detach from the WebView.
+            mChildView.removeViewOnUIThread();
+            // Attach to the browser UI.
+            client.onShowCustomView(this, mCallback);
+            // Set the onPrepared listener so we start
+            // playing when after the video view is reattached
+            // and its surface is recreated.
+            setOnPreparedListener(mPreparedListener);
+            mIsFullscreen = true;
+        }
+
+        @Override
+        public boolean onTouchEvent(MotionEvent ev) {
+            // TODO: implement properly (i.e. detect double tap)
+            if (mIsFullscreen || !isPlaying()) {
+                return super.onTouchEvent(ev);
+            }
+            playFullScreen();
+            return true;
+        }
+
+        @Override
+        public void onDetachedFromWindow() {
+            super.onDetachedFromWindow();
+            savePlaybackPosition();
+        }
+    }
+
+    /**
+     * Private constructor.
+     * @param context is the application context.
+     */
+    private HTML5VideoViewProxy(WebView webView) {
+        // This handler is for the main (UI) thread.
+        super(Looper.getMainLooper());
+        // Save the WebView object.
+        mWebView = webView;
+    }
+
+    @Override
+    public void handleMessage(Message msg) {
+        // This executes on the UI thread.
+        switch (msg.what) {
+            case INIT:
+                // Create the video view and set a default controller.
+                mVideoView = new HTML5VideoView(mWebView.getContext());
+                // This is needed because otherwise there will be a black square
+                // stuck on the screen.
+                mVideoView.setWillNotDraw(false);
+                mVideoView.setMediaController(new MediaController(mWebView.getContext()));
+                mChildView.mView = mVideoView;
+                break;
+            case PLAY:
+                if (mVideoView == null) {
+                    return;
+                }
+                HashMap<String, Object> map =
+                        (HashMap<String, Object>) msg.obj;
+                String url = (String) map.get("url");
+                mVideoView.setVideoURI(Uri.parse(url));
+                mVideoView.start();
+                break;
+        }
+    }
+
+    /**
+     * Play a video stream.
+     * @param url is the URL of the video stream.
+     * @param webview is the WebViewCore that is requesting the playback.
+     */
+    public void play(String url) {
+         // We need to know the webview that is requesting the playback.
+        Message message = obtainMessage(PLAY);
+        HashMap<String, Object> map = new HashMap();
+        map.put("url", url);
+        message.obj = map;
+        sendMessage(message);
+    }
+
+    public void createView() {
+        mChildView = mWebView.mViewManager.createView();
+        sendMessage(obtainMessage(INIT));
+    }
+
+    public void attachView(int x, int y, int width, int height) {
+        if (mChildView == null) {
+            return;
+        }
+        mChildView.attachView(x, y, width, height);
+    }
+
+    public void removeView() {
+        if (mChildView == null) {
+            return;
+        }
+        mChildView.removeView();
+    }
+
+    /**
+     * The factory for HTML5VideoViewProxy instances.
+     * @param webViewCore is the WebViewCore that is requesting the proxy.
+     *
+     * @return a new HTML5VideoViewProxy object.
+     */
+    public static HTML5VideoViewProxy getInstance(WebViewCore webViewCore) {
+        return new HTML5VideoViewProxy(webViewCore.getWebView());
+    }
+}
diff --git a/core/java/android/webkit/HttpDateTime.java b/core/java/android/webkit/HttpDateTime.java
index c6ec2d2..00b2731 100644
--- a/core/java/android/webkit/HttpDateTime.java
+++ b/core/java/android/webkit/HttpDateTime.java
@@ -23,7 +23,8 @@
 import java.util.regex.Pattern;
 
 
-class HttpDateTime {
+/** {@hide} */
+public final class HttpDateTime {
 
     /*
      * Regular expression for parsing HTTP-date.
@@ -47,14 +48,16 @@
      * Wdy, DD Mon YYYY HH:MM:SS
      * Wdy Mon (SP)D HH:MM:SS YYYY
      * Wdy Mon DD HH:MM:SS YYYY GMT
+     * 
+     * HH can be H if the first digit is zero.
      */
     private static final String HTTP_DATE_RFC_REGEXP =
             "([0-9]{1,2})[- ]([A-Za-z]{3,3})[- ]([0-9]{2,4})[ ]"
-            + "([0-9][0-9]:[0-9][0-9]:[0-9][0-9])";
+            + "([0-9]{1,2}:[0-9][0-9]:[0-9][0-9])";
 
     private static final String HTTP_DATE_ANSIC_REGEXP =
             "[ ]([A-Za-z]{3,3})[ ]+([0-9]{1,2})[ ]"
-            + "([0-9][0-9]:[0-9][0-9]:[0-9][0-9])[ ]([0-9]{2,4})";
+            + "([0-9]{1,2}:[0-9][0-9]:[0-9][0-9])[ ]([0-9]{2,4})";
 
     /**
      * The compiled version of the HTTP-date regular expressions.
@@ -65,6 +68,12 @@
             Pattern.compile(HTTP_DATE_ANSIC_REGEXP);
 
     private static class TimeOfDay {
+        TimeOfDay(int h, int m, int s) {
+            this.hour = h;
+            this.minute = m;
+            this.second = s;
+        }
+        
         int hour;
         int minute;
         int second;
@@ -76,7 +85,7 @@
         int date = 1;
         int month = Calendar.JANUARY;
         int year = 1970;
-        TimeOfDay timeOfDay = new TimeOfDay();
+        TimeOfDay timeOfDay;
 
         Matcher rfcMatcher = HTTP_DATE_RFC_PATTERN.matcher(timeString);
         if (rfcMatcher.find()) {
@@ -183,13 +192,22 @@
     }
 
     private static TimeOfDay getTime(String timeString) {
-        TimeOfDay time = new TimeOfDay();
-        time.hour = (timeString.charAt(0) - '0') * 10
-                + (timeString.charAt(1) - '0');
-        time.minute = (timeString.charAt(3) - '0') * 10
-                + (timeString.charAt(4) - '0');
-        time.second = (timeString.charAt(6) - '0') * 10
-                + (timeString.charAt(7) - '0');
-        return time;
+        // HH might be H
+        int i = 0;
+        int hour = timeString.charAt(i++) - '0';
+        if (timeString.charAt(i) != ':')
+            hour = hour * 10 + (timeString.charAt(i++) - '0');
+        // Skip ':'
+        i++;
+        
+        int minute = (timeString.charAt(i++) - '0') * 10
+                    + (timeString.charAt(i++) - '0');
+        // Skip ':'
+        i++;
+        
+        int second = (timeString.charAt(i++) - '0') * 10
+                  + (timeString.charAt(i++) - '0');
+
+        return new TimeOfDay(hour, minute, second);        
     }
 }
diff --git a/core/java/android/webkit/JWebCoreJavaBridge.java b/core/java/android/webkit/JWebCoreJavaBridge.java
index 1dbd007..2d7376c 100644
--- a/core/java/android/webkit/JWebCoreJavaBridge.java
+++ b/core/java/android/webkit/JWebCoreJavaBridge.java
@@ -34,9 +34,16 @@
     // Instant timer is used to implement a timer that needs to fire almost
     // immediately.
     private boolean mHasInstantTimer;
+
     // Reference count the pause/resume of timers
     private int mPauseTimerRefCount;
 
+    private boolean mTimerPaused;
+    private boolean mHasDeferredTimers;
+
+    /* package */
+    static final int REFRESH_PLUGINS = 100;
+
     /**
      * Construct a new JWebCoreJavaBridge to interface with
      * WebCore timers and cookies.
@@ -51,6 +58,17 @@
     }
 
     /**
+     * Call native timer callbacks.
+     */
+    private void fireSharedTimer() { 
+        PerfChecker checker = new PerfChecker();
+        // clear the flag so that sharedTimerFired() can set a new timer
+        mHasInstantTimer = false;
+        sharedTimerFired();
+        checker.responseAlert("sharedTimer");
+    }
+
+    /**
      * handleMessage
      * @param msg The dispatched message.
      *
@@ -60,16 +78,21 @@
     public void handleMessage(Message msg) {
         switch (msg.what) {
             case TIMER_MESSAGE: {
-                PerfChecker checker = new PerfChecker();
-                // clear the flag so that sharedTimerFired() can set a new timer
-                mHasInstantTimer = false;
-                sharedTimerFired();
-                checker.responseAlert("sharedTimer");
+                if (mTimerPaused) {
+                    mHasDeferredTimers = true;
+                } else {
+                    fireSharedTimer();
+                }
                 break;
             }
             case FUNCPTR_MESSAGE:
                 nativeServiceFuncPtrQueue();
                 break;
+            case REFRESH_PLUGINS:
+                nativeUpdatePluginDirectories(PluginManager.getInstance(null)
+                        .getPluginDirecoties(), ((Boolean) msg.obj)
+                        .booleanValue());
+                break;
         }
     }
     
@@ -86,7 +109,8 @@
      */
     public void pause() {
         if (--mPauseTimerRefCount == 0) {
-            setDeferringTimers(true);
+            mTimerPaused = true;
+            mHasDeferredTimers = false;
         }
     }
 
@@ -95,7 +119,11 @@
      */
     public void resume() {
         if (++mPauseTimerRefCount == 1) {
-            setDeferringTimers(false);
+           mTimerPaused = false;
+           if (mHasDeferredTimers) {
+               mHasDeferredTimers = false;
+               fireSharedTimer();
+           }
         }
     }
 
@@ -108,10 +136,9 @@
     /**
      * Store a cookie string associated with a url.
      * @param url The url to be used as a key for the cookie.
-     * @param docUrl The policy base url used by WebCore.
      * @param value The cookie string to be stored.
      */
-    private void setCookies(String url, String docUrl, String value) {
+    private void setCookies(String url, String value) {
         if (value.contains("\r") || value.contains("\n")) {
             // for security reason, filter out '\r' and '\n' from the cookie
             int size = value.length();
@@ -152,11 +179,18 @@
     }
 
     /**
+     * Returns an array of plugin directoies
+     */
+    private String[] getPluginDirectories() {
+        return PluginManager.getInstance(null).getPluginDirecoties();
+    }
+
+    /**
      * setSharedTimer
      * @param timemillis The relative time when the timer should fire
      */
     private void setSharedTimer(long timemillis) {
-        if (WebView.LOGV_ENABLED) Log.v(LOGTAG, "setSharedTimer " + timemillis);
+        if (DebugFlags.J_WEB_CORE_JAVA_BRIDGE) Log.v(LOGTAG, "setSharedTimer " + timemillis);
 
         if (timemillis <= 0) {
             // we don't accumulate the sharedTimer unless it is a delayed
@@ -180,11 +214,12 @@
      * Stop the shared timer.
      */
     private void stopSharedTimer() {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.J_WEB_CORE_JAVA_BRIDGE) {
             Log.v(LOGTAG, "stopSharedTimer removing all timers");
         }
         removeMessages(TIMER_MESSAGE);
         mHasInstantTimer = false;
+        mHasDeferredTimers = false;
     }
 
     private String[] getKeyStrengthList() {
@@ -199,6 +234,7 @@
     private native void nativeConstructor();
     private native void nativeFinalize();
     private native void sharedTimerFired();
-    private native void setDeferringTimers(boolean defer);
+    private native void nativeUpdatePluginDirectories(String[] directories,
+            boolean reload);
     public native void setNetworkOnLine(boolean online);
 }
diff --git a/core/java/android/webkit/LoadListener.java b/core/java/android/webkit/LoadListener.java
index 5ee824a..3da5a3c 100644
--- a/core/java/android/webkit/LoadListener.java
+++ b/core/java/android/webkit/LoadListener.java
@@ -43,8 +43,6 @@
 import java.util.regex.Pattern;
 import java.util.regex.Matcher;
 
-import org.apache.commons.codec.binary.Base64;
-
 class LoadListener extends Handler implements EventHandler {
 
     private static final String LOGTAG = "webkit";
@@ -111,7 +109,6 @@
     private String mMethod;
     private Map<String, String> mRequestHeaders;
     private byte[] mPostData;
-    private boolean mIsHighPriority;
     // Flag to indicate that this load is synchronous.
     private boolean mSynchronous;
     private Vector<Message> mMessageQueue;
@@ -140,15 +137,13 @@
 
     LoadListener(Context context, BrowserFrame frame, String url,
             int nativeLoader, boolean synchronous, boolean isMainPageLoader) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "LoadListener constructor url=" + url);
         }
         mContext = context;
         mBrowserFrame = frame;
         setUrl(url);
         mNativeLoader = nativeLoader;
-        mMimeType = "";
-        mEncoding = "";
         mSynchronous = synchronous;
         if (synchronous) {
             mMessageQueue = new Vector<Message>();
@@ -291,7 +286,7 @@
      * directly
      */
     public void headers(Headers headers) {
-        if (WebView.LOGV_ENABLED) Log.v(LOGTAG, "LoadListener.headers");
+        if (DebugFlags.LOAD_LISTENER) Log.v(LOGTAG, "LoadListener.headers");
         sendMessageInternal(obtainMessage(MSG_CONTENT_HEADERS, headers));
     }
 
@@ -299,8 +294,6 @@
     private void handleHeaders(Headers headers) {
         if (mCancelled) return;
         mHeaders = headers;
-        mMimeType = "";
-        mEncoding = "";
 
         ArrayList<String> cookies = headers.getSetCookie();
         for (int i = 0; i < cookies.size(); ++i) {
@@ -320,8 +313,8 @@
 
             // If we have one of "generic" MIME types, try to deduce
             // the right MIME type from the file extension (if any):
-            if (mMimeType.equalsIgnoreCase("text/plain") ||
-                    mMimeType.equalsIgnoreCase("application/octet-stream")) {
+            if (mMimeType.equals("text/plain") ||
+                    mMimeType.equals("application/octet-stream")) {
 
                 // for attachment, use the filename in the Content-Disposition
                 // to guess the mimetype
@@ -337,17 +330,14 @@
                 if (newMimeType != null) {
                     mMimeType = newMimeType;
                 }
-            } else if (mMimeType.equalsIgnoreCase("text/vnd.wap.wml")) {
+            } else if (mMimeType.equals("text/vnd.wap.wml")) {
                 // As we don't support wml, render it as plain text
                 mMimeType = "text/plain";
             } else {
-                // XXX: Until the servers send us either correct xhtml or
-                // text/html, treat application/xhtml+xml as text/html.
                 // It seems that xhtml+xml and vnd.wap.xhtml+xml mime
                 // subtypes are used interchangeably. So treat them the same.
-                if (mMimeType.equalsIgnoreCase("application/xhtml+xml") ||
-                        mMimeType.equals("application/vnd.wap.xhtml+xml")) {
-                    mMimeType = "text/html";
+                if (mMimeType.equals("application/vnd.wap.xhtml+xml")) {
+                    mMimeType = "application/xhtml+xml";
                 }
             }
         } else {
@@ -448,7 +438,7 @@
      */
     public void status(int majorVersion, int minorVersion,
             int code, /* Status-Code value */ String reasonPhrase) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "LoadListener: from: " + mUrl
                     + " major: " + majorVersion
                     + " minor: " + minorVersion
@@ -462,6 +452,9 @@
         status.put("reason", reasonPhrase);
         // New status means new data. Clear the old.
         mDataBuilder.clear();
+        mMimeType = "";
+        mEncoding = "";
+        mTransferEncoding = "";
         sendMessageInternal(obtainMessage(MSG_STATUS, status));
     }
 
@@ -505,7 +498,7 @@
      * directly
      */
     public void error(int id, String description) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "LoadListener.error url:" +
                     url() + " id:" + id + " description:" + description);
         }
@@ -533,23 +526,10 @@
      * mDataBuilder is a thread-safe structure.
      */
     public void data(byte[] data, int length) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "LoadListener.data(): url: " + url());
         }
 
-        // Decode base64 data
-        // Note: It's fine that we only decode base64 here and not in the other
-        // data call because the only caller of the stream version is not
-        // base64 encoded.
-        if ("base64".equalsIgnoreCase(mTransferEncoding)) {
-            if (length < data.length) {
-                byte[] trimmedData = new byte[length];
-                System.arraycopy(data, 0, trimmedData, 0, length);
-                data = trimmedData;
-            }
-            data = Base64.decodeBase64(data);
-            length = data.length;
-        }
         // Synchronize on mData because commitLoad may write mData to WebCore
         // and we don't want to replace mData or mDataLength at the same time
         // as a write.
@@ -571,7 +551,7 @@
      * directly
      */
     public void endData() {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "LoadListener.endData(): url: " + url());
         }
         sendMessageInternal(obtainMessage(MSG_CONTENT_FINISHED));
@@ -624,7 +604,7 @@
                 // before calling it.
                 if (mCacheLoader != null) {
                     mCacheLoader.load();
-                    if (WebView.LOGV_ENABLED) {
+                    if (DebugFlags.LOAD_LISTENER) {
                         Log.v(LOGTAG, "LoadListener cache load url=" + url());
                     }
                     return;
@@ -674,7 +654,7 @@
                     CacheManager.HEADER_KEY_IFNONEMATCH) &&
                     !headers.containsKey(
                             CacheManager.HEADER_KEY_IFMODIFIEDSINCE)) {
-                if (WebView.LOGV_ENABLED) {
+                if (DebugFlags.LOAD_LISTENER) {
                     Log.v(LOGTAG, "FrameLoader: HTTP URL in cache " +
                             "and usable: " + url());
                 }
@@ -693,7 +673,7 @@
      * directly
      */
     public void handleSslErrorRequest(SslError error) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG,
                     "LoadListener.handleSslErrorRequest(): url:" + url() +
                     " primary error: " + error.getPrimaryError() +
@@ -759,7 +739,7 @@
      * are null, cancel the request.
      */
     void handleAuthResponse(String username, String password) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "LoadListener.handleAuthResponse: url: " + mUrl
                     + " username: " + username
                     + " password: " + password);
@@ -809,14 +789,12 @@
      * @param method
      * @param headers
      * @param postData
-     * @param isHighPriority
      */
     void setRequestData(String method, Map<String, String> headers, 
-            byte[] postData, boolean isHighPriority) {
+            byte[] postData) {
         mMethod = method;
         mRequestHeaders = headers;
         mPostData = postData;
-        mIsHighPriority = isHighPriority;
     }
 
     /**
@@ -856,7 +834,7 @@
     }
 
     void attachRequestHandle(RequestHandle requestHandle) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "LoadListener.attachRequestHandle(): " +
                     "requestHandle: " +  requestHandle);
         }
@@ -864,7 +842,7 @@
     }
 
     void detachRequestHandle() {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "LoadListener.detachRequestHandle(): " +
                     "requestHandle: " + mRequestHandle);
         }
@@ -903,7 +881,7 @@
      */
     static boolean willLoadFromCache(String url) {
         boolean inCache = CacheManager.getCacheFile(url, null) != null;
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "willLoadFromCache: " + url + " in cache: " + 
                     inCache);
         }
@@ -924,6 +902,10 @@
         return mMimeType;
     }
 
+    String transferEncoding() {
+        return mTransferEncoding;
+    }
+
     /*
      * Return the size of the content being downloaded. This represents the
      * full content size, even under the situation where the download has been
@@ -978,8 +960,7 @@
         // pass content-type content-length and content-encoding
         final int nativeResponse = nativeCreateResponse(
                 mUrl, statusCode, mStatusText,
-                mMimeType, mContentLength, mEncoding,
-                mCacheResult == null ? 0 : mCacheResult.expires / 1000);
+                mMimeType, mContentLength, mEncoding);
         if (mHeaders != null) {
             mHeaders.getHeaders(new Headers.HeaderCallback() {
                     public void header(String name, String value) {
@@ -1101,7 +1082,7 @@
      * EventHandler's method call.
      */
     public void cancel() {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             if (mRequestHandle == null) {
                 Log.v(LOGTAG, "LoadListener.cancel(): no requestHandle");
             } else {
@@ -1207,7 +1188,7 @@
                     // Network.requestURL.
                     Network network = Network.getInstance(getContext());
                     if (!network.requestURL(mMethod, mRequestHeaders,
-                            mPostData, this, mIsHighPriority)) {
+                            mPostData, this)) {
                         // Signal a bad url error if we could not load the
                         // redirection.
                         handleError(EventHandler.ERROR_BAD_URL,
@@ -1233,7 +1214,7 @@
             tearDown();
         }
 
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "LoadListener.onRedirect(): redirect to: " +
                     redirectTo);
         }
@@ -1246,8 +1227,8 @@
     private static final Pattern CONTENT_TYPE_PATTERN =
             Pattern.compile("^((?:[xX]-)?[a-zA-Z\\*]+/[\\w\\+\\*-]+[\\.[\\w\\+-]+]*)$");
 
-    private void parseContentTypeHeader(String contentType) {
-        if (WebView.LOGV_ENABLED) {
+    /* package */ void parseContentTypeHeader(String contentType) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "LoadListener.parseContentTypeHeader: " +
                     "contentType: " + contentType);
         }
@@ -1268,13 +1249,14 @@
                     mEncoding = contentType.substring(i + 1);
                 }
                 // Trim excess whitespace.
-                mEncoding = mEncoding.trim();
+                mEncoding = mEncoding.trim().toLowerCase();
 
                 if (i < contentType.length() - 1) {
                     // for data: uri the mimeType and encoding have
                     // the form image/jpeg;base64 or text/plain;charset=utf-8
                     // or text/html;charset=utf-8;base64
-                    mTransferEncoding = contentType.substring(i + 1).trim();
+                    mTransferEncoding =
+                            contentType.substring(i + 1).trim().toLowerCase();
                 }
             } else {
                 mMimeType = contentType;
@@ -1294,6 +1276,8 @@
                 guessMimeType();
             }
         }
+        // Ensure mMimeType is lower case.
+        mMimeType = mMimeType.toLowerCase();
     }
 
     /**
@@ -1383,7 +1367,8 @@
      */
     private boolean ignoreCallbacks() {
         return (mCancelled || mAuthHeader != null ||
-                (mStatusCode > 300 && mStatusCode < 400));
+                // Allow 305 (Use Proxy) to call through.
+                (mStatusCode > 300 && mStatusCode < 400 && mStatusCode != 305));
     }
 
     /**
@@ -1424,7 +1409,7 @@
             mMimeType = "text/html";
             String newMimeType = guessMimeTypeFromExtension(mUrl);
             if (newMimeType != null) {
-                mMimeType =  newMimeType;
+                mMimeType = newMimeType;
             }
         }
     }
@@ -1434,23 +1419,12 @@
      */
     private String guessMimeTypeFromExtension(String url) {
         // PENDING: need to normalize url
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.LOAD_LISTENER) {
             Log.v(LOGTAG, "guessMimeTypeFromExtension: url = " + url);
         }
 
-        String mimeType =
-                MimeTypeMap.getSingleton().getMimeTypeFromExtension(
-                        MimeTypeMap.getFileExtensionFromUrl(url));
-
-        if (mimeType != null) {
-            // XXX: Until the servers send us either correct xhtml or
-            // text/html, treat application/xhtml+xml as text/html.
-            if (mimeType.equals("application/xhtml+xml")) {
-                mimeType = "text/html";
-            }
-        }
-
-        return mimeType;
+        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(
+                MimeTypeMap.getFileExtensionFromUrl(url));
     }
 
     /**
@@ -1469,7 +1443,7 @@
      * Cycle through our messages for synchronous loads.
      */
     /* package */ void loadSynchronousMessages() {
-        if (WebView.DEBUG && !mSynchronous) {
+        if (DebugFlags.LOAD_LISTENER && !mSynchronous) {
             throw new AssertionError();
         }
         // Note: this can be called twice if it is a synchronous network load,
@@ -1496,12 +1470,11 @@
      * @param expectedLength An estimate of the content length or the length
      *                       given by the server.
      * @param encoding HTTP encoding.
-     * @param expireTime HTTP expires converted to seconds since the epoch.
      * @return The native response pointer.
      */
     private native int nativeCreateResponse(String url, int statusCode,
             String statusText, String mimeType, long expectedLength,
-            String encoding, long expireTime);
+            String encoding);
 
     /**
      * Add a response header to the native object.
diff --git a/core/java/android/webkit/MimeTypeMap.java b/core/java/android/webkit/MimeTypeMap.java
index fdbc692..b2aa524 100644
--- a/core/java/android/webkit/MimeTypeMap.java
+++ b/core/java/android/webkit/MimeTypeMap.java
@@ -22,7 +22,7 @@
 /**
  * Two-way map that maps MIME-types to file extensions and vice versa.
  */
-public /* package */ class MimeTypeMap {
+public class MimeTypeMap {
 
     /**
      * Singleton MIME-type map instance:
@@ -39,7 +39,6 @@
      */
     private HashMap<String, String> mExtensionToMimeTypeMap;
 
-
     /**
      * Creates a new MIME-type map.
      */
@@ -50,7 +49,10 @@
 
     /**
      * Returns the file extension or an empty string iff there is no
-     * extension.
+     * extension. This method is a convenience method for obtaining the
+     * extension of a url and has undefined results for other Strings.
+     * @param url
+     * @return The file extension of the given url.
      */
     public static String getFileExtensionFromUrl(String url) {
         if (url != null && url.length() > 0) {
@@ -80,8 +82,7 @@
      * Load an entry into the map. This does not check if the item already
      * exists, it trusts the caller!
      */
-    private void loadEntry(String mimeType, String extension, 
-            boolean textType) {
+    private void loadEntry(String mimeType, String extension) {
         //
         // if we have an existing x --> y mapping, we do not want to
         // override it with another mapping x --> ?
@@ -94,18 +95,12 @@
             mMimeTypeToExtensionMap.put(mimeType, extension);
         }
 
-        //
-        // here, we don't want to map extensions to text MIME types;
-        // otherwise, we will start replacing generic text/plain and
-        // text/html with text MIME types that our platform does not
-        // understand.
-        //
-        if (!textType) {
-            mExtensionToMimeTypeMap.put(extension, mimeType);
-        }
+        mExtensionToMimeTypeMap.put(extension, mimeType);
     }
 
     /**
+     * Return true if the given MIME type has an entry in the map.
+     * @param mimeType A MIME type (i.e. text/plain)
      * @return True iff there is a mimeType entry in the map.
      */
     public boolean hasMimeType(String mimeType) {
@@ -117,7 +112,9 @@
     }
 
     /**
-     * @return The extension for the MIME type or null iff there is none.
+     * Return the MIME type for the given extension.
+     * @param extension A file extension without the leading '.'
+     * @return The MIME type for the given extension or null iff there is none.
      */
     public String getMimeTypeFromExtension(String extension) {
         if (extension != null && extension.length() > 0) {
@@ -128,18 +125,23 @@
     }
 
     /**
+     * Return true if the given extension has a registered MIME type.
+     * @param extension A file extension without the leading '.'
      * @return True iff there is an extension entry in the map.
      */
     public boolean hasExtension(String extension) {
         if (extension != null && extension.length() > 0) {
             return mExtensionToMimeTypeMap.containsKey(extension);
         }
-
         return false;
     }
 
     /**
-     * @return The MIME type for the extension or null iff there is none.
+     * Return the registered extension for the given MIME type. Note that some
+     * MIME types map to multiple extensions. This call will return the most
+     * common extension for the given MIME type.
+     * @param mimeType A MIME type (i.e. text/plain)
+     * @return The extension for the given MIME type or null iff there is none.
      */
     public String getExtensionFromMimeType(String mimeType) {
         if (mimeType != null && mimeType.length() > 0) {
@@ -150,6 +152,7 @@
     }
 
     /**
+     * Get the singleton instance of MimeTypeMap.
      * @return The singleton instance of the MIME-type map.
      */
     public static MimeTypeMap getSingleton() {
@@ -164,340 +167,311 @@
             // mail.google.com/a/google.com
             //
             // and "active" MIME types (due to potential security issues).
-            //
-            // Also, notice that not all data from this table is actually
-            // added (see loadEntry method for more details).
 
-            sMimeTypeMap.loadEntry("application/andrew-inset", "ez", false);
-            sMimeTypeMap.loadEntry("application/dsptype", "tsp", false);
-            sMimeTypeMap.loadEntry("application/futuresplash", "spl", false);
-            sMimeTypeMap.loadEntry("application/hta", "hta", false);
-            sMimeTypeMap.loadEntry("application/mac-binhex40", "hqx", false);
-            sMimeTypeMap.loadEntry("application/mac-compactpro", "cpt", false);
-            sMimeTypeMap.loadEntry("application/mathematica", "nb", false);
-            sMimeTypeMap.loadEntry("application/msaccess", "mdb", false);
-            sMimeTypeMap.loadEntry("application/oda", "oda", false);
-            sMimeTypeMap.loadEntry("application/ogg", "ogg", false);
-            sMimeTypeMap.loadEntry("application/pdf", "pdf", false);
-            sMimeTypeMap.loadEntry("application/pgp-keys", "key", false);
-            sMimeTypeMap.loadEntry("application/pgp-signature", "pgp", false);
-            sMimeTypeMap.loadEntry("application/pics-rules", "prf", false);
-            sMimeTypeMap.loadEntry("application/rar", "rar", false);
-            sMimeTypeMap.loadEntry("application/rdf+xml", "rdf", false);
-            sMimeTypeMap.loadEntry("application/rss+xml", "rss", false);
-            sMimeTypeMap.loadEntry("application/zip", "zip", false);
+            sMimeTypeMap.loadEntry("application/andrew-inset", "ez");
+            sMimeTypeMap.loadEntry("application/dsptype", "tsp");
+            sMimeTypeMap.loadEntry("application/futuresplash", "spl");
+            sMimeTypeMap.loadEntry("application/hta", "hta");
+            sMimeTypeMap.loadEntry("application/mac-binhex40", "hqx");
+            sMimeTypeMap.loadEntry("application/mac-compactpro", "cpt");
+            sMimeTypeMap.loadEntry("application/mathematica", "nb");
+            sMimeTypeMap.loadEntry("application/msaccess", "mdb");
+            sMimeTypeMap.loadEntry("application/oda", "oda");
+            sMimeTypeMap.loadEntry("application/ogg", "ogg");
+            sMimeTypeMap.loadEntry("application/pdf", "pdf");
+            sMimeTypeMap.loadEntry("application/pgp-keys", "key");
+            sMimeTypeMap.loadEntry("application/pgp-signature", "pgp");
+            sMimeTypeMap.loadEntry("application/pics-rules", "prf");
+            sMimeTypeMap.loadEntry("application/rar", "rar");
+            sMimeTypeMap.loadEntry("application/rdf+xml", "rdf");
+            sMimeTypeMap.loadEntry("application/rss+xml", "rss");
+            sMimeTypeMap.loadEntry("application/zip", "zip");
             sMimeTypeMap.loadEntry("application/vnd.android.package-archive", 
-                    "apk", false);
-            sMimeTypeMap.loadEntry("application/vnd.cinderella", "cdy", false);
-            sMimeTypeMap.loadEntry("application/vnd.ms-pki.stl", "stl", false);
+                    "apk");
+            sMimeTypeMap.loadEntry("application/vnd.cinderella", "cdy");
+            sMimeTypeMap.loadEntry("application/vnd.ms-pki.stl", "stl");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.oasis.opendocument.database", "odb", 
-                    false);
+                    "application/vnd.oasis.opendocument.database", "odb");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.oasis.opendocument.formula", "odf", 
-                    false);
+                    "application/vnd.oasis.opendocument.formula", "odf");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.oasis.opendocument.graphics", "odg", 
-                    false);
+                    "application/vnd.oasis.opendocument.graphics", "odg");
             sMimeTypeMap.loadEntry(
                     "application/vnd.oasis.opendocument.graphics-template",
-                    "otg", false);
+                    "otg");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.oasis.opendocument.image", "odi", false);
+                    "application/vnd.oasis.opendocument.image", "odi");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.oasis.opendocument.spreadsheet", "ods", 
-                    false);
+                    "application/vnd.oasis.opendocument.spreadsheet", "ods");
             sMimeTypeMap.loadEntry(
                     "application/vnd.oasis.opendocument.spreadsheet-template",
-                    "ots", false);
+                    "ots");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.oasis.opendocument.text", "odt", false);
+                    "application/vnd.oasis.opendocument.text", "odt");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.oasis.opendocument.text-master", "odm", 
-                    false);
+                    "application/vnd.oasis.opendocument.text-master", "odm");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.oasis.opendocument.text-template", "ott", 
-                    false);
+                    "application/vnd.oasis.opendocument.text-template", "ott");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.oasis.opendocument.text-web", "oth", 
-                    false);
-            sMimeTypeMap.loadEntry("application/vnd.rim.cod", "cod", false);
-            sMimeTypeMap.loadEntry("application/vnd.smaf", "mmf", false);
-            sMimeTypeMap.loadEntry("application/vnd.stardivision.calc", "sdc", 
-                    false);
-            sMimeTypeMap.loadEntry("application/vnd.stardivision.draw", "sda", 
-                    false);
+                    "application/vnd.oasis.opendocument.text-web", "oth");
+            sMimeTypeMap.loadEntry("application/vnd.rim.cod", "cod");
+            sMimeTypeMap.loadEntry("application/vnd.smaf", "mmf");
+            sMimeTypeMap.loadEntry("application/vnd.stardivision.calc", "sdc");
+            sMimeTypeMap.loadEntry("application/vnd.stardivision.draw", "sda");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.stardivision.impress", "sdd", false);
+                    "application/vnd.stardivision.impress", "sdd");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.stardivision.impress", "sdp", false);
-            sMimeTypeMap.loadEntry("application/vnd.stardivision.math", "smf", 
-                    false);
-            sMimeTypeMap.loadEntry("application/vnd.stardivision.writer", "sdw", 
-                    false);
-            sMimeTypeMap.loadEntry("application/vnd.stardivision.writer", "vor", 
-                    false);
+                    "application/vnd.stardivision.impress", "sdp");
+            sMimeTypeMap.loadEntry("application/vnd.stardivision.math", "smf");
+            sMimeTypeMap.loadEntry("application/vnd.stardivision.writer",
+                    "sdw");
+            sMimeTypeMap.loadEntry("application/vnd.stardivision.writer",
+                    "vor");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.stardivision.writer-global", "sgl", false);
-            sMimeTypeMap.loadEntry("application/vnd.sun.xml.calc", "sxc", 
-                    false);
+                    "application/vnd.stardivision.writer-global", "sgl");
+            sMimeTypeMap.loadEntry("application/vnd.sun.xml.calc", "sxc");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.sun.xml.calc.template", "stc", false);
-            sMimeTypeMap.loadEntry("application/vnd.sun.xml.draw", "sxd", 
-                    false);
+                    "application/vnd.sun.xml.calc.template", "stc");
+            sMimeTypeMap.loadEntry("application/vnd.sun.xml.draw", "sxd");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.sun.xml.draw.template", "std", false);
-            sMimeTypeMap.loadEntry("application/vnd.sun.xml.impress", "sxi", 
-                    false);
+                    "application/vnd.sun.xml.draw.template", "std");
+            sMimeTypeMap.loadEntry("application/vnd.sun.xml.impress", "sxi");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.sun.xml.impress.template", "sti", false);
-            sMimeTypeMap.loadEntry("application/vnd.sun.xml.math", "sxm", 
-                    false);
-            sMimeTypeMap.loadEntry("application/vnd.sun.xml.writer", "sxw", 
-                    false);
+                    "application/vnd.sun.xml.impress.template", "sti");
+            sMimeTypeMap.loadEntry("application/vnd.sun.xml.math", "sxm");
+            sMimeTypeMap.loadEntry("application/vnd.sun.xml.writer", "sxw");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.sun.xml.writer.global", "sxg", false);
+                    "application/vnd.sun.xml.writer.global", "sxg");
             sMimeTypeMap.loadEntry(
-                    "application/vnd.sun.xml.writer.template", "stw", false);
-            sMimeTypeMap.loadEntry("application/vnd.visio", "vsd", false);
-            sMimeTypeMap.loadEntry("application/x-abiword", "abw", false);
-            sMimeTypeMap.loadEntry("application/x-apple-diskimage", "dmg", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-bcpio", "bcpio", false);
-            sMimeTypeMap.loadEntry("application/x-bittorrent", "torrent", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-cdf", "cdf", false);
-            sMimeTypeMap.loadEntry("application/x-cdlink", "vcd", false);
-            sMimeTypeMap.loadEntry("application/x-chess-pgn", "pgn", false);
-            sMimeTypeMap.loadEntry("application/x-cpio", "cpio", false);
-            sMimeTypeMap.loadEntry("application/x-debian-package", "deb", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-debian-package", "udeb", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-director", "dcr", false);
-            sMimeTypeMap.loadEntry("application/x-director", "dir", false);
-            sMimeTypeMap.loadEntry("application/x-director", "dxr", false);
-            sMimeTypeMap.loadEntry("application/x-dms", "dms", false);
-            sMimeTypeMap.loadEntry("application/x-doom", "wad", false);
-            sMimeTypeMap.loadEntry("application/x-dvi", "dvi", false);
-            sMimeTypeMap.loadEntry("application/x-flac", "flac", false);
-            sMimeTypeMap.loadEntry("application/x-font", "pfa", false);
-            sMimeTypeMap.loadEntry("application/x-font", "pfb", false);
-            sMimeTypeMap.loadEntry("application/x-font", "gsf", false);
-            sMimeTypeMap.loadEntry("application/x-font", "pcf", false);
-            sMimeTypeMap.loadEntry("application/x-font", "pcf.Z", false);
-            sMimeTypeMap.loadEntry("application/x-freemind", "mm", false);
-            sMimeTypeMap.loadEntry("application/x-futuresplash", "spl", false);
-            sMimeTypeMap.loadEntry("application/x-gnumeric", "gnumeric", false);
-            sMimeTypeMap.loadEntry("application/x-go-sgf", "sgf", false);
-            sMimeTypeMap.loadEntry("application/x-graphing-calculator", "gcf", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-gtar", "gtar", false);
-            sMimeTypeMap.loadEntry("application/x-gtar", "tgz", false);
-            sMimeTypeMap.loadEntry("application/x-gtar", "taz", false);
-            sMimeTypeMap.loadEntry("application/x-hdf", "hdf", false);
-            sMimeTypeMap.loadEntry("application/x-ica", "ica", false);
-            sMimeTypeMap.loadEntry("application/x-internet-signup", "ins", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-internet-signup", "isp", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-iphone", "iii", false);
-            sMimeTypeMap.loadEntry("application/x-iso9660-image", "iso", false);
-            sMimeTypeMap.loadEntry("application/x-jmol", "jmz", false);
-            sMimeTypeMap.loadEntry("application/x-kchart", "chrt", false);
-            sMimeTypeMap.loadEntry("application/x-killustrator", "kil", false);
-            sMimeTypeMap.loadEntry("application/x-koan", "skp", false);
-            sMimeTypeMap.loadEntry("application/x-koan", "skd", false);
-            sMimeTypeMap.loadEntry("application/x-koan", "skt", false);
-            sMimeTypeMap.loadEntry("application/x-koan", "skm", false);
-            sMimeTypeMap.loadEntry("application/x-kpresenter", "kpr", false);
-            sMimeTypeMap.loadEntry("application/x-kpresenter", "kpt", false);
-            sMimeTypeMap.loadEntry("application/x-kspread", "ksp", false);
-            sMimeTypeMap.loadEntry("application/x-kword", "kwd", false);
-            sMimeTypeMap.loadEntry("application/x-kword", "kwt", false);
-            sMimeTypeMap.loadEntry("application/x-latex", "latex", false);
-            sMimeTypeMap.loadEntry("application/x-lha", "lha", false);
-            sMimeTypeMap.loadEntry("application/x-lzh", "lzh", false);
-            sMimeTypeMap.loadEntry("application/x-lzx", "lzx", false);
-            sMimeTypeMap.loadEntry("application/x-maker", "frm", false);
-            sMimeTypeMap.loadEntry("application/x-maker", "maker", false);
-            sMimeTypeMap.loadEntry("application/x-maker", "frame", false);
-            sMimeTypeMap.loadEntry("application/x-maker", "fb", false);
-            sMimeTypeMap.loadEntry("application/x-maker", "book", false);
-            sMimeTypeMap.loadEntry("application/x-maker", "fbdoc", false);
-            sMimeTypeMap.loadEntry("application/x-mif", "mif", false);
-            sMimeTypeMap.loadEntry("application/x-ms-wmd", "wmd", false);
-            sMimeTypeMap.loadEntry("application/x-ms-wmz", "wmz", false);
-            sMimeTypeMap.loadEntry("application/x-msi", "msi", false);
-            sMimeTypeMap.loadEntry("application/x-ns-proxy-autoconfig", "pac", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-nwc", "nwc", false);
-            sMimeTypeMap.loadEntry("application/x-object", "o", false);
-            sMimeTypeMap.loadEntry("application/x-oz-application", "oza", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-pkcs12", "p12", false);
-            sMimeTypeMap.loadEntry("application/x-pkcs7-certreqresp", "p7r", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-pkcs7-crl", "crl", false);
-            sMimeTypeMap.loadEntry("application/x-quicktimeplayer", "qtl", 
-                    false);
-            sMimeTypeMap.loadEntry("application/x-shar", "shar", false);
-            sMimeTypeMap.loadEntry("application/x-stuffit", "sit", false);
-            sMimeTypeMap.loadEntry("application/x-sv4cpio", "sv4cpio", false);
-            sMimeTypeMap.loadEntry("application/x-sv4crc", "sv4crc", false);
-            sMimeTypeMap.loadEntry("application/x-tar", "tar", false);
-            sMimeTypeMap.loadEntry("application/x-texinfo", "texinfo", false);
-            sMimeTypeMap.loadEntry("application/x-texinfo", "texi", false);
-            sMimeTypeMap.loadEntry("application/x-troff", "t", false);
-            sMimeTypeMap.loadEntry("application/x-troff", "roff", false);
-            sMimeTypeMap.loadEntry("application/x-troff-man", "man", false);
-            sMimeTypeMap.loadEntry("application/x-ustar", "ustar", false);
-            sMimeTypeMap.loadEntry("application/x-wais-source", "src", false);
-            sMimeTypeMap.loadEntry("application/x-wingz", "wz", false);
-            sMimeTypeMap.loadEntry(
-                    "application/x-webarchive", "webarchive", false); // added
-            sMimeTypeMap.loadEntry("application/x-x509-ca-cert", "crt", false);
-            sMimeTypeMap.loadEntry("application/x-xcf", "xcf", false);
-            sMimeTypeMap.loadEntry("application/x-xfig", "fig", false);
-            sMimeTypeMap.loadEntry("audio/basic", "snd", false);
-            sMimeTypeMap.loadEntry("audio/midi", "mid", false);
-            sMimeTypeMap.loadEntry("audio/midi", "midi", false);
-            sMimeTypeMap.loadEntry("audio/midi", "kar", false);
-            sMimeTypeMap.loadEntry("audio/mpeg", "mpga", false);
-            sMimeTypeMap.loadEntry("audio/mpeg", "mpega", false);
-            sMimeTypeMap.loadEntry("audio/mpeg", "mp2", false);
-            sMimeTypeMap.loadEntry("audio/mpeg", "mp3", false);
-            sMimeTypeMap.loadEntry("audio/mpeg", "m4a", false);
-            sMimeTypeMap.loadEntry("audio/mpegurl", "m3u", false);
-            sMimeTypeMap.loadEntry("audio/prs.sid", "sid", false);
-            sMimeTypeMap.loadEntry("audio/x-aiff", "aif", false);
-            sMimeTypeMap.loadEntry("audio/x-aiff", "aiff", false);
-            sMimeTypeMap.loadEntry("audio/x-aiff", "aifc", false);
-            sMimeTypeMap.loadEntry("audio/x-gsm", "gsm", false);
-            sMimeTypeMap.loadEntry("audio/x-mpegurl", "m3u", false);
-            sMimeTypeMap.loadEntry("audio/x-ms-wma", "wma", false);
-            sMimeTypeMap.loadEntry("audio/x-ms-wax", "wax", false);
-            sMimeTypeMap.loadEntry("audio/x-pn-realaudio", "ra", false);
-            sMimeTypeMap.loadEntry("audio/x-pn-realaudio", "rm", false);
-            sMimeTypeMap.loadEntry("audio/x-pn-realaudio", "ram", false);
-            sMimeTypeMap.loadEntry("audio/x-realaudio", "ra", false);
-            sMimeTypeMap.loadEntry("audio/x-scpls", "pls", false);
-            sMimeTypeMap.loadEntry("audio/x-sd2", "sd2", false);
-            sMimeTypeMap.loadEntry("audio/x-wav", "wav", false);
-            sMimeTypeMap.loadEntry("image/bmp", "bmp", false); // added
-            sMimeTypeMap.loadEntry("image/gif", "gif", false);
-            sMimeTypeMap.loadEntry("image/ico", "cur", false); // added
-            sMimeTypeMap.loadEntry("image/ico", "ico", false); // added
-            sMimeTypeMap.loadEntry("image/ief", "ief", false);
-            sMimeTypeMap.loadEntry("image/jpeg", "jpeg", false);
-            sMimeTypeMap.loadEntry("image/jpeg", "jpg", false);
-            sMimeTypeMap.loadEntry("image/jpeg", "jpe", false);
-            sMimeTypeMap.loadEntry("image/pcx", "pcx", false);
-            sMimeTypeMap.loadEntry("image/png", "png", false);
-            sMimeTypeMap.loadEntry("image/svg+xml", "svg", false);
-            sMimeTypeMap.loadEntry("image/svg+xml", "svgz", false);
-            sMimeTypeMap.loadEntry("image/tiff", "tiff", false);
-            sMimeTypeMap.loadEntry("image/tiff", "tif", false);
-            sMimeTypeMap.loadEntry("image/vnd.djvu", "djvu", false);
-            sMimeTypeMap.loadEntry("image/vnd.djvu", "djv", false);
-            sMimeTypeMap.loadEntry("image/vnd.wap.wbmp", "wbmp", false);
-            sMimeTypeMap.loadEntry("image/x-cmu-raster", "ras", false);
-            sMimeTypeMap.loadEntry("image/x-coreldraw", "cdr", false);
-            sMimeTypeMap.loadEntry("image/x-coreldrawpattern", "pat", false);
-            sMimeTypeMap.loadEntry("image/x-coreldrawtemplate", "cdt", false);
-            sMimeTypeMap.loadEntry("image/x-corelphotopaint", "cpt", false);
-            sMimeTypeMap.loadEntry("image/x-icon", "ico", false);
-            sMimeTypeMap.loadEntry("image/x-jg", "art", false);
-            sMimeTypeMap.loadEntry("image/x-jng", "jng", false);
-            sMimeTypeMap.loadEntry("image/x-ms-bmp", "bmp", false);
-            sMimeTypeMap.loadEntry("image/x-photoshop", "psd", false);
-            sMimeTypeMap.loadEntry("image/x-portable-anymap", "pnm", false);
-            sMimeTypeMap.loadEntry("image/x-portable-bitmap", "pbm", false);
-            sMimeTypeMap.loadEntry("image/x-portable-graymap", "pgm", false);
-            sMimeTypeMap.loadEntry("image/x-portable-pixmap", "ppm", false);
-            sMimeTypeMap.loadEntry("image/x-rgb", "rgb", false);
-            sMimeTypeMap.loadEntry("image/x-xbitmap", "xbm", false);
-            sMimeTypeMap.loadEntry("image/x-xpixmap", "xpm", false);
-            sMimeTypeMap.loadEntry("image/x-xwindowdump", "xwd", false);
-            sMimeTypeMap.loadEntry("model/iges", "igs", false);
-            sMimeTypeMap.loadEntry("model/iges", "iges", false);
-            sMimeTypeMap.loadEntry("model/mesh", "msh", false);
-            sMimeTypeMap.loadEntry("model/mesh", "mesh", false);
-            sMimeTypeMap.loadEntry("model/mesh", "silo", false);
-            sMimeTypeMap.loadEntry("text/calendar", "ics", true);
-            sMimeTypeMap.loadEntry("text/calendar", "icz", true);
-            sMimeTypeMap.loadEntry("text/comma-separated-values", "csv", true);
-            sMimeTypeMap.loadEntry("text/css", "css", true);
-            sMimeTypeMap.loadEntry("text/h323", "323", true);
-            sMimeTypeMap.loadEntry("text/iuls", "uls", true);
-            sMimeTypeMap.loadEntry("text/mathml", "mml", true);
+                    "application/vnd.sun.xml.writer.template", "stw");
+            sMimeTypeMap.loadEntry("application/vnd.visio", "vsd");
+            sMimeTypeMap.loadEntry("application/x-abiword", "abw");
+            sMimeTypeMap.loadEntry("application/x-apple-diskimage", "dmg");
+            sMimeTypeMap.loadEntry("application/x-bcpio", "bcpio");
+            sMimeTypeMap.loadEntry("application/x-bittorrent", "torrent");
+            sMimeTypeMap.loadEntry("application/x-cdf", "cdf");
+            sMimeTypeMap.loadEntry("application/x-cdlink", "vcd");
+            sMimeTypeMap.loadEntry("application/x-chess-pgn", "pgn");
+            sMimeTypeMap.loadEntry("application/x-cpio", "cpio");
+            sMimeTypeMap.loadEntry("application/x-debian-package", "deb");
+            sMimeTypeMap.loadEntry("application/x-debian-package", "udeb");
+            sMimeTypeMap.loadEntry("application/x-director", "dcr");
+            sMimeTypeMap.loadEntry("application/x-director", "dir");
+            sMimeTypeMap.loadEntry("application/x-director", "dxr");
+            sMimeTypeMap.loadEntry("application/x-dms", "dms");
+            sMimeTypeMap.loadEntry("application/x-doom", "wad");
+            sMimeTypeMap.loadEntry("application/x-dvi", "dvi");
+            sMimeTypeMap.loadEntry("application/x-flac", "flac");
+            sMimeTypeMap.loadEntry("application/x-font", "pfa");
+            sMimeTypeMap.loadEntry("application/x-font", "pfb");
+            sMimeTypeMap.loadEntry("application/x-font", "gsf");
+            sMimeTypeMap.loadEntry("application/x-font", "pcf");
+            sMimeTypeMap.loadEntry("application/x-font", "pcf.Z");
+            sMimeTypeMap.loadEntry("application/x-freemind", "mm");
+            sMimeTypeMap.loadEntry("application/x-futuresplash", "spl");
+            sMimeTypeMap.loadEntry("application/x-gnumeric", "gnumeric");
+            sMimeTypeMap.loadEntry("application/x-go-sgf", "sgf");
+            sMimeTypeMap.loadEntry("application/x-graphing-calculator", "gcf");
+            sMimeTypeMap.loadEntry("application/x-gtar", "gtar");
+            sMimeTypeMap.loadEntry("application/x-gtar", "tgz");
+            sMimeTypeMap.loadEntry("application/x-gtar", "taz");
+            sMimeTypeMap.loadEntry("application/x-hdf", "hdf");
+            sMimeTypeMap.loadEntry("application/x-ica", "ica");
+            sMimeTypeMap.loadEntry("application/x-internet-signup", "ins");
+            sMimeTypeMap.loadEntry("application/x-internet-signup", "isp");
+            sMimeTypeMap.loadEntry("application/x-iphone", "iii");
+            sMimeTypeMap.loadEntry("application/x-iso9660-image", "iso");
+            sMimeTypeMap.loadEntry("application/x-jmol", "jmz");
+            sMimeTypeMap.loadEntry("application/x-kchart", "chrt");
+            sMimeTypeMap.loadEntry("application/x-killustrator", "kil");
+            sMimeTypeMap.loadEntry("application/x-koan", "skp");
+            sMimeTypeMap.loadEntry("application/x-koan", "skd");
+            sMimeTypeMap.loadEntry("application/x-koan", "skt");
+            sMimeTypeMap.loadEntry("application/x-koan", "skm");
+            sMimeTypeMap.loadEntry("application/x-kpresenter", "kpr");
+            sMimeTypeMap.loadEntry("application/x-kpresenter", "kpt");
+            sMimeTypeMap.loadEntry("application/x-kspread", "ksp");
+            sMimeTypeMap.loadEntry("application/x-kword", "kwd");
+            sMimeTypeMap.loadEntry("application/x-kword", "kwt");
+            sMimeTypeMap.loadEntry("application/x-latex", "latex");
+            sMimeTypeMap.loadEntry("application/x-lha", "lha");
+            sMimeTypeMap.loadEntry("application/x-lzh", "lzh");
+            sMimeTypeMap.loadEntry("application/x-lzx", "lzx");
+            sMimeTypeMap.loadEntry("application/x-maker", "frm");
+            sMimeTypeMap.loadEntry("application/x-maker", "maker");
+            sMimeTypeMap.loadEntry("application/x-maker", "frame");
+            sMimeTypeMap.loadEntry("application/x-maker", "fb");
+            sMimeTypeMap.loadEntry("application/x-maker", "book");
+            sMimeTypeMap.loadEntry("application/x-maker", "fbdoc");
+            sMimeTypeMap.loadEntry("application/x-mif", "mif");
+            sMimeTypeMap.loadEntry("application/x-ms-wmd", "wmd");
+            sMimeTypeMap.loadEntry("application/x-ms-wmz", "wmz");
+            sMimeTypeMap.loadEntry("application/x-msi", "msi");
+            sMimeTypeMap.loadEntry("application/x-ns-proxy-autoconfig", "pac");
+            sMimeTypeMap.loadEntry("application/x-nwc", "nwc");
+            sMimeTypeMap.loadEntry("application/x-object", "o");
+            sMimeTypeMap.loadEntry("application/x-oz-application", "oza");
+            sMimeTypeMap.loadEntry("application/x-pkcs12", "p12");
+            sMimeTypeMap.loadEntry("application/x-pkcs7-certreqresp", "p7r");
+            sMimeTypeMap.loadEntry("application/x-pkcs7-crl", "crl");
+            sMimeTypeMap.loadEntry("application/x-quicktimeplayer", "qtl");
+            sMimeTypeMap.loadEntry("application/x-shar", "shar");
+            sMimeTypeMap.loadEntry("application/x-stuffit", "sit");
+            sMimeTypeMap.loadEntry("application/x-sv4cpio", "sv4cpio");
+            sMimeTypeMap.loadEntry("application/x-sv4crc", "sv4crc");
+            sMimeTypeMap.loadEntry("application/x-tar", "tar");
+            sMimeTypeMap.loadEntry("application/x-texinfo", "texinfo");
+            sMimeTypeMap.loadEntry("application/x-texinfo", "texi");
+            sMimeTypeMap.loadEntry("application/x-troff", "t");
+            sMimeTypeMap.loadEntry("application/x-troff", "roff");
+            sMimeTypeMap.loadEntry("application/x-troff-man", "man");
+            sMimeTypeMap.loadEntry("application/x-ustar", "ustar");
+            sMimeTypeMap.loadEntry("application/x-wais-source", "src");
+            sMimeTypeMap.loadEntry("application/x-wingz", "wz");
+            sMimeTypeMap.loadEntry("application/x-webarchive", "webarchive");
+            sMimeTypeMap.loadEntry("application/x-x509-ca-cert", "crt");
+            sMimeTypeMap.loadEntry("application/x-xcf", "xcf");
+            sMimeTypeMap.loadEntry("application/x-xfig", "fig");
+            sMimeTypeMap.loadEntry("application/xhtml+xml", "xhtml");
+            sMimeTypeMap.loadEntry("audio/basic", "snd");
+            sMimeTypeMap.loadEntry("audio/midi", "mid");
+            sMimeTypeMap.loadEntry("audio/midi", "midi");
+            sMimeTypeMap.loadEntry("audio/midi", "kar");
+            sMimeTypeMap.loadEntry("audio/mpeg", "mpga");
+            sMimeTypeMap.loadEntry("audio/mpeg", "mpega");
+            sMimeTypeMap.loadEntry("audio/mpeg", "mp2");
+            sMimeTypeMap.loadEntry("audio/mpeg", "mp3");
+            sMimeTypeMap.loadEntry("audio/mpeg", "m4a");
+            sMimeTypeMap.loadEntry("audio/mpegurl", "m3u");
+            sMimeTypeMap.loadEntry("audio/prs.sid", "sid");
+            sMimeTypeMap.loadEntry("audio/x-aiff", "aif");
+            sMimeTypeMap.loadEntry("audio/x-aiff", "aiff");
+            sMimeTypeMap.loadEntry("audio/x-aiff", "aifc");
+            sMimeTypeMap.loadEntry("audio/x-gsm", "gsm");
+            sMimeTypeMap.loadEntry("audio/x-mpegurl", "m3u");
+            sMimeTypeMap.loadEntry("audio/x-ms-wma", "wma");
+            sMimeTypeMap.loadEntry("audio/x-ms-wax", "wax");
+            sMimeTypeMap.loadEntry("audio/x-pn-realaudio", "ra");
+            sMimeTypeMap.loadEntry("audio/x-pn-realaudio", "rm");
+            sMimeTypeMap.loadEntry("audio/x-pn-realaudio", "ram");
+            sMimeTypeMap.loadEntry("audio/x-realaudio", "ra");
+            sMimeTypeMap.loadEntry("audio/x-scpls", "pls");
+            sMimeTypeMap.loadEntry("audio/x-sd2", "sd2");
+            sMimeTypeMap.loadEntry("audio/x-wav", "wav");
+            sMimeTypeMap.loadEntry("image/bmp", "bmp");
+            sMimeTypeMap.loadEntry("image/gif", "gif");
+            sMimeTypeMap.loadEntry("image/ico", "cur");
+            sMimeTypeMap.loadEntry("image/ico", "ico");
+            sMimeTypeMap.loadEntry("image/ief", "ief");
+            sMimeTypeMap.loadEntry("image/jpeg", "jpeg");
+            sMimeTypeMap.loadEntry("image/jpeg", "jpg");
+            sMimeTypeMap.loadEntry("image/jpeg", "jpe");
+            sMimeTypeMap.loadEntry("image/pcx", "pcx");
+            sMimeTypeMap.loadEntry("image/png", "png");
+            sMimeTypeMap.loadEntry("image/svg+xml", "svg");
+            sMimeTypeMap.loadEntry("image/svg+xml", "svgz");
+            sMimeTypeMap.loadEntry("image/tiff", "tiff");
+            sMimeTypeMap.loadEntry("image/tiff", "tif");
+            sMimeTypeMap.loadEntry("image/vnd.djvu", "djvu");
+            sMimeTypeMap.loadEntry("image/vnd.djvu", "djv");
+            sMimeTypeMap.loadEntry("image/vnd.wap.wbmp", "wbmp");
+            sMimeTypeMap.loadEntry("image/x-cmu-raster", "ras");
+            sMimeTypeMap.loadEntry("image/x-coreldraw", "cdr");
+            sMimeTypeMap.loadEntry("image/x-coreldrawpattern", "pat");
+            sMimeTypeMap.loadEntry("image/x-coreldrawtemplate", "cdt");
+            sMimeTypeMap.loadEntry("image/x-corelphotopaint", "cpt");
+            sMimeTypeMap.loadEntry("image/x-icon", "ico");
+            sMimeTypeMap.loadEntry("image/x-jg", "art");
+            sMimeTypeMap.loadEntry("image/x-jng", "jng");
+            sMimeTypeMap.loadEntry("image/x-ms-bmp", "bmp");
+            sMimeTypeMap.loadEntry("image/x-photoshop", "psd");
+            sMimeTypeMap.loadEntry("image/x-portable-anymap", "pnm");
+            sMimeTypeMap.loadEntry("image/x-portable-bitmap", "pbm");
+            sMimeTypeMap.loadEntry("image/x-portable-graymap", "pgm");
+            sMimeTypeMap.loadEntry("image/x-portable-pixmap", "ppm");
+            sMimeTypeMap.loadEntry("image/x-rgb", "rgb");
+            sMimeTypeMap.loadEntry("image/x-xbitmap", "xbm");
+            sMimeTypeMap.loadEntry("image/x-xpixmap", "xpm");
+            sMimeTypeMap.loadEntry("image/x-xwindowdump", "xwd");
+            sMimeTypeMap.loadEntry("model/iges", "igs");
+            sMimeTypeMap.loadEntry("model/iges", "iges");
+            sMimeTypeMap.loadEntry("model/mesh", "msh");
+            sMimeTypeMap.loadEntry("model/mesh", "mesh");
+            sMimeTypeMap.loadEntry("model/mesh", "silo");
+            sMimeTypeMap.loadEntry("text/calendar", "ics");
+            sMimeTypeMap.loadEntry("text/calendar", "icz");
+            sMimeTypeMap.loadEntry("text/comma-separated-values", "csv");
+            sMimeTypeMap.loadEntry("text/css", "css");
+            sMimeTypeMap.loadEntry("text/h323", "323");
+            sMimeTypeMap.loadEntry("text/iuls", "uls");
+            sMimeTypeMap.loadEntry("text/mathml", "mml");
             // add it first so it will be the default for ExtensionFromMimeType
-            sMimeTypeMap.loadEntry("text/plain", "txt", true);
-            sMimeTypeMap.loadEntry("text/plain", "asc", true);
-            sMimeTypeMap.loadEntry("text/plain", "text", true);
-            sMimeTypeMap.loadEntry("text/plain", "diff", true);
-            sMimeTypeMap.loadEntry("text/plain", "pot", true);
-            sMimeTypeMap.loadEntry("text/richtext", "rtx", true);
-            sMimeTypeMap.loadEntry("text/rtf", "rtf", true);
-            sMimeTypeMap.loadEntry("text/texmacs", "ts", true);
-            sMimeTypeMap.loadEntry("text/text", "phps", true);
-            sMimeTypeMap.loadEntry("text/tab-separated-values", "tsv", true);
-            sMimeTypeMap.loadEntry("text/x-bibtex", "bib", true);
-            sMimeTypeMap.loadEntry("text/x-boo", "boo", true);
-            sMimeTypeMap.loadEntry("text/x-c++hdr", "h++", true);
-            sMimeTypeMap.loadEntry("text/x-c++hdr", "hpp", true);
-            sMimeTypeMap.loadEntry("text/x-c++hdr", "hxx", true);
-            sMimeTypeMap.loadEntry("text/x-c++hdr", "hh", true);
-            sMimeTypeMap.loadEntry("text/x-c++src", "c++", true);
-            sMimeTypeMap.loadEntry("text/x-c++src", "cpp", true);
-            sMimeTypeMap.loadEntry("text/x-c++src", "cxx", true);
-            sMimeTypeMap.loadEntry("text/x-chdr", "h", true);
-            sMimeTypeMap.loadEntry("text/x-component", "htc", true);
-            sMimeTypeMap.loadEntry("text/x-csh", "csh", true);
-            sMimeTypeMap.loadEntry("text/x-csrc", "c", true);
-            sMimeTypeMap.loadEntry("text/x-dsrc", "d", true);
-            sMimeTypeMap.loadEntry("text/x-haskell", "hs", true);
-            sMimeTypeMap.loadEntry("text/x-java", "java", true);
-            sMimeTypeMap.loadEntry("text/x-literate-haskell", "lhs", true);
-            sMimeTypeMap.loadEntry("text/x-moc", "moc", true);
-            sMimeTypeMap.loadEntry("text/x-pascal", "p", true);
-            sMimeTypeMap.loadEntry("text/x-pascal", "pas", true);
-            sMimeTypeMap.loadEntry("text/x-pcs-gcd", "gcd", true);
-            sMimeTypeMap.loadEntry("text/x-setext", "etx", true);
-            sMimeTypeMap.loadEntry("text/x-tcl", "tcl", true);
-            sMimeTypeMap.loadEntry("text/x-tex", "tex", true);
-            sMimeTypeMap.loadEntry("text/x-tex", "ltx", true);
-            sMimeTypeMap.loadEntry("text/x-tex", "sty", true);
-            sMimeTypeMap.loadEntry("text/x-tex", "cls", true);
-            sMimeTypeMap.loadEntry("text/x-vcalendar", "vcs", true);
-            sMimeTypeMap.loadEntry("text/x-vcard", "vcf", true);
-            sMimeTypeMap.loadEntry("video/3gpp", "3gp", false);
-            sMimeTypeMap.loadEntry("video/3gpp", "3g2", false);
-            sMimeTypeMap.loadEntry("video/dl", "dl", false);
-            sMimeTypeMap.loadEntry("video/dv", "dif", false);
-            sMimeTypeMap.loadEntry("video/dv", "dv", false);
-            sMimeTypeMap.loadEntry("video/fli", "fli", false);
-            sMimeTypeMap.loadEntry("video/mpeg", "mpeg", false);
-            sMimeTypeMap.loadEntry("video/mpeg", "mpg", false);
-            sMimeTypeMap.loadEntry("video/mpeg", "mpe", false);
-            sMimeTypeMap.loadEntry("video/mp4", "mp4", false);
-            sMimeTypeMap.loadEntry("video/mpeg", "VOB", false);
-            sMimeTypeMap.loadEntry("video/quicktime", "qt", false);
-            sMimeTypeMap.loadEntry("video/quicktime", "mov", false);
-            sMimeTypeMap.loadEntry("video/vnd.mpegurl", "mxu", false);
-            sMimeTypeMap.loadEntry("video/x-la-asf", "lsf", false);
-            sMimeTypeMap.loadEntry("video/x-la-asf", "lsx", false);
-            sMimeTypeMap.loadEntry("video/x-mng", "mng", false);
-            sMimeTypeMap.loadEntry("video/x-ms-asf", "asf", false);
-            sMimeTypeMap.loadEntry("video/x-ms-asf", "asx", false);
-            sMimeTypeMap.loadEntry("video/x-ms-wm", "wm", false);
-            sMimeTypeMap.loadEntry("video/x-ms-wmv", "wmv", false);
-            sMimeTypeMap.loadEntry("video/x-ms-wmx", "wmx", false);
-            sMimeTypeMap.loadEntry("video/x-ms-wvx", "wvx", false);
-            sMimeTypeMap.loadEntry("video/x-msvideo", "avi", false);
-            sMimeTypeMap.loadEntry("video/x-sgi-movie", "movie", false);
-            sMimeTypeMap.loadEntry("x-conference/x-cooltalk", "ice", false);
-            sMimeTypeMap.loadEntry("x-epoc/x-sisx-app", "sisx", false);
+            sMimeTypeMap.loadEntry("text/plain", "txt");
+            sMimeTypeMap.loadEntry("text/plain", "asc");
+            sMimeTypeMap.loadEntry("text/plain", "text");
+            sMimeTypeMap.loadEntry("text/plain", "diff");
+            sMimeTypeMap.loadEntry("text/plain", "pot");
+            sMimeTypeMap.loadEntry("text/richtext", "rtx");
+            sMimeTypeMap.loadEntry("text/rtf", "rtf");
+            sMimeTypeMap.loadEntry("text/texmacs", "ts");
+            sMimeTypeMap.loadEntry("text/text", "phps");
+            sMimeTypeMap.loadEntry("text/tab-separated-values", "tsv");
+            sMimeTypeMap.loadEntry("text/x-bibtex", "bib");
+            sMimeTypeMap.loadEntry("text/x-boo", "boo");
+            sMimeTypeMap.loadEntry("text/x-c++hdr", "h++");
+            sMimeTypeMap.loadEntry("text/x-c++hdr", "hpp");
+            sMimeTypeMap.loadEntry("text/x-c++hdr", "hxx");
+            sMimeTypeMap.loadEntry("text/x-c++hdr", "hh");
+            sMimeTypeMap.loadEntry("text/x-c++src", "c++");
+            sMimeTypeMap.loadEntry("text/x-c++src", "cpp");
+            sMimeTypeMap.loadEntry("text/x-c++src", "cxx");
+            sMimeTypeMap.loadEntry("text/x-chdr", "h");
+            sMimeTypeMap.loadEntry("text/x-component", "htc");
+            sMimeTypeMap.loadEntry("text/x-csh", "csh");
+            sMimeTypeMap.loadEntry("text/x-csrc", "c");
+            sMimeTypeMap.loadEntry("text/x-dsrc", "d");
+            sMimeTypeMap.loadEntry("text/x-haskell", "hs");
+            sMimeTypeMap.loadEntry("text/x-java", "java");
+            sMimeTypeMap.loadEntry("text/x-literate-haskell", "lhs");
+            sMimeTypeMap.loadEntry("text/x-moc", "moc");
+            sMimeTypeMap.loadEntry("text/x-pascal", "p");
+            sMimeTypeMap.loadEntry("text/x-pascal", "pas");
+            sMimeTypeMap.loadEntry("text/x-pcs-gcd", "gcd");
+            sMimeTypeMap.loadEntry("text/x-setext", "etx");
+            sMimeTypeMap.loadEntry("text/x-tcl", "tcl");
+            sMimeTypeMap.loadEntry("text/x-tex", "tex");
+            sMimeTypeMap.loadEntry("text/x-tex", "ltx");
+            sMimeTypeMap.loadEntry("text/x-tex", "sty");
+            sMimeTypeMap.loadEntry("text/x-tex", "cls");
+            sMimeTypeMap.loadEntry("text/x-vcalendar", "vcs");
+            sMimeTypeMap.loadEntry("text/x-vcard", "vcf");
+            sMimeTypeMap.loadEntry("video/3gpp", "3gp");
+            sMimeTypeMap.loadEntry("video/3gpp", "3g2");
+            sMimeTypeMap.loadEntry("video/dl", "dl");
+            sMimeTypeMap.loadEntry("video/dv", "dif");
+            sMimeTypeMap.loadEntry("video/dv", "dv");
+            sMimeTypeMap.loadEntry("video/fli", "fli");
+            sMimeTypeMap.loadEntry("video/mpeg", "mpeg");
+            sMimeTypeMap.loadEntry("video/mpeg", "mpg");
+            sMimeTypeMap.loadEntry("video/mpeg", "mpe");
+            sMimeTypeMap.loadEntry("video/mp4", "mp4");
+            sMimeTypeMap.loadEntry("video/mpeg", "VOB");
+            sMimeTypeMap.loadEntry("video/quicktime", "qt");
+            sMimeTypeMap.loadEntry("video/quicktime", "mov");
+            sMimeTypeMap.loadEntry("video/vnd.mpegurl", "mxu");
+            sMimeTypeMap.loadEntry("video/x-la-asf", "lsf");
+            sMimeTypeMap.loadEntry("video/x-la-asf", "lsx");
+            sMimeTypeMap.loadEntry("video/x-mng", "mng");
+            sMimeTypeMap.loadEntry("video/x-ms-asf", "asf");
+            sMimeTypeMap.loadEntry("video/x-ms-asf", "asx");
+            sMimeTypeMap.loadEntry("video/x-ms-wm", "wm");
+            sMimeTypeMap.loadEntry("video/x-ms-wmv", "wmv");
+            sMimeTypeMap.loadEntry("video/x-ms-wmx", "wmx");
+            sMimeTypeMap.loadEntry("video/x-ms-wvx", "wvx");
+            sMimeTypeMap.loadEntry("video/x-msvideo", "avi");
+            sMimeTypeMap.loadEntry("video/x-sgi-movie", "movie");
+            sMimeTypeMap.loadEntry("x-conference/x-cooltalk", "ice");
+            sMimeTypeMap.loadEntry("x-epoc/x-sisx-app", "sisx");
         }
 
         return sMimeTypeMap;
diff --git a/core/java/android/webkit/Network.java b/core/java/android/webkit/Network.java
index c9b80ce..fb60109 100644
--- a/core/java/android/webkit/Network.java
+++ b/core/java/android/webkit/Network.java
@@ -132,7 +132,7 @@
      * XXX: Must be created in the same thread as WebCore!!!!!
      */
     private Network(Context context) {
-        if (WebView.DEBUG) {
+        if (DebugFlags.NETWORK) {
             Assert.assertTrue(Thread.currentThread().
                     getName().equals(WebViewCore.THREAD_NAME));
         }
@@ -149,14 +149,12 @@
      * @param headers The http headers.
      * @param postData The body of the request.
      * @param loader A LoadListener for receiving the results of the request.
-     * @param isHighPriority True if this is high priority request.
      * @return True if the request was successfully queued.
      */
     public boolean requestURL(String method,
                               Map<String, String> headers,
                               byte [] postData,
-                              LoadListener loader,
-                              boolean isHighPriority) {
+                              LoadListener loader) {
 
         String url = loader.url();
 
@@ -188,7 +186,7 @@
 
         RequestHandle handle = q.queueRequest(
                 url, loader.getWebAddress(), method, headers, loader,
-                bodyProvider, bodyLength, isHighPriority);
+                bodyProvider, bodyLength);
         loader.attachRequestHandle(handle);
 
         if (loader.isSynchronous()) {
@@ -232,7 +230,7 @@
      * connecting through the proxy.
      */
     public synchronized void setProxyUsername(String proxyUsername) {
-        if (WebView.DEBUG) {
+        if (DebugFlags.NETWORK) {
             Assert.assertTrue(isValidProxySet());
         }
 
@@ -252,7 +250,7 @@
      * connecting through the proxy.
      */
     public synchronized void setProxyPassword(String proxyPassword) {
-        if (WebView.DEBUG) {
+        if (DebugFlags.NETWORK) {
             Assert.assertTrue(isValidProxySet());
         }
 
@@ -266,7 +264,7 @@
      * @return True iff succeeds.
      */
     public boolean saveState(Bundle outState) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.NETWORK) {
             Log.v(LOGTAG, "Network.saveState()");
         }
 
@@ -280,7 +278,7 @@
      * @return True iff succeeds.
      */
     public boolean restoreState(Bundle inState) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.NETWORK) {
             Log.v(LOGTAG, "Network.restoreState()");
         }
 
@@ -300,7 +298,7 @@
      * @param loader The loader that resulted in SSL errors.
      */
     public void handleSslErrorRequest(LoadListener loader) {
-        if (WebView.DEBUG) Assert.assertNotNull(loader);
+        if (DebugFlags.NETWORK) Assert.assertNotNull(loader);
         if (loader != null) {
             mSslErrorHandler.handleSslErrorRequest(loader);
         }
@@ -313,7 +311,7 @@
      * authentication request.
      */
     public void handleAuthRequest(LoadListener loader) {
-        if (WebView.DEBUG) Assert.assertNotNull(loader);
+        if (DebugFlags.NETWORK) Assert.assertNotNull(loader);
         if (loader != null) {
             mHttpAuthHandler.handleAuthRequest(loader);
         }
diff --git a/core/java/android/webkit/PluginManager.java b/core/java/android/webkit/PluginManager.java
new file mode 100644
index 0000000..e4a44b92
--- /dev/null
+++ b/core/java/android/webkit/PluginManager.java
@@ -0,0 +1,157 @@
+/*
+ * 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.
+ */
+
+package android.webkit;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import android.annotation.SdkConstant;
+import android.annotation.SdkConstant.SdkConstantType;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.content.pm.ServiceInfo;
+import android.content.pm.Signature;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.util.Log;
+
+/**
+ * Class for managing the relationship between the {@link WebView} and installed
+ * plugins in the system. You can find this class through
+ * {@link PluginManager#getInstance}.
+ * 
+ * @hide pending API solidification
+ */
+public class PluginManager {
+
+    /**
+     * Service Action: A plugin wishes to be loaded in the WebView must provide
+     * {@link android.content.IntentFilter IntentFilter} that accepts this
+     * action in their AndroidManifest.xml.
+     * <p>
+     * TODO: we may change this to a new PLUGIN_ACTION if this is going to be
+     * public.
+     */
+    @SdkConstant(SdkConstantType.SERVICE_ACTION)
+    public static final String PLUGIN_ACTION = "android.webkit.PLUGIN";
+
+    /**
+     * A plugin wishes to be loaded in the WebView must provide this permission
+     * in their AndroidManifest.xml.
+     */
+    public static final String PLUGIN_PERMISSION = "android.webkit.permission.PLUGIN";
+
+    private static final String LOGTAG = "webkit";
+
+    private static PluginManager mInstance = null;
+
+    private final Context mContext;
+
+    private PluginManager(Context context) {
+        mContext = context;
+    }
+
+    public static synchronized PluginManager getInstance(Context context) {
+        if (mInstance == null) {
+            if (context == null) {
+                throw new IllegalStateException(
+                        "First call to PluginManager need a valid context.");
+            }
+            mInstance = new PluginManager(context);
+        }
+        return mInstance;
+    }
+
+    /**
+     * Signal the WebCore thread to refresh its list of plugins. Use this if the
+     * directory contents of one of the plugin directories has been modified and
+     * needs its changes reflecting. May cause plugin load and/or unload.
+     * 
+     * @param reloadOpenPages Set to true to reload all open pages.
+     */
+    public void refreshPlugins(boolean reloadOpenPages) {
+        BrowserFrame.sJavaBridge.obtainMessage(
+                JWebCoreJavaBridge.REFRESH_PLUGINS, reloadOpenPages)
+                .sendToTarget();
+    }
+
+    String[] getPluginDirecoties() {
+        ArrayList<String> directories = new ArrayList<String>();
+        PackageManager pm = mContext.getPackageManager();
+        List<ResolveInfo> plugins = pm.queryIntentServices(new Intent(
+                PLUGIN_ACTION), PackageManager.GET_SERVICES);
+        for (ResolveInfo info : plugins) {
+            ServiceInfo serviceInfo = info.serviceInfo;
+            if (serviceInfo == null) {
+                Log.w(LOGTAG, "Ignore bad plugin");
+                continue;
+            }
+            PackageInfo pkgInfo;
+            try {
+                pkgInfo = pm.getPackageInfo(serviceInfo.packageName,
+                        PackageManager.GET_PERMISSIONS
+                                | PackageManager.GET_SIGNATURES);
+            } catch (NameNotFoundException e) {
+                Log.w(LOGTAG, "Cant find plugin: " + serviceInfo.packageName);
+                continue;
+            }
+            if (pkgInfo == null) {
+                continue;
+            }
+            String directory = pkgInfo.applicationInfo.dataDir + "/lib";
+            if (directories.contains(directory)) {
+                continue;
+            }
+            String permissions[] = pkgInfo.requestedPermissions;
+            if (permissions == null) {
+                continue;
+            }
+            boolean permissionOk = false;
+            for (String permit : permissions) {
+                if (PLUGIN_PERMISSION.equals(permit)) {
+                    permissionOk = true;
+                    break;
+                }
+            }
+            if (!permissionOk) {
+                continue;
+            }
+            Signature signatures[] = pkgInfo.signatures;
+            if (signatures == null) {
+                continue;
+            }
+            boolean signatureMatch = false;
+            for (Signature signature : signatures) {
+                // TODO: check signature against Google provided one
+                signatureMatch = true;
+                break;
+            }
+            if (!signatureMatch) {
+                continue;
+            }
+            directories.add(directory);
+        }
+        // hack for gears for now
+        String gears = mContext.getDir("plugins", 0).getPath();
+        if (!directories.contains(gears)) {
+            directories.add(gears);
+        }
+        return directories.toArray(new String[directories.size()]);
+    }
+}
diff --git a/core/java/android/webkit/SslErrorHandler.java b/core/java/android/webkit/SslErrorHandler.java
index 5f84bbe..cc1e750 100644
--- a/core/java/android/webkit/SslErrorHandler.java
+++ b/core/java/android/webkit/SslErrorHandler.java
@@ -120,7 +120,7 @@
      * Handles SSL error(s) on the way up to the user.
      */
     /* package */ synchronized void handleSslErrorRequest(LoadListener loader) {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.SSL_ERROR_HANDLER) {
             Log.v(LOGTAG, "SslErrorHandler.handleSslErrorRequest(): " +
                   "url=" + loader.url());
         }
@@ -157,14 +157,14 @@
 
             SslError error = loader.sslError();
 
-            if (WebView.DEBUG) {
+            if (DebugFlags.SSL_ERROR_HANDLER) {
                 Assert.assertNotNull(error);
             }
 
             int primary = error.getPrimaryError();
             String host = loader.host();
 
-            if (WebView.DEBUG) {
+            if (DebugFlags.SSL_ERROR_HANDLER) {
                 Assert.assertTrue(host != null && primary != 0);
             }
 
@@ -205,11 +205,11 @@
      */
     /* package */ synchronized void handleSslErrorResponse(boolean proceed) {
         LoadListener loader = mLoaderQueue.poll();
-        if (WebView.DEBUG) {
+        if (DebugFlags.SSL_ERROR_HANDLER) {
             Assert.assertNotNull(loader);
         }
 
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.SSL_ERROR_HANDLER) {
             Log.v(LOGTAG, "SslErrorHandler.handleSslErrorResponse():"
                   + " proceed: " + proceed
                   + " url:" + loader.url());
@@ -221,13 +221,13 @@
                 int primary = loader.sslError().getPrimaryError();
                 String host = loader.host();
 
-                if (WebView.DEBUG) {
+                if (DebugFlags.SSL_ERROR_HANDLER) {
                     Assert.assertTrue(host != null && primary != 0);
                 }
                 boolean hasKey = mSslPrefTable.containsKey(host);
                 if (!hasKey ||
                     primary > mSslPrefTable.getInt(host)) {
-                    mSslPrefTable.putInt(host, new Integer(primary));
+                    mSslPrefTable.putInt(host, primary);
                 }
             }
             loader.handleSslErrorResponse(proceed);
diff --git a/core/java/android/webkit/StreamLoader.java b/core/java/android/webkit/StreamLoader.java
index 705157c..eab3350 100644
--- a/core/java/android/webkit/StreamLoader.java
+++ b/core/java/android/webkit/StreamLoader.java
@@ -102,7 +102,7 @@
                 // to pass data to the loader
                 mData = new byte[8192];
                 sendHeaders();
-                while (!sendData());
+                while (!sendData() && !mHandler.cancelled());
                 closeStreamAndSendEndData();
                 mHandler.loadSynchronousMessages();
             }
@@ -113,9 +113,13 @@
      * @see android.os.Handler#handleMessage(android.os.Message)
      */
     public void handleMessage(Message msg) {
-        if (WebView.DEBUG && mHandler.isSynchronous()) {
+        if (DebugFlags.STREAM_LOADER && mHandler.isSynchronous()) {
             throw new AssertionError();
         }
+        if (mHandler.cancelled()) {
+            closeStreamAndSendEndData();
+            return;
+        }
         switch(msg.what) {
             case MSG_STATUS:
                 if (setupStreamAndSendStatus()) {
diff --git a/core/java/android/webkit/URLUtil.java b/core/java/android/webkit/URLUtil.java
index 9889fe9..1d18289 100644
--- a/core/java/android/webkit/URLUtil.java
+++ b/core/java/android/webkit/URLUtil.java
@@ -61,7 +61,7 @@
             webAddress = new WebAddress(inUrl);
         } catch (ParseException ex) {
 
-            if (WebView.LOGV_ENABLED) {
+            if (DebugFlags.URL_UTIL) {
                 Log.v(LOGTAG, "smartUrlFilter: failed to parse url = " + inUrl);
             }
             return retVal;
diff --git a/core/java/android/webkit/ViewManager.java b/core/java/android/webkit/ViewManager.java
new file mode 100644
index 0000000..af33b4f
--- /dev/null
+++ b/core/java/android/webkit/ViewManager.java
@@ -0,0 +1,137 @@
+/*
+ * 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.
+ */
+
+package android.webkit;
+
+import android.content.Context;
+import android.view.View;
+import android.widget.AbsoluteLayout;
+
+import java.util.ArrayList;
+
+class ViewManager {
+    private final WebView mWebView;
+    private final ArrayList<ChildView> mChildren = new ArrayList<ChildView>();
+    private boolean mHidden;
+
+    class ChildView {
+        int x;
+        int y;
+        int width;
+        int height;
+        View mView; // generic view to show
+
+        ChildView() {
+        }
+
+        void setBounds(int x, int y, int width, int height) {
+            this.x = x;
+            this.y = y;
+            this.width = width;
+            this.height = height;
+        }
+
+        void attachView(int x, int y, int width, int height) {
+            if (mView == null) {
+                return;
+            }
+            setBounds(x, y, width, height);
+            final AbsoluteLayout.LayoutParams lp =
+                    new AbsoluteLayout.LayoutParams(ctv(width), ctv(height),
+                            ctv(x), ctv(y));
+            mWebView.mPrivateHandler.post(new Runnable() {
+                public void run() {
+                    // This method may be called multiple times. If the view is
+                    // already attached, just set the new LayoutParams,
+                    // otherwise attach the view and add it to the list of
+                    // children.
+                    if (mView.getParent() != null) {
+                        mView.setLayoutParams(lp);
+                    } else {
+                        attachViewOnUIThread(lp);
+                    }
+                }
+            });
+        }
+
+        void attachViewOnUIThread(AbsoluteLayout.LayoutParams lp) {
+            mWebView.addView(mView, lp);
+            mChildren.add(this);
+        }
+
+        void removeView() {
+            if (mView == null) {
+                return;
+            }
+            mWebView.mPrivateHandler.post(new Runnable() {
+                public void run() {
+                    removeViewOnUIThread();
+                }
+            });
+        }
+
+        void removeViewOnUIThread() {
+            mWebView.removeView(mView);
+            mChildren.remove(this);
+        }
+    }
+
+    ViewManager(WebView w) {
+        mWebView = w;
+    }
+
+    ChildView createView() {
+        return new ChildView();
+    }
+
+    // contentToView shorthand.
+    private int ctv(int val) {
+        return mWebView.contentToView(val);
+    }
+
+    void scaleAll() {
+        for (ChildView v : mChildren) {
+            View view = v.mView;
+            AbsoluteLayout.LayoutParams lp =
+                    (AbsoluteLayout.LayoutParams) view.getLayoutParams();
+            lp.width = ctv(v.width);
+            lp.height = ctv(v.height);
+            lp.x = ctv(v.x);
+            lp.y = ctv(v.y);
+            view.setLayoutParams(lp);
+        }
+    }
+
+    void hideAll() {
+        if (mHidden) {
+            return;
+        }
+        for (ChildView v : mChildren) {
+            v.mView.setVisibility(View.GONE);
+        }
+        mHidden = true;
+    }
+
+    void showAll() {
+        if (!mHidden) {
+            return;
+        }
+        for (ChildView v : mChildren) {
+            v.mView.setVisibility(View.VISIBLE);
+        }
+        mHidden = false;
+    }
+}
diff --git a/core/java/android/webkit/WebBackForwardList.java b/core/java/android/webkit/WebBackForwardList.java
index ffd6a11..62a5531 100644
--- a/core/java/android/webkit/WebBackForwardList.java
+++ b/core/java/android/webkit/WebBackForwardList.java
@@ -137,7 +137,7 @@
         // when removing the first item, we can assert that the index is 0.
         // This lets us change the current index without having to query the
         // native BackForwardList.
-        if (WebView.DEBUG && (index != 0)) {
+        if (DebugFlags.WEB_BACK_FORWARD_LIST && (index != 0)) {
             throw new AssertionError();
         }
         final WebHistoryItem h = mArray.remove(index);
diff --git a/core/java/android/webkit/WebChromeClient.java b/core/java/android/webkit/WebChromeClient.java
index 9d9763c..dd43b8b 100644
--- a/core/java/android/webkit/WebChromeClient.java
+++ b/core/java/android/webkit/WebChromeClient.java
@@ -18,6 +18,7 @@
 
 import android.graphics.Bitmap;
 import android.os.Message;
+import android.view.View;
 
 public class WebChromeClient {
 
@@ -44,6 +45,39 @@
     public void onReceivedIcon(WebView view, Bitmap icon) {}
 
     /**
+     * A callback interface used by the host application to notify
+     * the current page that its custom view has been dismissed.
+     *
+     * @hide pending council approval
+     */
+    public interface CustomViewCallback {
+        /**
+         * Invoked when the host application dismisses the
+         * custom view.
+         */
+        public void onCustomViewHidden();
+    }
+
+    /**
+     * Notify the host application that the current page would
+     * like to show a custom View.
+     * @param view is the View object to be shown.
+     * @param callback is the callback to be invoked if and when the view
+     * is dismissed.
+     *
+     * @hide pending council approval
+     */
+    public void onShowCustomView(View view, CustomViewCallback callback) {};
+
+    /**
+     * Notify the host application that the current page would
+     * like to hide its custom view.
+     *
+     * @hide pending council approval
+     */
+    public void onHideCustomView() {}
+
+    /**
      * Request the host application to create a new Webview. The host
      * application should handle placement of the new WebView in the view
      * system. The default behavior returns null.
@@ -158,6 +192,23 @@
         return false;
     }
 
+   /**
+    * Tell the client that the database quota for the origin has been exceeded.
+    * @param url The URL that triggered the notification
+    * @param databaseIdentifier The identifier of the database that caused the
+    *     quota overflow.
+    * @param currentQuota The current quota for the origin.
+    * @param quotaUpdater A callback to inform the WebCore thread that a new
+    *     quota is available. This callback must always be executed at some
+    *     point to ensure that the sleeping WebCore thread is woken up.
+    */
+    public void onExceededDatabaseQuota(String url, String databaseIdentifier,
+        long currentQuota, WebStorage.QuotaUpdater quotaUpdater) {
+        // This default implementation passes the current quota back to WebCore.
+        // WebCore will interpret this that new quota was declined.
+        quotaUpdater.updateQuota(currentQuota);
+    }
+
     /**
      * Tell the client that a JavaScript execution timeout has occured. And the
      * client may decide whether or not to interrupt the execution. If the
@@ -172,4 +223,15 @@
     public boolean onJsTimeout() {
         return true;
     }
+
+    /**
+     * Add a JavaScript error message to the console. Clients should override
+     * this to process the log message as they see fit.
+     * @param message The error message to report.
+     * @param lineNumber The line number of the error.
+     * @param sourceID The name of the source file that caused the error.
+     * @hide pending API council.
+     */
+    public void addMessageToConsole(String message, int lineNumber, String sourceID) {
+    }
 }
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index c5012f1..b56f167 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -22,9 +22,7 @@
 import android.os.Handler;
 import android.os.Message;
 import android.provider.Checkin;
-
 import java.lang.SecurityException;
-
 import java.util.Locale;
 
 /**
@@ -130,9 +128,13 @@
     private boolean mSyncPending = false;
     // Custom handler that queues messages until the WebCore thread is active.
     private final EventHandler mEventHandler;
+
     // Private settings so we don't have to go into native code to
     // retrieve the values. After setXXX, postSync() needs to be called.
-    // XXX: The default values need to match those in WebSettings.cpp
+    //
+    // The default values need to match those in WebSettings.cpp
+    // If the defaults change, please also update the JavaDocs so developers
+    // know what they are.
     private LayoutAlgorithm mLayoutAlgorithm = LayoutAlgorithm.NARROW_COLUMNS;
     private Context         mContext;
     private TextSize        mTextSize = TextSize.NORMAL;
@@ -146,7 +148,6 @@
     private String          mUserAgent;
     private boolean         mUseDefaultUserAgent;
     private String          mAcceptLanguage;
-    private String          mPluginsPath = "";
     private int             mMinimumFontSize = 8;
     private int             mMinimumLogicalFontSize = 8;
     private int             mDefaultFontSize = 16;
@@ -156,6 +157,7 @@
     private boolean         mBlockNetworkLoads;
     private boolean         mJavaScriptEnabled = false;
     private boolean         mPluginsEnabled = false;
+    private long            mWebStorageDefaultQuota = 0;
     private boolean         mJavaScriptCanOpenWindowsAutomatically = false;
     private boolean         mUseDoubleTree = false;
     private boolean         mUseWideViewport = false;
@@ -175,9 +177,12 @@
     private boolean         mSupportZoom = true;
     private boolean         mBuiltInZoomControls = false;
     private boolean         mAllowFileAccess = true;
-
-    // The Gears permissions manager. Only in Donut.
-    static GearsPermissionsManager sGearsPermissionsManager;
+    private String          mDatabasePath = "";
+    private boolean         mDatabaseEnabled = false;
+    private String          mAppCachePath = "";
+    private boolean         mAppCacheEnabled = false;
+    private long            mAppCacheMaxSize = Long.MAX_VALUE;
+    private boolean         mDomStorageEnabled = false;
 
     // Class to handle messages before WebCore is ready.
     private class EventHandler {
@@ -246,13 +251,13 @@
 
     // User agent strings.
     private static final String DESKTOP_USERAGENT =
-            "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en)"
-            + " AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2"
-            + " Safari/525.20.1";
+            "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_7; en-us)"
+            + " AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0"
+            + " Safari/530.17";
     private static final String IPHONE_USERAGENT = 
-            "Mozilla/5.0 (iPhone; U; CPU iPhone 2_1 like Mac OS X; en)"
-            + " AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2"
-            + " Mobile/5F136 Safari/525.20.1";
+            "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us)"
+            + " AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0"
+            + " Mobile/7A341 Safari/528.16";
     private static Locale sLocale;
     private static Object sLockForLocaleSettings;
     
@@ -510,24 +515,21 @@
     }
 
     /**
-     * Tell the WebView to use the double tree rendering algorithm.
-     * @param use True if the WebView is to use double tree rendering, false
-     *            otherwise.
+     * @deprecated This setting controlled a rendering optimization
+     * that is no longer present. Setting it now has no effect.
      */
+    @Deprecated
     public synchronized void setUseDoubleTree(boolean use) {
-        if (mUseDoubleTree != use) {
-            mUseDoubleTree = use;
-            postSync();
-        }
+        return;
     }
 
     /**
-     * Return true if the WebView is using the double tree rendering algorithm.
-     * @return True if the WebView is using the double tree rendering
-     *         algorithm.
+     * @deprecated This setting controlled a rendering optimization
+     * that is no longer present. Setting it now has no effect.
      */
+    @Deprecated
     public synchronized boolean getUseDoubleTree() {
-        return mUseDoubleTree;
+        return false;
     }
 
     /**
@@ -632,7 +634,7 @@
     }
 
     /**
-     * Return the current layout algorithm.
+     * Return the current layout algorithm. The default is NARROW_COLUMNS.
      * @return LayoutAlgorithm enum value describing the layout algorithm
      *         being used.
      * @see WebSettings.LayoutAlgorithm
@@ -653,7 +655,7 @@
     }
 
     /**
-     * Get the standard font family name.
+     * Get the standard font family name. The default is "sans-serif".
      * @return The standard font family name as a string.
      */
     public synchronized String getStandardFontFamily() {
@@ -672,7 +674,7 @@
     }
 
     /**
-     * Get the fixed font family name.
+     * Get the fixed font family name. The default is "monospace".
      * @return The fixed font family name as a string.
      */
     public synchronized String getFixedFontFamily() {
@@ -699,7 +701,7 @@
     }
 
     /**
-     * Set the serif font family name.
+     * Set the serif font family name. The default is "sans-serif".
      * @param font A font family name.
      */
     public synchronized void setSerifFontFamily(String font) {
@@ -710,7 +712,7 @@
     }
 
     /**
-     * Get the serif font family name.
+     * Get the serif font family name. The default is "serif".
      * @return The serif font family name as a string.
      */
     public synchronized String getSerifFontFamily() {
@@ -729,7 +731,7 @@
     }
 
     /**
-     * Get the cursive font family name.
+     * Get the cursive font family name. The default is "cursive".
      * @return The cursive font family name as a string.
      */
     public synchronized String getCursiveFontFamily() {
@@ -748,7 +750,7 @@
     }
 
     /**
-     * Get the fantasy font family name.
+     * Get the fantasy font family name. The default is "fantasy".
      * @return The fantasy font family name as a string.
      */
     public synchronized String getFantasyFontFamily() {
@@ -769,7 +771,7 @@
     }
 
     /**
-     * Get the minimum font size.
+     * Get the minimum font size. The default is 8.
      * @return A non-negative integer between 1 and 72.
      */
     public synchronized int getMinimumFontSize() {
@@ -790,7 +792,7 @@
     }
 
     /**
-     * Get the minimum logical font size.
+     * Get the minimum logical font size. The default is 8.
      * @return A non-negative integer between 1 and 72.
      */
     public synchronized int getMinimumLogicalFontSize() {
@@ -811,7 +813,7 @@
     }
 
     /**
-     * Get the default font size.
+     * Get the default font size. The default is 16.
      * @return A non-negative integer between 1 and 72.
      */
     public synchronized int getDefaultFontSize() {
@@ -832,7 +834,7 @@
     }
 
     /**
-     * Get the default fixed font size.
+     * Get the default fixed font size. The default is 16.
      * @return A non-negative integer between 1 and 72.
      */
     public synchronized int getDefaultFixedFontSize() {
@@ -852,6 +854,7 @@
 
     /**
      * Return true if the WebView will load image resources automatically.
+     * The default is true.
      * @return True if the WebView loads images automatically.
      */
     public synchronized boolean getLoadsImagesAutomatically() {
@@ -871,16 +874,16 @@
     }
 
     /**
-     * Return true if the WebView will block network image.
+     * Return true if the WebView will block network image. The default is false.
      * @return True if the WebView blocks network image.
      */
     public synchronized boolean getBlockNetworkImage() {
         return mBlockNetworkImage;
     }
-    
+
     /**
      * @hide
-     * Tell the WebView to block all network load requests. 
+     * Tell the WebView to block all network load requests.
      * @param flag True if the WebView should block all network loads
      */
     public synchronized void setBlockNetworkLoads(boolean flag) {
@@ -893,13 +896,14 @@
     /**
      * @hide
      * Return true if the WebView will block all network loads.
+     * The default is false.
      * @return True if the WebView blocks all network loads.
      */
     public synchronized boolean getBlockNetworkLoads() {
         return mBlockNetworkLoads;
     }
-    
-    
+
+
     private void verifyNetworkAccess() {
         if (!mBlockNetworkLoads) {
             if (mContext.checkPermission("android.permission.INTERNET", 
@@ -935,19 +939,129 @@
     }
 
     /**
-     * Set a custom path to plugins used by the WebView. The client
-     * must ensure it exists before this call.
-     * @param pluginsPath String path to the directory containing plugins.
+     * TODO: need to add @Deprecated
      */
     public synchronized void setPluginsPath(String pluginsPath) {
-        if (pluginsPath != null && !pluginsPath.equals(mPluginsPath)) {
-            mPluginsPath = pluginsPath;
+    }
+
+    /**
+     * @hide
+     * Set the default quota for WebStorage DBs
+     * @param quota the default quota in bytes
+     */
+    public synchronized void setWebStorageDefaultQuota(long quota) {
+        if (mWebStorageDefaultQuota != quota) {
+            mWebStorageDefaultQuota = quota;
             postSync();
         }
     }
 
     /**
-     * Return true if javascript is enabled.
+     * Set the path to where database storage API databases should be saved.
+     * This will update WebCore when the Sync runs in the C++ side.
+     * @param databasePath String path to the directory where databases should
+     *     be saved. May be the empty string but should never be null.
+     */
+    public synchronized void setDatabasePath(String databasePath) {
+        if (databasePath != null && !databasePath.equals(mDatabasePath)) {
+            mDatabasePath = databasePath;
+            postSync();
+        }
+    }
+
+    /**
+     * Tell the WebView to enable Application Caches API.
+     * @param flag True if the WebView should enable Application Caches.
+     * @hide pending api council approval
+     */
+    public synchronized void setAppCacheEnabled(boolean flag) {
+        if (mAppCacheEnabled != flag) {
+            mAppCacheEnabled = flag;
+            postSync();
+        }
+    }
+
+    /**
+     * Set a custom path to the Application Caches files. The client
+     * must ensure it exists before this call.
+     * @param appCachePath String path to the directory containing Application
+     * Caches files. The appCache path can be the empty string but should not
+     * be null. Passing null for this parameter will result in a no-op.
+     * @hide pending api council approval
+     */
+    public synchronized void setAppCachePath(String appCachePath) {
+        if (appCachePath != null && !appCachePath.equals(mAppCachePath)) {
+            mAppCachePath = appCachePath;
+            postSync();
+        }
+    }
+
+    /**
+     * Set the maximum size for the Application Caches content.
+     * @param appCacheMaxSize the maximum size in bytes.
+     *
+     * @hide pending api council approval
+     */
+    public synchronized void setAppCacheMaxSize(long appCacheMaxSize) {
+        if (appCacheMaxSize != mAppCacheMaxSize) {
+            mAppCacheMaxSize = appCacheMaxSize;
+            postSync();
+        }
+    }
+
+    /**
+     * Set whether the database storage API is enabled.
+     * @param flag boolean True if the WebView should use the database storage
+     *     API.
+     */
+    public synchronized void setDatabaseEnabled(boolean flag) {
+       if (mDatabaseEnabled != flag) {
+           mDatabaseEnabled = flag;
+           postSync();
+       }
+    }
+
+    /**
+     * Set whether the DOM storage API is enabled.
+     * @param flag boolean True if the WebView should use the DOM storage
+     *     API.
+     * @hide pending API council.
+     */
+    public synchronized void setDomStorageEnabled(boolean flag) {
+       if (mDomStorageEnabled != flag) {
+           mDomStorageEnabled = flag;
+           postSync();
+       }
+    }
+
+    /**
+     * Returns true if the DOM Storage API's are enabled.
+     * @return True if the DOM Storage API's are enabled.
+     * @hide pending API council.
+     */
+    public synchronized boolean getDomStorageEnabled() {
+       return mDomStorageEnabled;
+    }
+
+    /**
+     * Return the path to where database storage API databases are saved for
+     * the current WebView.
+     * @return the String path to the database storage API databases.
+     */
+    public synchronized String getDatabasePath() {
+        return mDatabasePath;
+    }
+
+    /**
+     * Returns true if database storage API is enabled.
+     * @return True if the database storage API is enabled.
+     */
+    public synchronized boolean getDatabaseEnabled() {
+        return mDatabaseEnabled;
+    }
+
+    /**
+     * Return true if javascript is enabled. <b>Note: The default is false.</b>
      * @return True if javascript is enabled.
      */
     public synchronized boolean getJavaScriptEnabled() {
@@ -963,11 +1077,19 @@
     }
 
     /**
-     * Return the current path used for plugins in the WebView.
-     * @return The string path to the WebView plugins.
+     * TODO: need to add @Deprecated
      */
     public synchronized String getPluginsPath() {
-        return mPluginsPath;
+        return "";
+    }
+
+    /**
+     * @hide
+     * Return the default quota for WebStorage DBs
+     * @return the default quota in bytes
+     */
+    public synchronized long getWebStorageDefaultQuota() {
+        return mWebStorageDefaultQuota;
     }
 
     /**
@@ -984,7 +1106,8 @@
     }
 
     /**
-     * Return true if javascript can open windows automatically.
+     * Return true if javascript can open windows automatically. The default
+     * is false.
      * @return True if javascript can open windows automatically during
      *         window.open().
      */
@@ -1004,7 +1127,7 @@
     }
 
     /**
-     * Get the default text encoding name.
+     * Get the default text encoding name. The default is "Latin-1".
      * @return The default text encoding name as a string.
      */
     public synchronized String getDefaultTextEncodingName() {
@@ -1093,8 +1216,8 @@
 
     /**
      * Set the priority of the Render thread. Unlike the other settings, this
-     * one only needs to be called once per process.
-     * 
+     * one only needs to be called once per process. The default is NORMAL.
+     *
      * @param priority RenderPriority, can be normal, high or low.
      */
     public synchronized void setRenderPriority(RenderPriority priority) {
@@ -1148,10 +1271,9 @@
     /*package*/
     synchronized void syncSettingsAndCreateHandler(BrowserFrame frame) {
         mBrowserFrame = frame;
-        if (WebView.DEBUG) {
+        if (DebugFlags.WEB_SETTINGS) {
             junit.framework.Assert.assertTrue(frame.mNativeFrame != 0);
         }
-        checkGearsPermissions();
         nativeSync(frame.mNativeFrame);
         mSyncPending = false;
         mEventHandler.createHandler();
@@ -1167,23 +1289,6 @@
         return size;
     }
 
-    private void checkGearsPermissions() {
-        // Did we already check the permissions at startup?
-        if (sGearsPermissionsManager != null) {
-            return;
-        }
-        // Is the pluginsPath sane?
-        String pluginsPath = getPluginsPath();
-        if (pluginsPath == null || pluginsPath.length() == 0) {
-            // We don't yet have a meaningful plugin path, so
-            // we can't do anything about the Gears permissions.
-            return;
-        }
-        sGearsPermissionsManager =
-            new GearsPermissionsManager(mContext, pluginsPath);
-        sGearsPermissionsManager.doCheckAndStartObserver();
-    }
-
     /* Post a SYNC message to handle syncing the native settings. */
     private synchronized void postSync() {
         // Only post if a sync is not pending
diff --git a/core/java/android/webkit/WebStorage.java b/core/java/android/webkit/WebStorage.java
new file mode 100644
index 0000000..1a60dba
--- /dev/null
+++ b/core/java/android/webkit/WebStorage.java
@@ -0,0 +1,300 @@
+/*
+ * 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.
+ */
+
+package android.webkit;
+
+import android.os.Handler;
+import android.os.Message;
+import android.util.Log;
+
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+/**
+ * Functionality for manipulating the webstorage databases.
+ */
+public final class WebStorage {
+
+    /**
+     * Encapsulates a callback function to be executed when a new quota is made
+     * available. We primarily want this to allow us to call back the sleeping
+     * WebCore thread from outside the WebViewCore class (as the native call
+     * is private). It is imperative that this the setDatabaseQuota method is
+     * executed once a decision to either allow or deny new quota is made,
+     * otherwise the WebCore thread will remain asleep.
+     */
+    public interface QuotaUpdater {
+        public void updateQuota(long newQuota);
+    };
+
+    // Log tag
+    private static final String TAG = "webstorage";
+
+    // Global instance of a WebStorage
+    private static WebStorage sWebStorage;
+
+    // We keep the origins, quotas and usages as member values
+    // that we protect via a lock and update in syncValues().
+    // This is needed to transfer this data across threads.
+    private static Lock mLock = new ReentrantLock();
+    private static Condition mCacheUpdated = mLock.newCondition();
+
+    // Message ids
+    static final int UPDATE = 0;
+    static final int SET_QUOTA_ORIGIN = 1;
+    static final int DELETE_ORIGIN = 2;
+    static final int DELETE_ALL = 3;
+
+    private Set <String> mOrigins;
+    private HashMap <String, Long> mQuotas = new HashMap<String, Long>();
+    private HashMap <String, Long> mUsages = new HashMap<String, Long>();
+
+    private Handler mHandler = null;
+
+    private class Origin {
+        String mOrigin = null;
+        long mQuota = 0;
+
+        public Origin(String origin, long quota) {
+            mOrigin = origin;
+            mQuota = quota;
+        }
+
+        public Origin(String origin) {
+            mOrigin = origin;
+        }
+
+        public String getOrigin() {
+            return mOrigin;
+        }
+
+        public long getQuota() {
+            return mQuota;
+        }
+    }
+
+    /**
+     * @hide
+     * Message handler
+     */
+    public void createHandler() {
+        if (mHandler == null) {
+            mHandler = new Handler() {
+                @Override
+                public void handleMessage(Message msg) {
+                    switch (msg.what) {
+                        case SET_QUOTA_ORIGIN: {
+                            Origin website = (Origin) msg.obj;
+                            nativeSetQuotaForOrigin(website.getOrigin(),
+                                                    website.getQuota());
+                            } break;
+
+                        case DELETE_ORIGIN: {
+                            Origin website = (Origin) msg.obj;
+                            nativeDeleteOrigin(website.getOrigin());
+                            } break;
+
+                        case DELETE_ALL:
+                            nativeDeleteAllData();
+                            break;
+
+                        case UPDATE:
+                            syncValues();
+                            break;
+                    }
+                }
+            };
+        }
+    }
+
+    /**
+     * @hide
+     * Returns a list of origins having a database
+     */
+    public Set getOrigins() {
+        Set ret = null;
+        mLock.lock();
+        try {
+            update();
+            mCacheUpdated.await();
+            ret = mOrigins;
+        } catch (InterruptedException e) {
+            Log.e(TAG, "Exception while waiting on the updated origins", e);
+        } finally {
+            mLock.unlock();
+        }
+        return ret;
+    }
+
+    /**
+     * @hide
+     * Returns the use for a given origin
+     */
+    public long getUsageForOrigin(String origin) {
+        long ret = 0;
+        if (origin == null) {
+          return ret;
+        }
+        mLock.lock();
+        try {
+            update();
+            mCacheUpdated.await();
+            Long usage = mUsages.get(origin);
+            if (usage != null) {
+                ret = usage.longValue();
+            }
+        } catch (InterruptedException e) {
+            Log.e(TAG, "Exception while waiting on the updated origins", e);
+        } finally {
+            mLock.unlock();
+        }
+        return ret;
+    }
+
+    /**
+     * @hide
+     * Returns the quota for a given origin
+     */
+    public long getQuotaForOrigin(String origin) {
+        long ret = 0;
+        if (origin == null) {
+          return ret;
+        }
+        mLock.lock();
+        try {
+            update();
+            mCacheUpdated.await();
+            Long quota = mQuotas.get(origin);
+            if (quota != null) {
+                ret = quota.longValue();
+            }
+        } catch (InterruptedException e) {
+            Log.e(TAG, "Exception while waiting on the updated origins", e);
+        } finally {
+            mLock.unlock();
+        }
+        return ret;
+    }
+
+    /**
+     * @hide
+     * Set the quota for a given origin
+     */
+    public void setQuotaForOrigin(String origin, long quota) {
+        if (origin != null) {
+            if (WebViewCore.THREAD_NAME.equals(Thread.currentThread().getName())) {
+                nativeSetQuotaForOrigin(origin, quota);
+            } else {
+                postMessage(Message.obtain(null, SET_QUOTA_ORIGIN,
+                    new Origin(origin, quota)));
+            }
+        }
+    }
+
+    /**
+     * @hide
+     * Delete a given origin
+     */
+    public void deleteOrigin(String origin) {
+        if (origin != null) {
+            if (WebViewCore.THREAD_NAME.equals(Thread.currentThread().getName())) {
+                nativeDeleteOrigin(origin);
+            } else {
+                postMessage(Message.obtain(null, DELETE_ORIGIN,
+                    new Origin(origin)));
+            }
+        }
+    }
+
+    /**
+     * @hide
+     * Delete all databases
+     */
+    public void deleteAllData() {
+        if (WebViewCore.THREAD_NAME.equals(Thread.currentThread().getName())) {
+            nativeDeleteAllData();
+        } else {
+            postMessage(Message.obtain(null, DELETE_ALL));
+        }
+    }
+
+    /**
+     * Utility function to send a message to our handler
+     */
+    private void postMessage(Message msg) {
+        if (mHandler != null) {
+            mHandler.sendMessage(msg);
+        }
+    }
+
+    /**
+     * @hide
+     * Get the global instance of WebStorage.
+     * @return A single instance of WebStorage.
+     */
+    public static WebStorage getInstance() {
+      if (sWebStorage == null) {
+          sWebStorage = new WebStorage();
+      }
+      return sWebStorage;
+    }
+
+    /**
+     * @hide
+     * Post a Sync request
+     */
+    public void update() {
+        if (WebViewCore.THREAD_NAME.equals(Thread.currentThread().getName())) {
+            syncValues();
+        } else {
+            postMessage(Message.obtain(null, UPDATE));
+        }
+    }
+
+    /**
+     * Run on the webcore thread
+     * set the local values with the current ones
+     */
+    private void syncValues() {
+        mLock.lock();
+        Set tmp = nativeGetOrigins();
+        mOrigins = new HashSet<String>();
+        mQuotas.clear();
+        mUsages.clear();
+        Iterator<String> iter = tmp.iterator();
+        while (iter.hasNext()) {
+            String origin = iter.next();
+            mOrigins.add(origin);
+            mQuotas.put(origin, new Long(nativeGetQuotaForOrigin(origin)));
+            mUsages.put(origin, new Long(nativeGetUsageForOrigin(origin)));
+        }
+        mCacheUpdated.signal();
+        mLock.unlock();
+    }
+
+    // Native functions
+    private static native Set nativeGetOrigins();
+    private static native long nativeGetUsageForOrigin(String origin);
+    private static native long nativeGetQuotaForOrigin(String origin);
+    private static native void nativeSetQuotaForOrigin(String origin, long quota);
+    private static native void nativeDeleteOrigin(String origin);
+    private static native void nativeDeleteAllData();
+}
diff --git a/core/java/android/webkit/WebSyncManager.java b/core/java/android/webkit/WebSyncManager.java
index ded17ed..d3ec603 100644
--- a/core/java/android/webkit/WebSyncManager.java
+++ b/core/java/android/webkit/WebSyncManager.java
@@ -47,7 +47,7 @@
         @Override
         public void handleMessage(Message msg) {
             if (msg.what == SYNC_MESSAGE) {
-                if (WebView.LOGV_ENABLED) {
+                if (DebugFlags.WEB_SYNC_MANAGER) {
                     Log.v(LOGTAG, "*** WebSyncManager sync ***");
                 }
                 syncFromRamToFlash();
@@ -94,7 +94,7 @@
      * sync() forces sync manager to sync now
      */
     public void sync() {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.WEB_SYNC_MANAGER) {
             Log.v(LOGTAG, "*** WebSyncManager sync ***");
         }
         if (mHandler == null) {
@@ -109,7 +109,7 @@
      * resetSync() resets sync manager's timer
      */
     public void resetSync() {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.WEB_SYNC_MANAGER) {
             Log.v(LOGTAG, "*** WebSyncManager resetSync ***");
         }
         if (mHandler == null) {
@@ -124,7 +124,7 @@
      * startSync() requests sync manager to start sync
      */
     public void startSync() {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.WEB_SYNC_MANAGER) {
             Log.v(LOGTAG, "***  WebSyncManager startSync ***, Ref count:" + 
                     mStartSyncRefCount);
         }
@@ -142,7 +142,7 @@
      * the queue to break the sync loop
      */
     public void stopSync() {
-        if (WebView.LOGV_ENABLED) {
+        if (DebugFlags.WEB_SYNC_MANAGER) {
             Log.v(LOGTAG, "*** WebSyncManager stopSync ***, Ref count:" + 
                     mStartSyncRefCount);
         }
diff --git a/core/java/android/webkit/TextDialog.java b/core/java/android/webkit/WebTextView.java
similarity index 65%
rename from core/java/android/webkit/TextDialog.java
rename to core/java/android/webkit/WebTextView.java
index 99de56d..7bc154b 100644
--- a/core/java/android/webkit/TextDialog.java
+++ b/core/java/android/webkit/WebTextView.java
@@ -17,14 +17,13 @@
 package android.webkit;
 
 import android.content.Context;
+import android.graphics.Canvas;
 import android.graphics.Color;
+import android.graphics.ColorFilter;
 import android.graphics.Paint;
+import android.graphics.PixelFormat;
 import android.graphics.Rect;
-import android.graphics.drawable.ColorDrawable;
 import android.graphics.drawable.Drawable;
-import android.graphics.drawable.LayerDrawable;
-import android.graphics.drawable.ShapeDrawable;
-import android.graphics.drawable.shapes.RectShape;
 import android.text.Editable;
 import android.text.InputFilter;
 import android.text.Selection;
@@ -32,13 +31,17 @@
 import android.text.TextPaint;
 import android.text.TextUtils;
 import android.text.method.MovementMethod;
-import android.view.inputmethod.EditorInfo;
-import android.view.inputmethod.InputMethodManager;
+import android.text.method.Touch;
+import android.util.Log;
+import android.view.Gravity;
 import android.view.KeyCharacterMap;
 import android.view.KeyEvent;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
+import android.view.inputmethod.EditorInfo;
+import android.view.inputmethod.InputMethodManager;
+import android.view.inputmethod.InputConnection;
 import android.widget.AbsoluteLayout.LayoutParams;
 import android.widget.ArrayAdapter;
 import android.widget.AutoCompleteTextView;
@@ -47,11 +50,13 @@
 import java.util.ArrayList;
 
 /**
- * TextDialog is a specialized version of EditText used by WebView
+ * WebTextView is a specialized version of EditText used by WebView
  * to overlay html textfields (and textareas) to use our standard
  * text editing.
  */
-/* package */ class TextDialog extends AutoCompleteTextView {
+/* package */ class WebTextView extends AutoCompleteTextView {
+
+    static final String LOGTAG = "webtextview";
 
     private WebView         mWebView;
     private boolean         mSingle;
@@ -62,13 +67,20 @@
     // on the enter key.  The method for blocking unmatched key ups prevents
     // the shift key from working properly.
     private boolean         mGotEnterDown;
-    // mScrollToAccommodateCursor being set to false prevents us from scrolling
-    // the cursor on screen when using the trackball to select a textfield.
-    private boolean         mScrollToAccommodateCursor;
     private int             mMaxLength;
     // Keep track of the text before the change so we know whether we actually
     // need to send down the DOM events.
     private String          mPreChange;
+    private Drawable        mBackground;
+    // Variables for keeping track of the touch down, to send to the WebView
+    // when a drag starts
+    private float           mDragStartX;
+    private float           mDragStartY;
+    private long            mDragStartTime;
+    private boolean         mDragSent;
+    // True if the most recent drag event has caused either the TextView to
+    // scroll or the web page to scroll.  Gets reset after a touch down.
+    private boolean         mScrolled;
     // Array to store the final character added in onTextChanged, so that its
     // KeyEvents may be determined.
     private char[]          mCharacter = new char[1];
@@ -79,38 +91,14 @@
     private static final InputFilter[] NO_FILTERS = new InputFilter[0];
 
     /**
-     * Create a new TextDialog.
-     * @param   context The Context for this TextDialog.
+     * Create a new WebTextView.
+     * @param   context The Context for this WebTextView.
      * @param   webView The WebView that created this.
      */
-    /* package */ TextDialog(Context context, WebView webView) {
+    /* package */ WebTextView(Context context, WebView webView) {
         super(context);
         mWebView = webView;
-        ShapeDrawable background = new ShapeDrawable(new RectShape());
-        Paint shapePaint = background.getPaint();
-        shapePaint.setStyle(Paint.Style.STROKE);
-        ColorDrawable color = new ColorDrawable(Color.WHITE);
-        Drawable[] array = new Drawable[2];
-        array[0] = color;
-        array[1] = background;
-        LayerDrawable layers = new LayerDrawable(array);
-        // Hide WebCore's text behind this and allow the WebView
-        // to draw its own focusring.
-        setBackgroundDrawable(layers);
-        // Align the text better with the text behind it, so moving
-        // off of the textfield will not appear to move the text.
-        setPadding(3, 2, 0, 0);
         mMaxLength = -1;
-        // Turn on subpixel text, and turn off kerning, so it better matches
-        // the text in webkit.
-        TextPaint paint = getPaint();
-        int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG |
-                Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG;
-        paint.setFlags(flags);
-        // Set the text color to black, regardless of the theme.  This ensures
-        // that other applications that use embedded WebViews will properly
-        // display the text in textfields.
-        setTextColor(Color.BLACK);
         setImeOptions(EditorInfo.IME_ACTION_NONE);
     }
 
@@ -122,10 +110,36 @@
         // Treat ACTION_DOWN and ACTION MULTIPLE the same
         boolean down = event.getAction() != KeyEvent.ACTION_UP;
         int keyCode = event.getKeyCode();
+
+        boolean isArrowKey = false;
+        switch(keyCode) {
+            case KeyEvent.KEYCODE_DPAD_LEFT:
+            case KeyEvent.KEYCODE_DPAD_RIGHT:
+            case KeyEvent.KEYCODE_DPAD_UP:
+            case KeyEvent.KEYCODE_DPAD_DOWN:
+                if (!mWebView.nativeCursorMatchesFocus()) {
+                    return down ? mWebView.onKeyDown(keyCode, event) : mWebView
+                            .onKeyUp(keyCode, event);
+
+                }
+                isArrowKey = true;
+                break;
+        }
+
+        if (!isArrowKey && mWebView.nativeFocusNodePointer() != mNodePointer) {
+            mWebView.nativeClearCursor();
+            // Do not call remove() here, which hides the soft keyboard.  If
+            // the soft keyboard is being displayed, the user will still want
+            // it there.
+            mWebView.removeView(this);
+            mWebView.requestFocus();
+            return mWebView.dispatchKeyEvent(event);
+        }
+
         Spannable text = (Spannable) getText();
         int oldLength = text.length();
         // Normally the delete key's dom events are sent via onTextChanged.
-        // However, if the length is zero, the text did not change, so we 
+        // However, if the length is zero, the text did not change, so we
         // go ahead and pass the key down immediately.
         if (KeyEvent.KEYCODE_DEL == keyCode && 0 == oldLength) {
             sendDomEvent(event);
@@ -151,6 +165,10 @@
             if (isPopupShowing()) {
                 return super.dispatchKeyEvent(event);
             }
+            if (!mWebView.nativeCursorMatchesFocus()) {
+                return down ? mWebView.onKeyDown(keyCode, event) : mWebView
+                        .onKeyUp(keyCode, event);
+            }
             // Center key should be passed to a potential onClick
             if (!down) {
                 mWebView.shortPressOnTextField();
@@ -177,7 +195,7 @@
             oldText = "";
         }
         if (super.dispatchKeyEvent(event)) {
-            // If the TextDialog handled the key it was either an alphanumeric
+            // If the WebTextView handled the key it was either an alphanumeric
             // key, a delete, or a movement within the text. All of those are
             // ok to pass to javascript.
 
@@ -187,27 +205,15 @@
             // so do not pass down to javascript, and instead
             // return true.  If it is an arrow key or a delete key, we can go
             // ahead and pass it down.
-            boolean isArrowKey;
-            switch(keyCode) {
-                case KeyEvent.KEYCODE_DPAD_LEFT:
-                case KeyEvent.KEYCODE_DPAD_RIGHT:
-                case KeyEvent.KEYCODE_DPAD_UP:
-                case KeyEvent.KEYCODE_DPAD_DOWN:
-                    isArrowKey = true;
-                    break;
-                case KeyEvent.KEYCODE_ENTER:
-                    // For multi-line text boxes, newlines will
-                    // trigger onTextChanged for key down (which will send both
-                    // key up and key down) but not key up.
-                    mGotEnterDown = true;
-                default:
-                    isArrowKey = false;
-                    break;
+            if (KeyEvent.KEYCODE_ENTER == keyCode) {
+                // For multi-line text boxes, newlines will
+                // trigger onTextChanged for key down (which will send both
+                // key up and key down) but not key up.
+                mGotEnterDown = true;
             }
             if (maxedOut && !isArrowKey && keyCode != KeyEvent.KEYCODE_DEL) {
                 if (oldEnd == oldStart) {
                     // Return true so the key gets dropped.
-                    mScrollToAccommodateCursor = true;
                     return true;
                 } else if (!oldText.equals(getText().toString())) {
                     // FIXME: This makes the text work properly, but it
@@ -221,36 +227,33 @@
                     int newEnd = Selection.getSelectionEnd(span);
                     mWebView.replaceTextfieldText(0, oldLength, span.toString(),
                             newStart, newEnd);
-                    mScrollToAccommodateCursor = true;
                     return true;
                 }
             }
+            /* FIXME:
+             * In theory, we would like to send the events for the arrow keys.
+             * However, the TextView can arbitrarily change the selection (i.e.
+             * long press followed by using the trackball).  Therefore, we keep
+             * in sync with the TextView via onSelectionChanged.  If we also
+             * send the DOM event, we lose the correct selection.
             if (isArrowKey) {
                 // Arrow key does not change the text, but we still want to send
                 // the DOM events.
                 sendDomEvent(event);
             }
-            mScrollToAccommodateCursor = true;
+             */
             return true;
         }
-        // FIXME: TextViews return false for up and down key events even though
-        // they change the selection. Since we don't want the get out of sync
-        // with WebCore's notion of the current selection, reset the selection
-        // to what it was before the key event.
-        Selection.setSelection(text, oldStart, oldEnd);
         // Ignore the key up event for newlines. This prevents
         // multiple newlines in the native textarea.
         if (mGotEnterDown && !down) {
             return true;
         }
         // if it is a navigation key, pass it to WebView
-        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
-                || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
-                || keyCode == KeyEvent.KEYCODE_DPAD_UP
-                || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
+        if (isArrowKey) {
             // WebView check the trackballtime in onKeyDown to avoid calling
-            // native from both trackball and key handling. As this is called 
-            // from TextDialog, we always want WebView to check with native. 
+            // native from both trackball and key handling. As this is called
+            // from WebTextView, we always want WebView to check with native.
             // Reset trackballtime to ensure it.
             mWebView.resetTrackballTime();
             return down ? mWebView.onKeyDown(keyCode, event) : mWebView
@@ -260,9 +263,9 @@
     }
 
     /**
-     *  Create a fake touch up event at (x,y) with respect to this TextDialog.
+     *  Create a fake touch up event at (x,y) with respect to this WebTextView.
      *  This is used by WebView to act as though a touch event which happened
-     *  before we placed the TextDialog actually hit it, so that it can place
+     *  before we placed the WebTextView actually hit it, so that it can place
      *  the cursor accordingly.
      */
     /* package */ void fakeTouchEvent(float x, float y) {
@@ -279,31 +282,46 @@
     }
 
     /**
-     *  Determine whether this TextDialog currently represents the node
+     *  Determine whether this WebTextView currently represents the node
      *  represented by ptr.
      *  @param  ptr Pointer to a node to compare to.
-     *  @return boolean Whether this TextDialog already represents the node
+     *  @return boolean Whether this WebTextView already represents the node
      *          pointed to by ptr.
      */
     /* package */ boolean isSameTextField(int ptr) {
         return ptr == mNodePointer;
     }
 
-    @Override
-    public boolean onPreDraw() {
-        if (getLayout() == null) {
-            measure(mWidthSpec, mHeightSpec);
+    @Override public InputConnection onCreateInputConnection(
+            EditorInfo outAttrs) {
+        InputConnection connection = super.onCreateInputConnection(outAttrs);
+        if (mWebView != null) {
+            // Use the name of the textfield + the url.  Use backslash as an
+            // arbitrary separator.
+            outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\"
+                    + mWebView.getUrl();
         }
-        return super.onPreDraw();
+        return connection;
     }
-    
+
+    @Override
+    protected void onSelectionChanged(int selStart, int selEnd) {
+        if (mWebView != null) {
+            if (DebugFlags.WEB_TEXT_VIEW) {
+                Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart
+                        + " selEnd=" + selEnd);
+            }
+            mWebView.setSelection(selStart, selEnd);
+        }
+    }
+
     @Override
     protected void onTextChanged(CharSequence s,int start,int before,int count){
         super.onTextChanged(s, start, before, count);
         String postChange = s.toString();
         // Prevent calls to setText from invoking onTextChanged (since this will
         // mean we are on a different textfield).  Also prevent the change when
-        // going from a textfield with a string of text to one with a smaller 
+        // going from a textfield with a string of text to one with a smaller
         // limit on text length from registering the onTextChanged event.
         if (mPreChange == null || mPreChange.equals(postChange) ||
                 (mMaxLength > -1 && mPreChange.length() > mMaxLength &&
@@ -311,8 +329,7 @@
             return;
         }
         mPreChange = postChange;
-        // This was simply a delete or a cut, so just delete the 
-        // selection.
+        // This was simply a delete or a cut, so just delete the selection.
         if (before > 0 && 0 == count) {
             mWebView.deleteSelection(start, start + before);
             // For this and all changes to the text, update our cache
@@ -337,24 +354,87 @@
                     start + count - charactersFromKeyEvents,
                     start + count - charactersFromKeyEvents);
         } else {
-            // This corrects the selection which may have been affected by the 
+            // This corrects the selection which may have been affected by the
             // trackball or auto-correct.
+            if (DebugFlags.WEB_TEXT_VIEW) {
+                Log.v(LOGTAG, "onTextChanged start=" + start
+                        + " start + before=" + (start + before));
+            }
             mWebView.setSelection(start, start + before);
         }
-        updateCachedTextfield();
-        if (cannotUseKeyEvents) {
-            return;
-        }
-        int length = events.length;
-        for (int i = 0; i < length; i++) {
-            // We never send modifier keys to native code so don't send them
-            // here either.
-            if (!KeyEvent.isModifierKey(events[i].getKeyCode())) {
-                sendDomEvent(events[i]);
+        if (!cannotUseKeyEvents) {
+            int length = events.length;
+            for (int i = 0; i < length; i++) {
+                // We never send modifier keys to native code so don't send them
+                // here either.
+                if (!KeyEvent.isModifierKey(events[i].getKeyCode())) {
+                    sendDomEvent(events[i]);
+                }
             }
         }
+        updateCachedTextfield();
     }
-    
+
+    @Override
+    public boolean onTouchEvent(MotionEvent event) {
+        switch (event.getAction()) {
+        case MotionEvent.ACTION_DOWN:
+            super.onTouchEvent(event);
+            // This event may be the start of a drag, so store it to pass to the
+            // WebView if it is.
+            mDragStartX = event.getX();
+            mDragStartY = event.getY();
+            mDragStartTime = event.getEventTime();
+            mDragSent = false;
+            mScrolled = false;
+            break;
+        case MotionEvent.ACTION_MOVE:
+            Spannable buffer = getText();
+            int initialScrollX = Touch.getInitialScrollX(this, buffer);
+            int initialScrollY = Touch.getInitialScrollY(this, buffer);
+            super.onTouchEvent(event);
+            if (mScrollX != initialScrollX
+                    || mScrollY != initialScrollY) {
+                if (mWebView != null) {
+                    mWebView.scrollFocusedTextInput(mScrollX, mScrollY);
+                }
+                mScrolled = true;
+                return true;
+            }
+            if (mWebView != null) {
+                // Only want to set the initial state once.
+                if (!mDragSent) {
+                    mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY,
+                            mDragStartTime);
+                    mDragSent = true;
+                }
+                boolean scrolled = mWebView.textFieldDrag(event);
+                if (scrolled) {
+                    mScrolled = true;
+                    cancelLongPress();
+                    return true;
+                }
+            }
+            return false;
+        case MotionEvent.ACTION_UP:
+        case MotionEvent.ACTION_CANCEL:
+            if (!mScrolled) {
+                // If the page scrolled, or the TextView scrolled, we do not
+                // want to change the selection, and the long press has already
+                // been canceled, so there is no need to call into super.
+                super.onTouchEvent(event);
+            }
+            // Necessary for the WebView to reset its state
+            if (mWebView != null && mDragSent) {
+                mWebView.onTouchEvent(event);
+            }
+            break;
+        default:
+            break;
+        }
+        return true;
+    }
+
     @Override
     public boolean onTrackballEvent(MotionEvent event) {
         if (isPopupShowing()) {
@@ -363,29 +443,23 @@
         if (event.getAction() != MotionEvent.ACTION_MOVE) {
             return false;
         }
+        // If the Cursor is not on the text input, webview should handle the
+        // trackball
+        if (!mWebView.nativeCursorMatchesFocus()) {
+            return mWebView.onTrackballEvent(event);
+        }
         Spannable text = (Spannable) getText();
         MovementMethod move = getMovementMethod();
         if (move != null && getLayout() != null &&
             move.onTrackballEvent(this, text, event)) {
-            // Need to pass down the selection, which has changed.
-            // FIXME: This should work, but does not, so we set the selection
-            // in onTextChanged.
-            //int start = Selection.getSelectionStart(text);
-            //int end = Selection.getSelectionEnd(text);
-            //mWebView.setSelection(start, end);
+            // Selection is changed in onSelectionChanged
             return true;
         }
-        // If the user is in a textfield, and the movement method is not
-        // handling the trackball events, it means they are at the end of the
-        // field and continuing to move the trackball.  In this case, we should
-        // not scroll the cursor on screen bc the user may be attempting to
-        // scroll the page, possibly in the opposite direction of the cursor.
-        mScrollToAccommodateCursor = false;
         return false;
     }
 
     /**
-     * Remove this TextDialog from its host WebView, and return
+     * Remove this WebTextView from its host WebView, and return
      * focus to the host.
      */
     /* package */ void remove() {
@@ -394,11 +468,6 @@
                 getWindowToken(), 0);
         mWebView.removeView(this);
         mWebView.requestFocus();
-        mScrollToAccommodateCursor = false;
-    }
-
-    /* package */ void enableScrollOnScreen(boolean enable) {
-        mScrollToAccommodateCursor = enable;
     }
 
     /* package */ void bringIntoView() {
@@ -407,14 +476,6 @@
         }
     }
 
-    @Override
-    public boolean requestRectangleOnScreen(Rect rectangle) {
-        if (mScrollToAccommodateCursor) {
-            return super.requestRectangleOnScreen(rectangle);
-        }
-        return false;
-    }
-    
     /**
      *  Send the DOM events for the specified event.
      *  @param event    KeyEvent to be translated into a DOM event.
@@ -425,7 +486,7 @@
 
     /**
      *  Always use this instead of setAdapter, as this has features specific to
-     *  the TextDialog.
+     *  the WebTextView.
      */
     public void setAdapterCustom(AutoCompleteAdapter adapter) {
         if (adapter != null) {
@@ -476,7 +537,65 @@
         if (inPassword) {
             setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.
                     TYPE_TEXT_VARIATION_PASSWORD);
+            createBackground();
         }
+        // For password fields, draw the WebTextView.  For others, just show
+        // webkit's drawing.
+        setWillNotDraw(!inPassword);
+        setBackgroundDrawable(inPassword ? mBackground : null);
+        // For non-password fields, avoid the invals from TextView's blinking
+        // cursor
+        setCursorVisible(inPassword);
+    }
+
+    /**
+     * Private class used for the background of a password textfield.
+     */
+    private static class OutlineDrawable extends Drawable {
+        public void draw(Canvas canvas) {
+            Rect bounds = getBounds();
+            Paint paint = new Paint();
+            paint.setAntiAlias(true);
+            // Draw the background.
+            paint.setColor(Color.WHITE);
+            canvas.drawRect(bounds, paint);
+            // Draw the outline.
+            paint.setStyle(Paint.Style.STROKE);
+            paint.setColor(Color.BLACK);
+            canvas.drawRect(bounds, paint);
+        }
+        // Always want it to be opaque.
+        public int getOpacity() {
+            return PixelFormat.OPAQUE;
+        }
+        // These are needed because they are abstract in Drawable.
+        public void setAlpha(int alpha) { }
+        public void setColorFilter(ColorFilter cf) { }
+    }
+
+    /**
+     * Create a background for the WebTextView and set up the paint for drawing
+     * the text.  This way, we can see the password transformation of the
+     * system, which (optionally) shows the actual text before changing to dots.
+     * The background is necessary to hide the webkit-drawn text beneath.
+     */
+    private void createBackground() {
+        if (mBackground != null) {
+            return;
+        }
+        mBackground = new OutlineDrawable();
+
+        setGravity(Gravity.CENTER_VERTICAL);
+        // Turn on subpixel text, and turn off kerning, so it better matches
+        // the text in webkit.
+        TextPaint paint = getPaint();
+        int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG |
+                Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG;
+        paint.setFlags(flags);
+        // Set the text color to black, regardless of the theme.  This ensures
+        // that other applications that use embedded WebViews will properly
+        // display the text in password textfields.
+        setTextColor(Color.BLACK);
     }
 
     /* package */ void setMaxLength(int maxLength) {
@@ -491,16 +610,16 @@
 
     /**
      *  Set the pointer for this node so it can be determined which node this
-     *  TextDialog represents.
+     *  WebTextView represents.
      *  @param  ptr Integer representing the pointer to the node which this
-     *          TextDialog represents.
+     *          WebTextView represents.
      */
     /* package */ void setNodePointer(int ptr) {
         mNodePointer = ptr;
     }
 
     /**
-     * Determine the position and size of TextDialog, and add it to the
+     * Determine the position and size of WebTextView, and add it to the
      * WebView's view heirarchy.  All parameters are presumed to be in
      * view coordinates.  Also requests Focus and sets the cursor to not
      * request to be in view.
@@ -551,8 +670,8 @@
     }
 
     /**
-     * Set the text for this TextDialog, and set the selection to (start, end)
-     * @param   text    Text to go into this TextDialog.
+     * Set the text for this WebTextView, and set the selection to (start, end)
+     * @param   text    Text to go into this WebTextView.
      * @param   start   Beginning of the selection.
      * @param   end     End of the selection.
      */
@@ -569,6 +688,10 @@
         } else if (start > length) {
             start = length;
         }
+        if (DebugFlags.WEB_TEXT_VIEW) {
+            Log.v(LOGTAG, "setText start=" + start
+                    + " end=" + end);
+        }
         Selection.setSelection(span, start, end);
     }
 
@@ -583,7 +706,7 @@
         edit.replace(0, edit.length(), text);
         updateCachedTextfield();
     }
-    
+
     /**
      *  Update the cache to reflect the current text.
      */
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index fcf946f..19df87f 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -58,7 +58,7 @@
 import android.view.ViewTreeObserver;
 import android.view.animation.AlphaAnimation;
 import android.view.inputmethod.InputMethodManager;
-import android.webkit.TextDialog.AutoCompleteAdapter;
+import android.webkit.WebTextView.AutoCompleteAdapter;
 import android.webkit.WebViewCore.EventHub;
 import android.widget.AbsoluteLayout;
 import android.widget.Adapter;
@@ -80,11 +80,10 @@
 import java.io.IOException;
 import java.net.URLDecoder;
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.List;
 
 /**
- * <p>A View that displays web pages. This class is the basis upon which you 
+ * <p>A View that displays web pages. This class is the basis upon which you
  * can roll your own web browser or simply display some online content within your Activity.
  * It uses the WebKit rendering engine to display
  * web pages and includes methods to navigate forward and backward
@@ -93,12 +92,109 @@
  * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
  * (introduced in API version 3).
  * <p>Note that, in order for your Activity to access the Internet and load web pages
- * in a WebView, you must add the <var>INTERNET</var> permissions to your 
+ * in a WebView, you must add the <var>INTERNET</var> permissions to your
  * Android Manifest file:</p>
  * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
+ *
  * <p>This must be a child of the <code>&lt;manifest></code> element.</p>
+ *
+ * <h3>Basic usage</h3>
+ *
+ * <p>By default, a WebView provides no browser-like widgets, does not
+ * enable JavaScript and errors will be ignored. If your goal is only
+ * to display some HTML as a part of your UI, this is probably fine;
+ * the user won't need to interact with the web page beyond reading
+ * it, and the web page won't need to interact with the user. If you
+ * actually want a fully blown web browser, then you probably want to
+ * invoke the Browser application with your URL rather than show it
+ * with a WebView. See {@link android.content.Intent} for more information.</p>
+ *
+ * <pre class="prettyprint">
+ * WebView webview = new WebView(this);
+ * setContentView(webview);
+ *
+ * // Simplest usage: note that an exception will NOT be thrown
+ * // if there is an error loading this page (see below).
+ * webview.loadUrl("http://slashdot.org/");
+ *
+ * // Of course you can also load from any string:
+ * String summary = "&lt;html>&lt;body>You scored &lt;b>192</b> points.&lt;/body>&lt;/html>";
+ * webview.loadData(summary, "text/html", "utf-8");
+ * // ... although note that there are restrictions on what this HTML can do.
+ * // See the JavaDocs for loadData and loadDataWithBaseUrl for more info.
+ * </pre>
+ *
+ * <p>A WebView has several customization points where you can add your
+ * own behavior. These are:</p>
+ *
+ * <ul>
+ *   <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
+ *       This class is called when something that might impact a
+ *       browser UI happens, for instance, progress updates and
+ *       JavaScript alerts are sent here.
+ *   </li>
+ *   <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
+ *       It will be called when things happen that impact the
+ *       rendering of the content, eg, errors or form submissions. You
+ *       can also intercept URL loading here.</li>
+ *   <li>Via the {@link android.webkit.WebSettings} class, which contains
+ *       miscellaneous configuration. </li>
+ *   <li>With the {@link android.webkit.WebView#addJavascriptInterface} method.
+ *       This lets you bind Java objects into the WebView so they can be
+ *       controlled from the web pages JavaScript.</li>
+ * </ul>
+ *
+ * <p>Here's a more complicated example, showing error handling,
+ *    settings, and progress notification:</p>
+ *
+ * <pre class="prettyprint">
+ * // Let's display the progress in the activity title bar, like the
+ * // browser app does.
+ * getWindow().requestFeature(Window.FEATURE_PROGRESS);
+ *
+ * webview.getSettings().setJavaScriptEnabled(true);
+ *
+ * final Activity activity = this;
+ * webview.setWebChromeClient(new WebChromeClient() {
+ *   public void onProgressChanged(WebView view, int progress) {
+ *     // Activities and WebViews measure progress with different scales.
+ *     // The progress meter will automatically disappear when we reach 100%
+ *     activity.setProgress(progress * 1000);
+ *   }
+ * });
+ * webview.setWebViewClient(new WebViewClient() {
+ *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
+ *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
+ *   }
+ * });
+ *
+ * webview.loadUrl("http://slashdot.org/");
+ * </pre>
+ *
+ * <h3>Cookie and window management</h3>
+ *
+ * <p>For obvious security reasons, your application has its own
+ * cache, cookie store etc - it does not share the Browser
+ * applications data. Cookies are managed on a separate thread, so
+ * operations like index building don't block the UI
+ * thread. Follow the instructions in {@link android.webkit.CookieSyncManager}
+ * if you want to use cookies in your application.
+ * </p>
+ *
+ * <p>By default, requests by the HTML to open new windows are
+ * ignored. This is true whether they be opened by JavaScript or by
+ * the target attribute on a link. You can customize your
+ * WebChromeClient to provide your own behaviour for opening multiple windows,
+ * and render them in whatever manner you want.</p>
+ *
+ * <p>Standard behavior for an Activity is to be destroyed and
+ * recreated when the devices orientation is changed. This will cause
+ * the WebView to reload the current page. If you don't want that, you
+ * can set your Activity to handle the orientation and keyboardHidden
+ * changes, and then just leave the WebView alone. It'll automatically
+ * re-orient itself as appropriate.</p>
  */
-public class WebView extends AbsoluteLayout 
+public class WebView extends AbsoluteLayout
         implements ViewTreeObserver.OnGlobalFocusChangeListener,
         ViewGroup.OnHierarchyChangeListener {
 
@@ -108,62 +204,66 @@
     // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK
     private boolean mAutoRedraw;
 
-    // keep debugging parameters near the top of the file
     static final String LOGTAG = "webview";
-    static final boolean DEBUG = false;
-    static final boolean LOGV_ENABLED = DEBUG;
 
-    private class ExtendedZoomControls extends FrameLayout {
+    static class ScaleLimitData {
+        int mMinScale;
+        int mMaxScale;
+    }
+
+    private static class ExtendedZoomControls extends FrameLayout {
         public ExtendedZoomControls(Context context, AttributeSet attrs) {
             super(context, attrs);
             LayoutInflater inflater = (LayoutInflater)
                     context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true);
-            mZoomControls = (ZoomControls) findViewById(com.android.internal.R.id.zoomControls);
+            mPlusMinusZoomControls = (ZoomControls) findViewById(
+                    com.android.internal.R.id.zoomControls);
             mZoomMagnify = (ImageView) findViewById(com.android.internal.R.id.zoomMagnify);
         }
-        
+
         public void show(boolean showZoom, boolean canZoomOut) {
-            mZoomControls.setVisibility(showZoom ? View.VISIBLE : View.GONE);
+            mPlusMinusZoomControls.setVisibility(
+                    showZoom ? View.VISIBLE : View.GONE);
             mZoomMagnify.setVisibility(canZoomOut ? View.VISIBLE : View.GONE);
             fade(View.VISIBLE, 0.0f, 1.0f);
         }
-        
+
         public void hide() {
             fade(View.GONE, 1.0f, 0.0f);
         }
-        
+
         private void fade(int visibility, float startAlpha, float endAlpha) {
             AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha);
             anim.setDuration(500);
             startAnimation(anim);
             setVisibility(visibility);
         }
-        
+
         public void setIsZoomMagnifyEnabled(boolean isEnabled) {
             mZoomMagnify.setEnabled(isEnabled);
         }
-        
+
         public boolean hasFocus() {
-            return mZoomControls.hasFocus() || mZoomMagnify.hasFocus();
+            return mPlusMinusZoomControls.hasFocus() || mZoomMagnify.hasFocus();
         }
-        
+
         public void setOnZoomInClickListener(OnClickListener listener) {
-            mZoomControls.setOnZoomInClickListener(listener);
+            mPlusMinusZoomControls.setOnZoomInClickListener(listener);
         }
-            
+
         public void setOnZoomOutClickListener(OnClickListener listener) {
-            mZoomControls.setOnZoomOutClickListener(listener);
+            mPlusMinusZoomControls.setOnZoomOutClickListener(listener);
         }
-            
+
         public void setOnZoomMagnifyClickListener(OnClickListener listener) {
             mZoomMagnify.setOnClickListener(listener);
         }
 
-        ZoomControls mZoomControls;
-        ImageView mZoomMagnify;
+        ZoomControls    mPlusMinusZoomControls;
+        ImageView       mZoomMagnify;
     }
-    
+
     /**
      *  Transportation object for returning WebView across thread boundaries.
      */
@@ -203,11 +303,14 @@
     private WebViewCore mWebViewCore;
     // Handler for dispatching UI messages.
     /* package */ final Handler mPrivateHandler = new PrivateHandler();
-    private TextDialog mTextEntry;
+    private WebTextView mWebTextView;
     // Used to ignore changes to webkit text that arrives to the UI side after
     // more key events.
     private int mTextGeneration;
 
+    // Used by WebViewCore to create child views.
+    /* package */ final ViewManager mViewManager;
+
     // The list of loaded plugins.
     private static PluginList sPluginList;
 
@@ -229,9 +332,18 @@
 
     /**
      * The minimum elapsed time before sending another ACTION_MOVE event to
-     * WebViewCore
+     * WebViewCore. This really should be tuned for each type of the devices.
+     * For example in Google Map api test case, it takes Dream device at least
+     * 150ms to do a full cycle in the WebViewCore by processing a touch event,
+     * triggering the layout and drawing the picture. While the same process
+     * takes 60+ms on the current high speed device. If we make
+     * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent
+     * to WebViewCore queue and the real layout and draw events will be pushed
+     * to further, which slows down the refresh rate. Choose 50 to favor the
+     * current high speed devices. For Dream like devices, 100 is a better
+     * choice. Maybe make this in the buildspec later.
      */
-    private static final int TOUCH_SENT_INTERVAL = 100;
+    private static final int TOUCH_SENT_INTERVAL = 50;
 
     /**
      * Helper class to get velocity for fling
@@ -267,12 +379,15 @@
     // take control of touch events unless it says no for touch down event.
     private boolean mPreventDrag;
 
-    // If updateTextEntry gets called while we are out of focus, use this 
-    // variable to remember to do it next time we gain focus.
-    private boolean mNeedsUpdateTextEntry = false;
-    
-    // Whether or not to draw the focus ring.
-    private boolean mDrawFocusRing = true;
+    // To keep track of whether the current drag was initiated by a WebTextView,
+    // so that we know not to hide the cursor
+    boolean mDragFromTextInput;
+
+    // Whether or not to draw the cursor ring.
+    private boolean mDrawCursorRing = true;
+
+    // true if onPause has been called (and not onResume)
+    private boolean mIsPaused;
 
     /**
      * Customizable constant
@@ -292,7 +407,7 @@
     // needed to avoid flinging after a pause of no movement
     private static final int MIN_FLING_TIME = 250;
     // The time that the Zoom Controls are visible before fading away
-    private static final long ZOOM_CONTROLS_TIMEOUT = 
+    private static final long ZOOM_CONTROLS_TIMEOUT =
             ViewConfiguration.getZoomControlsTimeout();
     // The amount of content to overlap between two screens when going through
     // pages with the space bar, in pixels.
@@ -313,7 +428,7 @@
     private int mContentWidth;   // cache of value from WebViewCore
     private int mContentHeight;  // cache of value from WebViewCore
 
-    // Need to have the separate control for horizontal and vertical scrollbar 
+    // Need to have the separate control for horizontal and vertical scrollbar
     // style than the View's single scrollbar style
     private boolean mOverlayHorizontalScrollbar = true;
     private boolean mOverlayVerticalScrollbar = false;
@@ -328,51 +443,49 @@
 
     private boolean mWrapContent;
 
-    // true if we should call webcore to draw the content, false means we have
-    // requested something but it isn't ready to draw yet.
-    private WebViewCore.FocusData mFocusData;
     /**
      * Private message ids
      */
-    private static final int REMEMBER_PASSWORD = 1;
-    private static final int NEVER_REMEMBER_PASSWORD = 2;
-    private static final int SWITCH_TO_SHORTPRESS = 3;
-    private static final int SWITCH_TO_LONGPRESS = 4;
-    private static final int UPDATE_TEXT_ENTRY_ADAPTER = 6;
-    private static final int SWITCH_TO_ENTER = 7;
-    private static final int RESUME_WEBCORE_UPDATE = 8;
+    private static final int REMEMBER_PASSWORD          = 1;
+    private static final int NEVER_REMEMBER_PASSWORD    = 2;
+    private static final int SWITCH_TO_SHORTPRESS       = 3;
+    private static final int SWITCH_TO_LONGPRESS        = 4;
+    private static final int REQUEST_FORM_DATA          = 6;
+    private static final int SWITCH_TO_CLICK            = 7;
+    private static final int RESUME_WEBCORE_UPDATE      = 8;
 
     //! arg1=x, arg2=y
-    static final int SCROLL_TO_MSG_ID               = 10;
-    static final int SCROLL_BY_MSG_ID               = 11;
+    static final int SCROLL_TO_MSG_ID                   = 10;
+    static final int SCROLL_BY_MSG_ID                   = 11;
     //! arg1=x, arg2=y
-    static final int SPAWN_SCROLL_TO_MSG_ID         = 12;
+    static final int SPAWN_SCROLL_TO_MSG_ID             = 12;
     //! arg1=x, arg2=y
-    static final int SYNC_SCROLL_TO_MSG_ID          = 13;
-    static final int NEW_PICTURE_MSG_ID             = 14;
-    static final int UPDATE_TEXT_ENTRY_MSG_ID       = 15;
-    static final int WEBCORE_INITIALIZED_MSG_ID     = 16;
-    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID   = 17;
-    static final int DID_FIRST_LAYOUT_MSG_ID        = 18;
-    static final int RECOMPUTE_FOCUS_MSG_ID         = 19;
-    static final int NOTIFY_FOCUS_SET_MSG_ID        = 20;
-    static final int MARK_NODE_INVALID_ID           = 21;
-    static final int UPDATE_CLIPBOARD               = 22;
-    static final int LONG_PRESS_ENTER               = 23;
-    static final int PREVENT_TOUCH_ID               = 24;
-    static final int WEBCORE_NEED_TOUCH_EVENTS      = 25;
+    static final int SYNC_SCROLL_TO_MSG_ID              = 13;
+    static final int NEW_PICTURE_MSG_ID                 = 14;
+    static final int UPDATE_TEXT_ENTRY_MSG_ID           = 15;
+    static final int WEBCORE_INITIALIZED_MSG_ID         = 16;
+    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 17;
+    static final int DID_FIRST_LAYOUT_MSG_ID            = 18;
+    static final int MOVE_OUT_OF_PLUGIN                 = 19;
+    static final int CLEAR_TEXT_ENTRY                   = 20;
+
+    static final int UPDATE_CLIPBOARD                   = 22;
+    static final int LONG_PRESS_CENTER                  = 23;
+    static final int PREVENT_TOUCH_ID                   = 24;
+    static final int WEBCORE_NEED_TOUCH_EVENTS          = 25;
     // obj=Rect in doc coordinates
-    static final int INVAL_RECT_MSG_ID              = 26;
-    
+    static final int INVAL_RECT_MSG_ID                  = 26;
+    static final int REQUEST_KEYBOARD                   = 27;
+
     static final String[] HandlerDebugString = {
-        "REMEMBER_PASSWORD", // = 1;
-        "NEVER_REMEMBER_PASSWORD", // = 2;
-        "SWITCH_TO_SHORTPRESS", // = 3;
-        "SWITCH_TO_LONGPRESS", // = 4;
+        "REMEMBER_PASSWORD", //              = 1;
+        "NEVER_REMEMBER_PASSWORD", //        = 2;
+        "SWITCH_TO_SHORTPRESS", //           = 3;
+        "SWITCH_TO_LONGPRESS", //            = 4;
         "5",
-        "UPDATE_TEXT_ENTRY_ADAPTER", // = 6;
-        "SWITCH_TO_ENTER", // = 7;
-        "RESUME_WEBCORE_UPDATE", // = 8;
+        "REQUEST_FORM_DATA", //              = 6;
+        "SWITCH_TO_CLICK", //                = 7;
+        "RESUME_WEBCORE_UPDATE", //          = 8;
         "9",
         "SCROLL_TO_MSG_ID", //               = 10;
         "SCROLL_BY_MSG_ID", //               = 11;
@@ -383,14 +496,15 @@
         "WEBCORE_INITIALIZED_MSG_ID", //     = 16;
         "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 17;
         "DID_FIRST_LAYOUT_MSG_ID", //        = 18;
-        "RECOMPUTE_FOCUS_MSG_ID", //         = 19;
-        "NOTIFY_FOCUS_SET_MSG_ID", //        = 20;
-        "MARK_NODE_INVALID_ID", //           = 21;
+        "MOVE_OUT_OF_PLUGIN", //             = 19;
+        "CLEAR_TEXT_ENTRY", //               = 20;
+        "21", //                             = 21;
         "UPDATE_CLIPBOARD", //               = 22;
-        "LONG_PRESS_ENTER", //               = 23;
+        "LONG_PRESS_CENTER", //              = 23;
         "PREVENT_TOUCH_ID", //               = 24;
         "WEBCORE_NEED_TOUCH_EVENTS", //      = 25;
-        "INVAL_RECT_MSG_ID" //               = 26;
+        "INVAL_RECT_MSG_ID", //              = 26;
+        "REQUEST_KEYBOARD" //                = 27;
     };
 
     // width which view is considered to be fully zoomed out
@@ -421,6 +535,8 @@
     private float mZoomScale;
     private float mInvInitialZoomScale;
     private float mInvFinalZoomScale;
+    private int mInitialScrollX;
+    private int mInitialScrollY;
     private long mZoomStart;
     private static final int ZOOM_ANIMATION_LENGTH = 500;
 
@@ -433,7 +549,7 @@
     private static final int SNAP_X_LOCK = 4;
     private static final int SNAP_Y_LOCK = 5;
     private boolean mSnapPositive;
-    
+
     // Used to match key downs and key ups
     private boolean mGotKeyDown;
 
@@ -456,7 +572,7 @@
      * URI scheme for map address
      */
     public static final String SCHEME_GEO = "geo:0,0?q=";
-    
+
     private int mBackgroundColor = Color.WHITE;
 
     // Used to notify listeners of a new picture.
@@ -473,7 +589,8 @@
         public void onNewPicture(WebView view, Picture picture);
     }
 
-    public class HitTestResult {
+    // FIXME: Want to make this public, but need to change the API file.
+    public /*static*/ class HitTestResult {
         /**
          * Default HitTestResult, where the target is unknown
          */
@@ -543,9 +660,7 @@
     private ExtendedZoomControls mZoomControls;
     private Runnable mZoomControlRunnable;
 
-    private ZoomButtonsController mZoomButtonsController; 
-    private ImageView mZoomOverviewButton;
-    private ImageView mZoomFitPageButton;
+    private ZoomButtonsController mZoomButtonsController;
 
     // These keep track of the center point of the zoom.  They are used to
     // determine the point around which we should zoom.
@@ -568,11 +683,11 @@
             } else {
                 zoomOut();
             }
-            
+
             updateZoomButtonsEnabled();
         }
     };
-    
+
     /**
      * Construct a new WebView with a Context object.
      * @param context A Context object used to access application assets.
@@ -603,48 +718,22 @@
         mCallbackProxy = new CallbackProxy(context, this);
         mWebViewCore = new WebViewCore(context, this, mCallbackProxy);
         mDatabase = WebViewDatabase.getInstance(context);
-        mFocusData = new WebViewCore.FocusData();
-        mFocusData.mFrame = 0;
-        mFocusData.mNode = 0;
-        mFocusData.mX = 0;
-        mFocusData.mY = 0;
         mScroller = new Scroller(context);
 
-        initZoomController(context);
-    }
+        mViewManager = new ViewManager(this);
 
-    private void initZoomController(Context context) {
-        // Create the buttons controller
         mZoomButtonsController = new ZoomButtonsController(this);
         mZoomButtonsController.setOnZoomListener(mZoomListener);
-
-        // Create the accessory buttons
-        LayoutInflater inflater =
-                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-        ViewGroup container = mZoomButtonsController.getContainer();
-        inflater.inflate(com.android.internal.R.layout.zoom_browser_accessory_buttons, container);
-        mZoomOverviewButton =
-                (ImageView) container.findViewById(com.android.internal.R.id.zoom_page_overview);
-        mZoomOverviewButton.setOnClickListener(
-            new View.OnClickListener() {
-                public void onClick(View v) {
-                    mZoomButtonsController.setVisible(false);
-                    zoomScrollOut();
-                    if (mLogEvent) {
-                        Checkin.updateStats(mContext.getContentResolver(),
-                                Checkin.Stats.Tag.BROWSER_ZOOM_OVERVIEW, 1, 0.0);
-                    }
-                }
-            });
-        mZoomFitPageButton =
-                (ImageView) container.findViewById(com.android.internal.R.id.zoom_fit_page);
-        mZoomFitPageButton.setOnClickListener(
-            new View.OnClickListener() {
-                public void onClick(View v) {
-                    zoomWithPreview(mDefaultScale);
-                    updateZoomButtonsEnabled();
-                }
-            });
+        // ZoomButtonsController positions the buttons at the bottom, but in
+        // the middle.  Change their layout parameters so they appear on the
+        // right.
+        View controls = mZoomButtonsController.getZoomControls();
+        ViewGroup.LayoutParams params = controls.getLayoutParams();
+        if (params instanceof FrameLayout.LayoutParams) {
+            FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams)
+                    params;
+            frameParams.gravity = Gravity.RIGHT;
+        }
     }
 
     private void updateZoomButtonsEnabled() {
@@ -654,20 +743,15 @@
             // Hide the zoom in and out buttons, as well as the fit to page
             // button, if the page cannot zoom
             mZoomButtonsController.getZoomControls().setVisibility(View.GONE);
-            mZoomFitPageButton.setVisibility(View.GONE);
         } else {
             // Bring back the hidden zoom controls.
             mZoomButtonsController.getZoomControls()
                     .setVisibility(View.VISIBLE);
-            mZoomFitPageButton.setVisibility(View.VISIBLE);
             // Set each one individually, as a page may be able to zoom in
             // or out.
             mZoomButtonsController.setZoomInEnabled(canZoomIn);
             mZoomButtonsController.setZoomOutEnabled(canZoomOut);
-            mZoomFitPageButton.setEnabled(mActualScale != mDefaultScale);
         }
-        mZoomOverviewButton.setVisibility(canZoomScrollOut() ? View.VISIBLE:
-                View.GONE);
     }
 
     private void init() {
@@ -902,7 +986,7 @@
         clearTextEntry();
         if (mWebViewCore != null) {
             // Set the handlers to null before destroying WebViewCore so no
-            // more messages will be posted. 
+            // more messages will be posted.
             mCallbackProxy.setWebViewClient(null);
             mCallbackProxy.setWebChromeClient(null);
             // Tell WebViewCore to destroy itself
@@ -933,12 +1017,23 @@
 
     /**
      * If platform notifications are enabled, this should be called
-     * from onPause() or onStop().
+     * from the Activity's onPause() or onStop().
      */
     public static void disablePlatformNotifications() {
         Network.disablePlatformNotifications();
     }
-    
+
+    /**
+     * Sets JavaScript engine flags.
+     *
+     * @param flags JS engine flags in a String
+     *
+     * @hide pending API solidification
+     */
+    public void setJsFlags(String flags) {
+        mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags);
+    }
+
     /**
      * Inform WebView of the network state. This is used to set
      * the javascript property window.navigator.isOnline and
@@ -951,7 +1046,7 @@
     }
 
     /**
-     * Save the state of this WebView used in 
+     * Save the state of this WebView used in
      * {@link android.app.Activity#onSaveInstanceState}. Please note that this
      * method no longer stores the display data for this WebView. The previous
      * behavior could potentially leak files if {@link #restoreState} was never
@@ -1082,10 +1177,10 @@
 
     /**
      * Restore the state of this WebView from the given map used in
-     * {@link android.app.Activity#onRestoreInstanceState}. This method should 
-     * be called to restore the state of the WebView before using the object. If 
-     * it is called after the WebView has had a chance to build state (load 
-     * pages, create a back/forward list, etc.) there may be undesirable 
+     * {@link android.app.Activity#onRestoreInstanceState}. This method should
+     * be called to restore the state of the WebView before using the object. If
+     * it is called after the WebView has had a chance to build state (load
+     * pages, create a back/forward list, etc.) there may be undesirable
      * side-effects. Please note that this method no longer restores the
      * display data for this WebView. See {@link #savePicture} and {@link
      * #restorePicture} for saving and restoring the display data.
@@ -1146,6 +1241,9 @@
      * @param url The url of the resource to load.
      */
     public void loadUrl(String url) {
+        if (url == null) {
+            return;
+        }
         switchOutDrawHistory();
         mWebViewCore.sendMessage(EventHub.LOAD_URL, url);
         clearTextEntry();
@@ -1155,18 +1253,18 @@
      * Load the url with postData using "POST" method into the WebView. If url
      * is not a network url, it will be loaded with {link
      * {@link #loadUrl(String)} instead.
-     * 
+     *
      * @param url The url of the resource to load.
      * @param postData The data will be passed to "POST" request.
-     * 
+     *
      * @hide pending API solidification
      */
     public void postUrl(String url, byte[] postData) {
         if (URLUtil.isNetworkUrl(url)) {
             switchOutDrawHistory();
-            HashMap arg = new HashMap();
-            arg.put("url", url);
-            arg.put("data", postData);
+            WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData();
+            arg.mUrl = url;
+            arg.mPostData = postData;
             mWebViewCore.sendMessage(EventHub.POST_URL, arg);
             clearTextEntry();
         } else {
@@ -1200,7 +1298,7 @@
      * able to access asset files. If the baseUrl is anything other than
      * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for
      * sub resources.
-     * 
+     *
      * @param baseUrl Url to resolve relative paths with, if null defaults to
      *            "about:blank"
      * @param data A String of data in the given encoding.
@@ -1211,18 +1309,18 @@
      */
     public void loadDataWithBaseURL(String baseUrl, String data,
             String mimeType, String encoding, String failUrl) {
-        
+
         if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
             loadData(data, mimeType, encoding);
             return;
         }
         switchOutDrawHistory();
-        HashMap arg = new HashMap();
-        arg.put("baseUrl", baseUrl);
-        arg.put("data", data);
-        arg.put("mimeType", mimeType);
-        arg.put("encoding", encoding);
-        arg.put("failUrl", failUrl);
+        WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
+        arg.mBaseUrl = baseUrl;
+        arg.mData = data;
+        arg.mMimeType = mimeType;
+        arg.mEncoding = encoding;
+        arg.mFailUrl = failUrl;
         mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
         clearTextEntry();
     }
@@ -1332,7 +1430,7 @@
                     ignoreSnapshot ? 1 : 0);
         }
     }
-    
+
     private boolean extendScroll(int y) {
         int finalY = mScroller.getFinalY();
         int newY = pinLocY(finalY + y);
@@ -1341,7 +1439,7 @@
         mScroller.extendDuration(computeDuration(0, y));
         return true;
     }
-    
+
     /**
      * Scroll the contents of the view up by half the view size
      * @param top true to jump to the top of the page
@@ -1351,7 +1449,7 @@
         if (mNativeClass == 0) {
             return false;
         }
-        nativeClearFocus(-1, -1);
+        nativeClearCursor(); // start next trackball movement from page edge
         if (top) {
             // go to the top of the document
             return pinScrollTo(mScrollX, 0, true, 0);
@@ -1365,10 +1463,10 @@
             y = -h / 2;
         }
         mUserScroll = true;
-        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 
+        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
                 : extendScroll(y);
     }
-    
+
     /**
      * Scroll the contents of the view down by half the page size
      * @param bottom true to jump to bottom of page
@@ -1378,7 +1476,7 @@
         if (mNativeClass == 0) {
             return false;
         }
-        nativeClearFocus(-1, -1);
+        nativeClearCursor(); // start next trackball movement from page edge
         if (bottom) {
             return pinScrollTo(mScrollX, mContentHeight, true, 0);
         }
@@ -1391,7 +1489,7 @@
             y = h / 2;
         }
         mUserScroll = true;
-        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 
+        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
                 : extendScroll(y);
     }
 
@@ -1404,7 +1502,7 @@
         mContentHeight = 0;
         mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
     }
-    
+
     /**
      * Return a new picture that captures the current display of the webview.
      * This is a copy of the display, and will be unaffected if the webview
@@ -1415,7 +1513,7 @@
      *         bounds of the view.
      */
     public Picture capturePicture() {
-        if (null == mWebViewCore) return null; // check for out of memory tab 
+        if (null == mWebViewCore) return null; // check for out of memory tab
         return mWebViewCore.copyContentPicture();
     }
 
@@ -1423,17 +1521,17 @@
      *  Return true if the browser is displaying a TextView for text input.
      */
     private boolean inEditingMode() {
-        return mTextEntry != null && mTextEntry.getParent() != null
-                && mTextEntry.hasFocus();
+        return mWebTextView != null && mWebTextView.getParent() != null
+                && mWebTextView.hasFocus();
     }
 
     private void clearTextEntry() {
         if (inEditingMode()) {
-            mTextEntry.remove();
+            mWebTextView.remove();
         }
     }
 
-    /** 
+    /**
      * Return the current scale of the WebView
      * @return The current scale.
      */
@@ -1474,7 +1572,7 @@
     }
 
     /**
-     * Return a HitTestResult based on the current focus node. If a HTML::a tag
+     * Return a HitTestResult based on the current cursor node. If a HTML::a tag
      * is found and the anchor has a non-javascript url, the HitTestResult type
      * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the
      * anchor does not have a url or if it is a javascript url, the type will
@@ -1497,26 +1595,26 @@
         }
 
         HitTestResult result = new HitTestResult();
-
-        if (nativeUpdateFocusNode()) {
-            FocusNode node = mFocusNode;
-            if (node.mIsTextField || node.mIsTextArea) {
+        if (nativeHasCursorNode()) {
+            if (nativeCursorIsTextInput()) {
                 result.setType(HitTestResult.EDIT_TEXT_TYPE);
-            } else if (node.mText != null) {
-                String text = node.mText;
-                if (text.startsWith(SCHEME_TEL)) {
-                    result.setType(HitTestResult.PHONE_TYPE);
-                    result.setExtra(text.substring(SCHEME_TEL.length()));
-                } else if (text.startsWith(SCHEME_MAILTO)) {
-                    result.setType(HitTestResult.EMAIL_TYPE);
-                    result.setExtra(text.substring(SCHEME_MAILTO.length()));
-                } else if (text.startsWith(SCHEME_GEO)) {
-                    result.setType(HitTestResult.GEO_TYPE);
-                    result.setExtra(URLDecoder.decode(text
-                            .substring(SCHEME_GEO.length())));
-                } else if (node.mIsAnchor) {
-                    result.setType(HitTestResult.SRC_ANCHOR_TYPE);
-                    result.setExtra(text);
+            } else {
+                String text = nativeCursorText();
+                if (text != null) {
+                    if (text.startsWith(SCHEME_TEL)) {
+                        result.setType(HitTestResult.PHONE_TYPE);
+                        result.setExtra(text.substring(SCHEME_TEL.length()));
+                    } else if (text.startsWith(SCHEME_MAILTO)) {
+                        result.setType(HitTestResult.EMAIL_TYPE);
+                        result.setExtra(text.substring(SCHEME_MAILTO.length()));
+                    } else if (text.startsWith(SCHEME_GEO)) {
+                        result.setType(HitTestResult.GEO_TYPE);
+                        result.setExtra(URLDecoder.decode(text
+                                .substring(SCHEME_GEO.length())));
+                    } else if (nativeCursorIsAnchor()) {
+                        result.setType(HitTestResult.SRC_ANCHOR_TYPE);
+                        result.setExtra(text);
+                    }
                 }
             }
         }
@@ -1528,8 +1626,8 @@
             int contentY = viewToContent((int) mLastTouchY + mScrollY);
             String text = nativeImageURI(contentX, contentY);
             if (text != null) {
-                result.setType(type == HitTestResult.UNKNOWN_TYPE ? 
-                        HitTestResult.IMAGE_TYPE : 
+                result.setType(type == HitTestResult.UNKNOWN_TYPE ?
+                        HitTestResult.IMAGE_TYPE :
                         HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
                 result.setExtra(text);
             }
@@ -1541,31 +1639,29 @@
      * Request the href of an anchor element due to getFocusNodePath returning
      * "href." If hrefMsg is null, this method returns immediately and does not
      * dispatch hrefMsg to its target.
-     * 
+     *
      * @param hrefMsg This message will be dispatched with the result of the
      *            request as the data member with "url" as key. The result can
      *            be null.
      */
+    // FIXME: API change required to change the name of this function.  We now
+    // look at the cursor node, and not the focus node.  Also, what is
+    // getFocusNodePath?
     public void requestFocusNodeHref(Message hrefMsg) {
         if (hrefMsg == null || mNativeClass == 0) {
             return;
         }
-        if (nativeUpdateFocusNode()) {
-            FocusNode node = mFocusNode;
-            if (node.mIsAnchor) {
-                // NOTE: We may already have the url of the anchor stored in
-                // node.mText but it may be out of date or the caller may want
-                // to know about javascript urls.
-                mWebViewCore.sendMessage(EventHub.REQUEST_FOCUS_HREF,
-                        node.mFramePointer, node.mNodePointer, hrefMsg);
-            }
+        if (nativeCursorIsAnchor()) {
+            mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
+                    nativeCursorFramePointer(), nativeCursorNodePointer(),
+                    hrefMsg);
         }
     }
-    
+
     /**
      * Request the url of the image last touched by the user. msg will be sent
      * to its target with a String representing the url as its object.
-     * 
+     *
      * @param msg This message will be dispatched with the result of the request
      *            as the data member with "url" as key. The result can be null.
      */
@@ -1609,7 +1705,7 @@
         return Math.round(x * mInvActualScale);
     }
 
-    private int contentToView(int x) {
+    /*package*/ int contentToView(int x) {
         return Math.round(x * mActualScale);
     }
 
@@ -1640,7 +1736,7 @@
         if ((w | h) == 0) {
             return;
         }
-        
+
         // don't abort a scroll animation if we didn't change anything
         if (mContentWidth != w || mContentHeight != h) {
             // record new dimensions
@@ -1700,7 +1796,10 @@
                 mActualScale = scale;
                 mInvActualScale = 1 / scale;
 
-                // as we don't have animation for scaling, don't do animation 
+                // Scale all the child views
+                mViewManager.scaleAll();
+
+                // as we don't have animation for scaling, don't do animation
                 // for scrolling, as it causes weird intermediate state
                 //        pinScrollTo(Math.round(sx), Math.round(sy));
                 mScrollX = pinLocX(Math.round(sx));
@@ -1721,18 +1820,21 @@
     private Rect sendOurVisibleRect() {
         Rect rect = new Rect();
         calcOurContentVisibleRect(rect);
-        if (mFindIsUp) {
-            rect.bottom -= viewToContent(FIND_HEIGHT);
-        }
         // Rect.equals() checks for null input.
         if (!rect.equals(mLastVisibleRectSent)) {
+            Point pos = new Point(rect.left, rect.top);
             mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
-                                     rect.left, rect.top);
+                    nativeMoveGeneration(), 0, pos);
             mLastVisibleRectSent = rect;
         }
         Rect globalRect = new Rect();
         if (getGlobalVisibleRect(globalRect)
                 && !globalRect.equals(mLastGlobalRect)) {
+            if (DebugFlags.WEB_VIEW) {
+                Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
+                        + globalRect.top + ",r=" + globalRect.right + ",b="
+                        + globalRect.bottom);
+            }
             // TODO: the global offset is only used by windowRect()
             // in ChromeClientAndroid ; other clients such as touch
             // and mouse events could return view + screen relative points.
@@ -1747,6 +1849,9 @@
         Point p = new Point();
         getGlobalVisibleRect(r, p);
         r.offset(-p.x, -p.y);
+        if (mFindIsUp) {
+            r.bottom -= FIND_HEIGHT;
+        }
     }
 
     // Sets r to be our visible rectangle in content coordinates
@@ -1824,10 +1929,10 @@
         WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
         return h != null ? h.getUrl() : null;
     }
-    
+
     /**
-     * Get the original url for the current page. This is not always the same 
-     * as the url passed to WebViewClient.onPageStarted because although the 
+     * Get the original url for the current page. This is not always the same
+     * as the url passed to WebViewClient.onPageStarted because although the
      * load for that url has begun, the current page may not have changed.
      * Also, there may have been redirects resulting in a different url to that
      * originally requested.
@@ -1865,7 +1970,7 @@
     public int getProgress() {
         return mCallbackProxy.getProgress();
     }
-    
+
     /**
      * @return the height of the HTML content.
      */
@@ -1874,30 +1979,77 @@
     }
 
     /**
-     * Pause all layout, parsing, and javascript timers. This can be useful if
-     * the WebView is not visible or the application has been paused.
+     * Pause all layout, parsing, and javascript timers for all webviews. This
+     * is a global requests, not restricted to just this webview. This can be
+     * useful if the application has been paused.
      */
     public void pauseTimers() {
         mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
     }
 
     /**
-     * Resume all layout, parsing, and javascript timers. This will resume
-     * dispatching all timers.
+     * Resume all layout, parsing, and javascript timers for all webviews.
+     * This will resume dispatching all timers.
      */
     public void resumeTimers() {
         mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
     }
 
     /**
-     * Clear the resource cache. This will cause resources to be re-downloaded
-     * if accessed again.
-     * <p>
-     * Note: this really needs to be a static method as it clears cache for all
-     * WebView. But we need mWebViewCore to send message to WebCore thread, so
-     * we can't make this static.
+     * Call this to pause any extra processing associated with this view and
+     * its associated DOM/plugins/javascript/etc. For example, if the view is
+     * taken offscreen, this could be called to reduce unnecessary CPU and/or
+     * network traffic. When the view is again "active", call onResume().
+     *
+     * Note that this differs from pauseTimers(), which affects all views/DOMs
+     * @hide
+     */
+    public void onPause() {
+        if (!mIsPaused) {
+            mIsPaused = true;
+            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
+        }
+    }
+
+    /**
+     * Call this to balanace a previous call to onPause()
+     * @hide
+     */
+    public void onResume() {
+        if (mIsPaused) {
+            mIsPaused = false;
+            mWebViewCore.sendMessage(EventHub.ON_RESUME);
+        }
+    }
+
+    /**
+     * Returns true if the view is paused, meaning onPause() was called. Calling
+     * onResume() sets the paused state back to false.
+     * @hide
+     */
+    public boolean isPaused() {
+        return mIsPaused;
+    }
+
+    /**
+     * Call this to inform the view that memory is low so that it can
+     * free any available memory.
+     * @hide
+     */
+    public void freeMemory() {
+        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
+    }
+
+    /**
+     * Clear the resource cache. Note that the cache is per-application, so
+     * this will clear the cache for all WebViews used.
+     *
+     * @param includeDiskFiles If false, only the RAM cache is cleared.
      */
     public void clearCache(boolean includeDiskFiles) {
+        // Note: this really needs to be a static method as it clears cache for all
+        // WebView. But we need mWebViewCore to send message to WebCore thread, so
+        // we can't make this static.
         mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
                 includeDiskFiles ? 1 : 0, 0);
     }
@@ -1909,7 +2061,7 @@
     public void clearFormData() {
         if (inEditingMode()) {
             AutoCompleteAdapter adapter = null;
-            mTextEntry.setAdapterCustom(adapter);
+            mWebTextView.setAdapterCustom(adapter);
         }
     }
 
@@ -1943,7 +2095,7 @@
 
     /*
      * Highlight and scroll to the next occurance of String in findAll.
-     * Wraps the page infinitely, and scrolls.  Must be called after 
+     * Wraps the page infinitely, and scrolls.  Must be called after
      * calling findAll.
      *
      * @param forward Direction to search.
@@ -1969,11 +2121,8 @@
     // or not we draw the highlights for matches.
     private boolean mFindIsUp;
 
-    private native int nativeFindAll(String findLower, String findUpper);
-    private native void nativeFindNext(boolean forward);
-    
     /**
-     * Return the first substring consisting of the address of a physical 
+     * Return the first substring consisting of the address of a physical
      * location. Currently, only addresses in the United States are detected,
      * and consist of:
      * - a house number
@@ -1986,14 +2135,40 @@
      * All names must be correctly capitalized, and the zip code, if present,
      * must be valid for the state. The street type must be a standard USPS
      * spelling or abbreviation. The state or territory must also be spelled
-     * or abbreviated using USPS standards. The house number may not exceed 
+     * or abbreviated using USPS standards. The house number may not exceed
      * five digits.
      * @param addr The string to search for addresses.
      *
      * @return the address, or if no address is found, return null.
      */
     public static String findAddress(String addr) {
-        return WebViewCore.nativeFindAddress(addr);
+        return findAddress(addr, false);
+    }
+
+    /**
+     * @hide
+     * Return the first substring consisting of the address of a physical
+     * location. Currently, only addresses in the United States are detected,
+     * and consist of:
+     * - a house number
+     * - a street name
+     * - a street type (Road, Circle, etc), either spelled out or abbreviated
+     * - a city name
+     * - a state or territory, either spelled out or two-letter abbr.
+     * - an optional 5 digit or 9 digit zip code.
+     *
+     * Names are optionally capitalized, and the zip code, if present,
+     * must be valid for the state. The street type must be a standard USPS
+     * spelling or abbreviation. The state or territory must also be spelled
+     * or abbreviated using USPS standards. The house number may not exceed
+     * five digits.
+     * @param addr The string to search for addresses.
+     * @param caseInsensitive addr Set to true to make search ignore case.
+     *
+     * @return the address, or if no address is found, return null.
+     */
+    public static String findAddress(String addr, boolean caseInsensitive) {
+        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
     }
 
     /*
@@ -2204,6 +2379,16 @@
     }
 
     /**
+     * Gets the chrome handler.
+     * @return the current WebChromeClient instance.
+     *
+     * @hide API council approval.
+     */
+    public WebChromeClient getWebChromeClient() {
+        return mCallbackProxy.getWebChromeClient();
+    }
+
+    /**
      * Set the Picture listener. This is an interface used to receive
      * notifications of a new Picture.
      * @param listener An implementation of WebView.PictureListener.
@@ -2248,10 +2433,9 @@
      * @param interfaceName The name to used to expose the class in Javascript
      */
     public void addJavascriptInterface(Object obj, String interfaceName) {
-        // Use Hashmap rather than Bundle as Bundles can't cope with Objects
-        HashMap arg = new HashMap();
-        arg.put("object", obj);
-        arg.put("interfaceName", interfaceName);
+        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
+        arg.mObject = obj;
+        arg.mInterfaceName = interfaceName;
         mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
     }
 
@@ -2277,16 +2461,10 @@
     }
 
    /**
-    * Signal the WebCore thread to refresh its list of plugins. Use
-    * this if the directory contents of one of the plugin directories
-    * has been modified and needs its changes reflecting. May cause
-    * plugin load and/or unload.
-    * @param reloadOpenPages Set to true to reload all open pages.
+     * TODO: need to add @Deprecated
     */
     public void refreshPlugins(boolean reloadOpenPages) {
-        if (mWebViewCore != null) {
-            mWebViewCore.sendMessage(EventHub.REFRESH_PLUGINS, reloadOpenPages);
-        }
+        PluginManager.getInstance(mContext).refreshPlugins(reloadOpenPages);
     }
 
     //-------------------------------------------------------------------------
@@ -2297,7 +2475,7 @@
     protected void finalize() throws Throwable {
         destroy();
     }
-    
+
     @Override
     protected void onDraw(Canvas canvas) {
         // if mNativeClass is 0, the WebView has been destroyed. Do nothing.
@@ -2306,7 +2484,7 @@
         }
         if (mWebViewCore.mEndScaleZoom) {
             mWebViewCore.mEndScaleZoom = false;
-            if (mTouchMode >= FIRST_SCROLL_ZOOM 
+            if (mTouchMode >= FIRST_SCROLL_ZOOM
                     && mTouchMode <= LAST_SCROLL_ZOOM) {
                 setHorizontalScrollBarEnabled(true);
                 setVerticalScrollBarEnabled(true);
@@ -2317,22 +2495,21 @@
         if (mTouchMode >= FIRST_SCROLL_ZOOM && mTouchMode <= LAST_SCROLL_ZOOM) {
             scrollZoomDraw(canvas);
         } else {
-            nativeRecomputeFocus();
             // Update the buttons in the picture, so when we draw the picture
             // to the screen, they are in the correct state.
             // Tell the native side if user is a) touching the screen,
             // b) pressing the trackball down, or c) pressing the enter key
-            // If the focus is a button, we need to draw it in the pressed
+            // If the cursor is on a button, we need to draw it in the pressed
             // state.
             // If mNativeClass is 0, we should not reach here, so we do not
             // need to check it again.
             nativeRecordButtons(hasFocus() && hasWindowFocus(),
                     mTouchMode == TOUCH_SHORTPRESS_START_MODE
-                    || mTrackballDown || mGotEnterDown, false);
-            drawCoreAndFocusRing(canvas, mBackgroundColor, mDrawFocusRing);
+                    || mTrackballDown || mGotCenterDown, false);
+            drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing);
         }
         canvas.restoreToCount(sc);
-        
+
         if (AUTO_REDRAW_HACK && mAutoRedraw) {
             invalidate();
         }
@@ -2348,15 +2525,23 @@
 
     @Override
     public boolean performLongClick() {
+        if (mNativeClass != 0 && nativeCursorIsTextInput()) {
+            // Send the click so that the textfield is in focus
+            // FIXME: When we start respecting changes to the native textfield's
+            // selection, need to make sure that this does not change it.
+            mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
+                    nativeCursorNodePointer());
+            rebuildWebTextView();
+        }
         if (inEditingMode()) {
-            return mTextEntry.performLongClick();
+            return mWebTextView.performLongClick();
         } else {
             return super.performLongClick();
         }
     }
 
-    private void drawCoreAndFocusRing(Canvas canvas, int color,
-        boolean drawFocus) {
+    private void drawCoreAndCursorRing(Canvas canvas, int color,
+        boolean drawCursorRing) {
         if (mDrawHistory) {
             canvas.scale(mActualScale, mActualScale);
             canvas.drawPicture(mHistoryPicture);
@@ -2364,14 +2549,14 @@
         }
 
         boolean animateZoom = mZoomScale != 0;
-        boolean animateScroll = !mScroller.isFinished() 
+        boolean animateScroll = !mScroller.isFinished()
                 || mVelocityTracker != null;
         if (animateZoom) {
             float zoomScale;
             int interval = (int) (SystemClock.uptimeMillis() - mZoomStart);
             if (interval < ZOOM_ANIMATION_LENGTH) {
                 float ratio = (float) interval / ZOOM_ANIMATION_LENGTH;
-                zoomScale = 1.0f / (mInvInitialZoomScale 
+                zoomScale = 1.0f / (mInvInitialZoomScale
                         + (mInvFinalZoomScale - mInvInitialZoomScale) * ratio);
                 invalidate();
             } else {
@@ -2379,24 +2564,15 @@
                 // set mZoomScale to be 0 as we have done animation
                 mZoomScale = 0;
             }
-            float scale = (mActualScale - zoomScale) * mInvActualScale;
-            float tx = scale * (mZoomCenterX + mScrollX);
-            float ty = scale * (mZoomCenterY + mScrollY);
-
-            // this block pins the translate to "legal" bounds. This makes the
-            // animation a bit non-obvious, but it means we won't pop when the
-            // "real" zoom takes effect
-            if (true) {
-               // canvas.translate(mScrollX, mScrollY);
-                tx -= mScrollX;
-                ty -= mScrollY;
-                tx = -pinLoc(-Math.round(tx), getViewWidth(), Math
-                        .round(mContentWidth * zoomScale));
-                ty = -pinLoc(-Math.round(ty), getViewHeight(), Math
-                        .round(mContentHeight * zoomScale));
-                tx += mScrollX;
-                ty += mScrollY;
-            }
+            float scale = zoomScale * mInvInitialZoomScale;
+            int tx = Math.round(scale * (mInitialScrollX + mZoomCenterX)
+                    - mZoomCenterX);
+            tx = -pinLoc(tx, getViewWidth(), Math.round(mContentWidth
+                    * zoomScale)) + mScrollX;
+            int ty = Math.round(scale * (mInitialScrollY + mZoomCenterY)
+                    - mZoomCenterY);
+            ty = -pinLoc(ty, getViewHeight(), Math.round(mContentHeight
+                    * zoomScale)) + mScrollY;
             canvas.translate(tx, ty);
             canvas.scale(zoomScale, zoomScale);
         } else {
@@ -2411,10 +2587,10 @@
             if (mTouchSelection) {
                 nativeDrawSelectionRegion(canvas);
             } else {
-                nativeDrawSelection(canvas, mSelectX, mSelectY, 
+                nativeDrawSelection(canvas, mSelectX, mSelectY,
                         mExtendSelection);
             }
-        } else if (drawFocus) {
+        } else if (drawCursorRing) {
             if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
                 mTouchMode = TOUCH_SHORTPRESS_MODE;
                 HitTestResult hitTest = getHitTestResult();
@@ -2425,7 +2601,7 @@
                             LONG_PRESS_TIMEOUT);
                 }
             }
-            nativeDrawFocusRing(canvas);
+            nativeDrawCursorRing(canvas);
         }
         // When the FindDialog is up, only draw the matches if we are not in
         // the process of scrolling them into view.
@@ -2434,14 +2610,12 @@
         }
     }
 
-    private native void nativeDrawMatches(Canvas canvas);
-    
     private float scrollZoomGridScale(float invScale) {
-        float griddedInvScale = (int) (invScale * SCROLL_ZOOM_GRID) 
+        float griddedInvScale = (int) (invScale * SCROLL_ZOOM_GRID)
             / (float) SCROLL_ZOOM_GRID;
         return 1.0f / griddedInvScale;
     }
-    
+
     private float scrollZoomX(float scale) {
         int width = getViewWidth();
         float maxScrollZoomX = mContentWidth * scale - width;
@@ -2457,7 +2631,7 @@
         return -(maxScrollZoomY > 0 ? mZoomScrollY * maxScrollZoomY / maxY
                 : maxScrollZoomY / 2);
     }
-    
+
     private void drawMagnifyFrame(Canvas canvas, Rect frame, Paint paint) {
         final float ADORNMENT_LEN = 16.0f;
         float width = frame.width();
@@ -2478,13 +2652,13 @@
         path.offset(frame.left, frame.top);
         canvas.drawPath(path, paint);
     }
-    
-    // Returns frame surrounding magified portion of screen while 
+
+    // Returns frame surrounding magified portion of screen while
     // scroll-zoom is enabled. The frame is also used to center the
     // zoom-in zoom-out points at the start and end of the animation.
     private Rect scrollZoomFrame(int width, int height, float halfScale) {
         Rect scrollFrame = new Rect();
-        scrollFrame.set(mZoomScrollX, mZoomScrollY, 
+        scrollFrame.set(mZoomScrollX, mZoomScrollY,
                 mZoomScrollX + width, mZoomScrollY + height);
         if (mContentWidth * mZoomScrollLimit < width) {
             float scale = zoomFrameScaleX(width, halfScale, 1.0f);
@@ -2500,37 +2674,37 @@
         }
         return scrollFrame;
     }
-    
+
     private float zoomFrameScaleX(int width, float halfScale, float noScale) {
         // mContentWidth > width > mContentWidth * mZoomScrollLimit
         if (mContentWidth <= width) {
             return halfScale;
         }
-        float part = (width - mContentWidth * mZoomScrollLimit)  
+        float part = (width - mContentWidth * mZoomScrollLimit)
                 / (width * (1 - mZoomScrollLimit));
         return halfScale * part + noScale * (1.0f - part);
     }
-    
+
     private float zoomFrameScaleY(int height, float halfScale, float noScale) {
         if (mContentHeight <= height) {
             return halfScale;
         }
-        float part = (height - mContentHeight * mZoomScrollLimit)  
+        float part = (height - mContentHeight * mZoomScrollLimit)
                 / (height * (1 - mZoomScrollLimit));
         return halfScale * part + noScale * (1.0f - part);
     }
-    
+
     private float scrollZoomMagScale(float invScale) {
         return (invScale * 2 + mInvActualScale) / 3;
     }
-    
+
     private void scrollZoomDraw(Canvas canvas) {
-        float invScale = mZoomScrollInvLimit; 
+        float invScale = mZoomScrollInvLimit;
         int elapsed = 0;
         if (mTouchMode != SCROLL_ZOOM_OUT) {
-            elapsed = (int) Math.min(System.currentTimeMillis() 
+            elapsed = (int) Math.min(System.currentTimeMillis()
                 - mZoomScrollStart, SCROLL_ZOOM_DURATION);
-            float transitionScale = (mZoomScrollInvLimit - mInvActualScale) 
+            float transitionScale = (mZoomScrollInvLimit - mInvActualScale)
                     * elapsed / SCROLL_ZOOM_DURATION;
             if (mTouchMode == SCROLL_ZOOM_ANIMATION_OUT) {
                 invScale = mInvActualScale + transitionScale;
@@ -2548,21 +2722,23 @@
             if (mTouchMode == SCROLL_ZOOM_ANIMATION_IN) {
                 setHorizontalScrollBarEnabled(true);
                 setVerticalScrollBarEnabled(true);
-                updateTextEntry();
-                scrollTo((int) (scrollFrame.centerX() * mActualScale) 
-                        - (width >> 1), (int) (scrollFrame.centerY() 
+                rebuildWebTextView();
+                scrollTo((int) (scrollFrame.centerX() * mActualScale)
+                        - (width >> 1), (int) (scrollFrame.centerY()
                         * mActualScale) - (height >> 1));
                 mTouchMode = TOUCH_DONE_MODE;
+                // Show all the child views once we are done.
+                mViewManager.showAll();
             } else {
                 mTouchMode = SCROLL_ZOOM_OUT;
             }
         }
         float newX = scrollZoomX(scale);
         float newY = scrollZoomY(scale);
-        if (LOGV_ENABLED) {
+        if (DebugFlags.WEB_VIEW) {
             Log.v(LOGTAG, "scrollZoomDraw scale=" + scale + " + (" + newX
                     + ", " + newY + ") mZoomScroll=(" + mZoomScrollX + ", "
-                    + mZoomScrollY + ")" + " invScale=" + invScale + " scale=" 
+                    + mZoomScrollY + ")" + " invScale=" + invScale + " scale="
                     + scale);
         }
         canvas.translate(newX, newY);
@@ -2606,8 +2782,8 @@
         }
         canvas.scale(halfScale, halfScale, mZoomScrollX + width * halfX
                 , mZoomScrollY + height * halfY);
-        if (LOGV_ENABLED) {
-            Log.v(LOGTAG, "scrollZoomDraw halfScale=" + halfScale + " w/h=(" 
+        if (DebugFlags.WEB_VIEW) {
+            Log.v(LOGTAG, "scrollZoomDraw halfScale=" + halfScale + " w/h=("
                     + width + ", " + height + ") half=(" + halfX + ", "
                     + halfY + ")");
         }
@@ -2635,14 +2811,17 @@
                 , Math.max(0, (int) ((x - left) / scale)));
         mZoomScrollY = Math.min(mContentHeight - height
                 , Math.max(0, (int) ((y - top) / scale)));
-        if (LOGV_ENABLED) {
+        if (DebugFlags.WEB_VIEW) {
             Log.v(LOGTAG, "zoomScrollTap scale=" + scale + " + (" + left
                     + ", " + top + ") mZoomScroll=(" + mZoomScrollX + ", "
                     + mZoomScrollY + ")" + " x=" + x + " y=" + y);
         }
     }
 
-    private boolean canZoomScrollOut() {
+    /**
+     * @hide
+     */
+    public boolean canZoomScrollOut() {
         if (mContentWidth == 0 || mContentHeight == 0) {
             return false;
         }
@@ -2652,7 +2831,7 @@
         float y = (float) height / (float) mContentHeight;
         mZoomScrollLimit = Math.max(DEFAULT_MIN_ZOOM_SCALE, Math.min(x, y));
         mZoomScrollInvLimit = 1.0f / mZoomScrollLimit;
-        if (LOGV_ENABLED) {
+        if (DebugFlags.WEB_VIEW) {
             Log.v(LOGTAG, "canZoomScrollOut"
                     + " mInvActualScale=" + mInvActualScale
                     + " mZoomScrollLimit=" + mZoomScrollLimit
@@ -2667,7 +2846,7 @@
         return mContentWidth >= width * limit
                 || mContentHeight >= height * limit;
     }
-        
+
     private void startZoomScrollOut() {
         setHorizontalScrollBarEnabled(false);
         setVerticalScrollBarEnabled(false);
@@ -2693,30 +2872,35 @@
         mZoomScrollStart = System.currentTimeMillis();
         Rect zoomFrame = scrollZoomFrame(width, height
                 , scrollZoomMagScale(mZoomScrollInvLimit));
-        mZoomScrollX = Math.max(0, (int) ((mScrollX + halfW) * mInvActualScale) 
+        mZoomScrollX = Math.max(0, (int) ((mScrollX + halfW) * mInvActualScale)
                 - (zoomFrame.width() >> 1));
-        mZoomScrollY = Math.max(0, (int) ((mScrollY + halfH) * mInvActualScale) 
+        mZoomScrollY = Math.max(0, (int) ((mScrollY + halfH) * mInvActualScale)
                 - (zoomFrame.height() >> 1));
         scrollTo(0, 0); // triggers inval, starts animation
         clearTextEntry();
-        if (LOGV_ENABLED) {
-            Log.v(LOGTAG, "startZoomScrollOut mZoomScroll=(" 
+        if (DebugFlags.WEB_VIEW) {
+            Log.v(LOGTAG, "startZoomScrollOut mZoomScroll=("
                     + mZoomScrollX + ", " + mZoomScrollY +")");
         }
     }
-    
-    private void zoomScrollOut() {
+
+    /**
+     * @hide
+     */
+    public void zoomScrollOut() {
         if (canZoomScrollOut() == false) {
             mTouchMode = TOUCH_DONE_MODE;
             return;
         }
+        // Hide the child views while in this mode.
+        mViewManager.hideAll();
         startZoomScrollOut();
         mTouchMode = SCROLL_ZOOM_ANIMATION_OUT;
         invalidate();
     }
 
     private void moveZoomScrollWindow(float x, float y) {
-        if (Math.abs(x - mLastZoomScrollRawX) < 1.5f 
+        if (Math.abs(x - mLastZoomScrollRawX) < 1.5f
                 && Math.abs(y - mLastZoomScrollRawY) < 1.5f) {
             return;
         }
@@ -2728,12 +2912,12 @@
         int height = getViewHeight();
         int maxZoomX = mContentWidth - width;
         if (maxZoomX > 0) {
-            int maxScreenX = width - (int) Math.ceil(width 
+            int maxScreenX = width - (int) Math.ceil(width
                     * mZoomScrollLimit) - SCROLL_ZOOM_FINGER_BUFFER;
-            if (LOGV_ENABLED) {
-                Log.v(LOGTAG, "moveZoomScrollWindow-X" 
+            if (DebugFlags.WEB_VIEW) {
+                Log.v(LOGTAG, "moveZoomScrollWindow-X"
                         + " maxScreenX=" + maxScreenX + " width=" + width
-                        + " mZoomScrollLimit=" + mZoomScrollLimit + " x=" + x); 
+                        + " mZoomScrollLimit=" + mZoomScrollLimit + " x=" + x);
             }
             x += maxScreenX * mLastScrollX / maxZoomX - mLastTouchX;
             x *= Math.max(maxZoomX / maxScreenX, mZoomScrollInvLimit);
@@ -2741,12 +2925,12 @@
         }
         int maxZoomY = mContentHeight - height;
         if (maxZoomY > 0) {
-            int maxScreenY = height - (int) Math.ceil(height 
+            int maxScreenY = height - (int) Math.ceil(height
                     * mZoomScrollLimit) - SCROLL_ZOOM_FINGER_BUFFER;
-            if (LOGV_ENABLED) {
-                Log.v(LOGTAG, "moveZoomScrollWindow-Y" 
+            if (DebugFlags.WEB_VIEW) {
+                Log.v(LOGTAG, "moveZoomScrollWindow-Y"
                         + " maxScreenY=" + maxScreenY + " height=" + height
-                        + " mZoomScrollLimit=" + mZoomScrollLimit + " y=" + y); 
+                        + " mZoomScrollLimit=" + mZoomScrollLimit + " y=" + y);
             }
             y += maxScreenY * mLastScrollY / maxZoomY - mLastTouchY;
             y *= Math.max(maxZoomY / maxScreenY, mZoomScrollInvLimit);
@@ -2755,12 +2939,12 @@
         if (oldX != mZoomScrollX || oldY != mZoomScrollY) {
             invalidate();
         }
-        if (LOGV_ENABLED) {
-            Log.v(LOGTAG, "moveZoomScrollWindow" 
-                    + " scrollTo=(" + mZoomScrollX + ", " + mZoomScrollY + ")" 
-                    + " mLastTouch=(" + mLastTouchX + ", " + mLastTouchY + ")" 
-                    + " maxZoom=(" + maxZoomX + ", " + maxZoomY + ")" 
-                    + " last=("+mLastScrollX+", "+mLastScrollY+")" 
+        if (DebugFlags.WEB_VIEW) {
+            Log.v(LOGTAG, "moveZoomScrollWindow"
+                    + " scrollTo=(" + mZoomScrollX + ", " + mZoomScrollY + ")"
+                    + " mLastTouch=(" + mLastTouchX + ", " + mLastTouchY + ")"
+                    + " maxZoom=(" + maxZoomX + ", " + maxZoomY + ")"
+                    + " last=("+mLastScrollX+", "+mLastScrollY+")"
                     + " x=" + x + " y=" + y);
         }
     }
@@ -2805,7 +2989,7 @@
     // Should only be called in UI thread
     void switchOutDrawHistory() {
         if (null == mWebViewCore) return; // CallbackProxy may trigger this
-        if (mDrawHistory) {
+        if (mDrawHistory && mWebViewCore.pictureReady()) {
             mDrawHistory = false;
             invalidate();
             int oldScrollX = mScrollX;
@@ -2821,72 +3005,31 @@
         }
     }
 
-    /**
-     *  Class representing the node which is focused.
-     */
-    private class FocusNode {
-        public FocusNode() {
-            mBounds = new Rect();
-        }
-        // Only to be called by JNI
-        private void setAll(boolean isTextField, boolean isTextArea, boolean 
-                isPassword, boolean isAnchor, boolean isRtlText, int maxLength, 
-                int textSize, int boundsX, int boundsY, int boundsRight, int 
-                boundsBottom, int nodePointer, int framePointer, String text, 
-                String name, int rootTextGeneration) {
-            mIsTextField        = isTextField;
-            mIsTextArea         = isTextArea;
-            mIsPassword         = isPassword;
-            mIsAnchor           = isAnchor;
-            mIsRtlText          = isRtlText;
-
-            mMaxLength          = maxLength;
-            mTextSize           = textSize;
-            
-            mBounds.set(boundsX, boundsY, boundsRight, boundsBottom);
-            
-            
-            mNodePointer        = nodePointer;
-            mFramePointer       = framePointer;
-            mText               = text;
-            mName               = name;
-            mRootTextGeneration = rootTextGeneration;
-        }
-        public boolean  mIsTextField;
-        public boolean  mIsTextArea;
-        public boolean  mIsPassword;
-        public boolean  mIsAnchor;
-        public boolean  mIsRtlText;
-
-        public int      mSelectionStart;
-        public int      mSelectionEnd;
-        public int      mMaxLength;
-        public int      mTextSize;
-        
-        public Rect     mBounds;
-        
-        public int      mNodePointer;
-        public int      mFramePointer;
-        public String   mText;
-        public String   mName;
-        public int      mRootTextGeneration;
+    WebViewCore.CursorData cursorData() {
+        WebViewCore.CursorData result = new WebViewCore.CursorData();
+        result.mMoveGeneration = nativeMoveGeneration();
+        result.mFrame = nativeCursorFramePointer();
+        Point position = nativeCursorPosition();
+        result.mX = position.x;
+        result.mY = position.y;
+        return result;
     }
-    
-    // Warning: ONLY use mFocusNode AFTER calling nativeUpdateFocusNode(),
-    // and ONLY if it returns true;
-    private FocusNode mFocusNode = new FocusNode();
-    
+
     /**
      *  Delete text from start to end in the focused textfield. If there is no
-     *  focus, or if start == end, silently fail.  If start and end are out of 
+     *  focus, or if start == end, silently fail.  If start and end are out of
      *  order, swap them.
      *  @param  start   Beginning of selection to delete.
      *  @param  end     End of selection to delete.
      */
     /* package */ void deleteSelection(int start, int end) {
         mTextGeneration++;
-        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, start, end,
-                new WebViewCore.FocusData(mFocusData));
+        WebViewCore.DeleteSelectionData data
+                = new WebViewCore.DeleteSelectionData();
+        data.mStart = start;
+        data.mEnd = end;
+        data.mTextGeneration = mTextGeneration;
+        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, data);
     }
 
     /**
@@ -2896,119 +3039,133 @@
      *  @param  end     End of selection.
      */
     /* package */ void setSelection(int start, int end) {
-        mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end,
-                new WebViewCore.FocusData(mFocusData));
+        mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
     }
 
     // Called by JNI when a touch event puts a textfield into focus.
-    private void displaySoftKeyboard() {
+    private void displaySoftKeyboard(boolean isTextView) {
         InputMethodManager imm = (InputMethodManager)
                 getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
-        imm.showSoftInput(mTextEntry, 0);
-        mTextEntry.enableScrollOnScreen(true);
-        // Now we need to fake a touch event to place the cursor where the
-        // user touched.
-        AbsoluteLayout.LayoutParams lp = (AbsoluteLayout.LayoutParams)
-                mTextEntry.getLayoutParams();
-        if (lp != null) {
-            // Take the last touch and adjust for the location of the
-            // TextDialog.
-            float x = mLastTouchX + (float) (mScrollX - lp.x);
-            float y = mLastTouchY + (float) (mScrollY - lp.y);
-            mTextEntry.fakeTouchEvent(x, y);
+
+        if (isTextView) {
+            imm.showSoftInput(mWebTextView, 0);
+            // Now we need to fake a touch event to place the cursor where the
+            // user touched.
+            AbsoluteLayout.LayoutParams lp = (AbsoluteLayout.LayoutParams)
+                    mWebTextView.getLayoutParams();
+            if (lp != null) {
+                // Take the last touch and adjust for the location of the
+                // WebTextView.
+                float x = mLastTouchX + (float) (mScrollX - lp.x);
+                float y = mLastTouchY + (float) (mScrollY - lp.y);
+                mWebTextView.fakeTouchEvent(x, y);
+            }
+        }
+        else { // used by plugins
+            imm.showSoftInput(this, 0);
         }
     }
 
-    private void updateTextEntry() {
-        if (mTextEntry == null) {
-            mTextEntry = new TextDialog(mContext, WebView.this);
-            // Initialize our generation number.
-            mTextGeneration = 0;
-        }
-        // If we do not have focus, do nothing until we gain focus.
-        if (!hasFocus() && !mTextEntry.hasFocus()
-                || (mTouchMode >= FIRST_SCROLL_ZOOM 
+    // Called by WebKit to instruct the UI to hide the keyboard
+    private void hideSoftKeyboard() {
+        InputMethodManager imm = (InputMethodManager)
+                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
+
+        imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
+    }
+
+    /*
+     * This method checks the current focus and cursor and potentially rebuilds
+     * mWebTextView to have the appropriate properties, such as password,
+     * multiline, and what text it contains.  It also removes it if necessary.
+     */
+    private void rebuildWebTextView() {
+        // If the WebView does not have focus, do nothing until it gains focus.
+        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())
+                || (mTouchMode >= FIRST_SCROLL_ZOOM
                 && mTouchMode <= LAST_SCROLL_ZOOM)) {
-            mNeedsUpdateTextEntry = true;
             return;
         }
         boolean alreadyThere = inEditingMode();
-        if (0 == mNativeClass || !nativeUpdateFocusNode()) {
+        // inEditingMode can only return true if mWebTextView is non-null,
+        // so we can safely call remove() if (alreadyThere)
+        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
             if (alreadyThere) {
-                mTextEntry.remove();
+                mWebTextView.remove();
             }
             return;
         }
-        FocusNode node = mFocusNode;
-        if (!node.mIsTextField && !node.mIsTextArea) {
-            if (alreadyThere) {
-                mTextEntry.remove();
-            }
-            return;
+        // At this point, we know we have found an input field, so go ahead
+        // and create the WebTextView if necessary.
+        if (mWebTextView == null) {
+            mWebTextView = new WebTextView(mContext, WebView.this);
+            // Initialize our generation number.
+            mTextGeneration = 0;
         }
-        mTextEntry.setTextSize(contentToView(node.mTextSize));
-        Rect visibleRect = sendOurVisibleRect();
+        mWebTextView.setTextSize(contentToView(nativeFocusCandidateTextSize()));
+        Rect visibleRect = new Rect();
+        calcOurContentVisibleRect(visibleRect);
         // Note that sendOurVisibleRect calls viewToContent, so the coordinates
         // should be in content coordinates.
-        if (!Rect.intersects(node.mBounds, visibleRect)) {
-            // Node is not on screen, so do not bother.
-            return;
+        Rect bounds = nativeFocusCandidateNodeBounds();
+        if (!Rect.intersects(bounds, visibleRect)) {
+            mWebTextView.bringIntoView();
         }
-        int x = node.mBounds.left;
-        int y = node.mBounds.top;
-        int width = node.mBounds.width();
-        int height = node.mBounds.height();
-        if (alreadyThere && mTextEntry.isSameTextField(node.mNodePointer)) {
+        String text = nativeFocusCandidateText();
+        int nodePointer = nativeFocusCandidatePointer();
+        if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
             // It is possible that we have the same textfield, but it has moved,
             // i.e. In the case of opening/closing the screen.
             // In that case, we need to set the dimensions, but not the other
             // aspects.
             // We also need to restore the selection, which gets wrecked by
             // calling setTextEntryRect.
-            Spannable spannable = (Spannable) mTextEntry.getText();
+            Spannable spannable = (Spannable) mWebTextView.getText();
             int start = Selection.getSelectionStart(spannable);
             int end = Selection.getSelectionEnd(spannable);
-            setTextEntryRect(x, y, width, height);
             // If the text has been changed by webkit, update it.  However, if
             // there has been more UI text input, ignore it.  We will receive
             // another update when that text is recognized.
-            if (node.mText != null && !node.mText.equals(spannable.toString())
-                    && node.mRootTextGeneration == mTextGeneration) {
-                mTextEntry.setTextAndKeepSelection(node.mText);
+            if (text != null && !text.equals(spannable.toString())
+                    && nativeTextGeneration() == mTextGeneration) {
+                mWebTextView.setTextAndKeepSelection(text);
             } else {
                 Selection.setSelection(spannable, start, end);
             }
         } else {
-            String text = node.mText;
-            setTextEntryRect(x, y, width, height);
-            mTextEntry.setGravity(node.mIsRtlText ? Gravity.RIGHT : 
-                    Gravity.NO_GRAVITY);
+            Rect vBox = contentToView(bounds);
+            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
+                    vBox.height());
+            mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
+                    Gravity.RIGHT : Gravity.NO_GRAVITY);
             // this needs to be called before update adapter thread starts to
-            // ensure the mTextEntry has the same node pointer
-            mTextEntry.setNodePointer(node.mNodePointer);
+            // ensure the mWebTextView has the same node pointer
+            mWebTextView.setNodePointer(nodePointer);
             int maxLength = -1;
-            if (node.mIsTextField) {
-                maxLength = node.mMaxLength;
+            boolean isTextField = nativeFocusCandidateIsTextField();
+            if (isTextField) {
+                maxLength = nativeFocusCandidateMaxLength();
+                String name = nativeFocusCandidateName();
                 if (mWebViewCore.getSettings().getSaveFormData()
-                        && node.mName != null) {
-                    HashMap data = new HashMap();
-                    data.put("text", node.mText);
+                        && name != null) {
                     Message update = mPrivateHandler.obtainMessage(
-                            UPDATE_TEXT_ENTRY_ADAPTER, node.mNodePointer, 0,
-                            data);
-                    UpdateTextEntryAdapter updater = new UpdateTextEntryAdapter(
-                            node.mName, getUrl(), update);
+                            REQUEST_FORM_DATA, nodePointer);
+                    RequestFormData updater = new RequestFormData(name,
+                            getUrl(), update);
                     Thread t = new Thread(updater);
                     t.start();
                 }
             }
-            mTextEntry.setMaxLength(maxLength);
+            mWebTextView.setMaxLength(maxLength);
             AutoCompleteAdapter adapter = null;
-            mTextEntry.setAdapterCustom(adapter);
-            mTextEntry.setSingleLine(node.mIsTextField);
-            mTextEntry.setInPassword(node.mIsPassword);
+            mWebTextView.setAdapterCustom(adapter);
+            mWebTextView.setSingleLine(isTextField);
+            mWebTextView.setInPassword(nativeFocusCandidateIsPassword());
             if (null == text) {
-                mTextEntry.setText("", 0, 0);
+                mWebTextView.setText("", 0, 0);
+                if (DebugFlags.WEB_VIEW) {
+                    Log.v(LOGTAG, "rebuildWebTextView null == text");
+                }
             } else {
                 // Change to true to enable the old style behavior, where
                 // entering a textfield/textarea always set the selection to the
@@ -3019,24 +3176,35 @@
                 // textarea.  Testing out a new behavior, where textfields set
                 // selection at the end, and textareas at the beginning.
                 if (false) {
-                    mTextEntry.setText(text, 0, text.length());
-                } else if (node.mIsTextField) {
+                    mWebTextView.setText(text, 0, text.length());
+                } else if (isTextField) {
                     int length = text.length();
-                    mTextEntry.setText(text, length, length);
+                    mWebTextView.setText(text, length, length);
+                    if (DebugFlags.WEB_VIEW) {
+                        Log.v(LOGTAG, "rebuildWebTextView length=" + length);
+                    }
                 } else {
-                    mTextEntry.setText(text, 0, 0);
+                    mWebTextView.setText(text, 0, 0);
+                    if (DebugFlags.WEB_VIEW) {
+                        Log.v(LOGTAG, "rebuildWebTextView !isTextField");
+                    }
                 }
             }
-            mTextEntry.requestFocus();
+            mWebTextView.requestFocus();
         }
     }
 
-    private class UpdateTextEntryAdapter implements Runnable {
+    /*
+     * This class requests an Adapter for the WebTextView which shows past
+     * entries stored in the database.  It is a Runnable so that it can be done
+     * in its own thread, without slowing down the UI.
+     */
+    private class RequestFormData implements Runnable {
         private String mName;
         private String mUrl;
         private Message mUpdateMessage;
 
-        public UpdateTextEntryAdapter(String name, String url, Message msg) {
+        public RequestFormData(String name, String url, Message msg) {
             mName = name;
             mUrl = url;
             mUpdateMessage = msg;
@@ -3047,29 +3215,21 @@
             if (pastEntries.size() > 0) {
                 AutoCompleteAdapter adapter = new
                         AutoCompleteAdapter(mContext, pastEntries);
-                ((HashMap) mUpdateMessage.obj).put("adapter", adapter);
+                mUpdateMessage.obj = adapter;
                 mUpdateMessage.sendToTarget();
             }
         }
     }
 
-    private void setTextEntryRect(int x, int y, int width, int height) {
-        x = contentToView(x);
-        y = contentToView(y);
-        width = contentToView(width);
-        height = contentToView(height);
-        mTextEntry.setRect(x, y, width, height);
-    }
-
-    // This is used to determine long press with the enter key, or
-    // a center key.  Does not affect long press with the trackball/touch.
-    private boolean mGotEnterDown = false;
+    // This is used to determine long press with the center key.  Does not
+    // affect long press with the trackball/touch.
+    private boolean mGotCenterDown = false;
 
     @Override
     public boolean onKeyDown(int keyCode, KeyEvent event) {
-        if (LOGV_ENABLED) {
+        if (DebugFlags.WEB_VIEW) {
             Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
-                    + ", " + event);
+                    + ", " + event + ", unicode=" + event.getUnicodeChar());
         }
 
         if (mNativeClass == 0) {
@@ -3095,29 +3255,27 @@
             return false;
         }
 
-        if (mShiftIsPressed == false && nativeFocusNodeWantsKeyEvents() == false
-                && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 
+        if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false
+                && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
                 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
             mExtendSelection = false;
             mShiftIsPressed = true;
-            if (nativeUpdateFocusNode()) {
-                FocusNode node = mFocusNode;
-                mSelectX = contentToView(node.mBounds.left);
-                mSelectY = contentToView(node.mBounds.top);
+            if (nativeHasCursorNode()) {
+                Rect rect = nativeCursorNodeBounds();
+                mSelectX = contentToView(rect.left);
+                mSelectY = contentToView(rect.top);
             } else {
                 mSelectX = mScrollX + (int) mLastTouchX;
                 mSelectY = mScrollY + (int) mLastTouchY;
             }
-            int contentX = viewToContent((int) mLastTouchX + mScrollX);
-            int contentY = viewToContent((int) mLastTouchY + mScrollY);
-            nativeClearFocus(contentX, contentY);
+            nativeHideCursor();
        }
 
         if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
                 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
             // always handle the navigation keys in the UI thread
             switchOutDrawHistory();
-            if (navHandledKey(keyCode, 1, false, event.getEventTime())) {
+            if (navHandledKey(keyCode, 1, false, event.getEventTime(), false)) {
                 playSoundEffect(keyCodeToSoundsEffect(keyCode));
                 return true;
             }
@@ -3125,13 +3283,12 @@
             return false;
         }
 
-        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER
-                || keyCode == KeyEvent.KEYCODE_ENTER) {
+        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
             switchOutDrawHistory();
             if (event.getRepeatCount() == 0) {
-                mGotEnterDown = true;
+                mGotCenterDown = true;
                 mPrivateHandler.sendMessageDelayed(mPrivateHandler
-                        .obtainMessage(LONG_PRESS_ENTER), LONG_PRESS_TIMEOUT);
+                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
                 // Already checked mNativeClass, so we do not need to check it
                 // again.
                 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
@@ -3141,6 +3298,15 @@
             return false;
         }
 
+        if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
+                && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
+            // turn off copy select if a shift-key combo is pressed
+            mExtendSelection = mShiftIsPressed = false;
+            if (mTouchMode == TOUCH_SELECT_MODE) {
+                mTouchMode = TOUCH_INIT_MODE;
+            }
+        }
+
         if (getSettings().getNavDump()) {
             switch (keyCode) {
                 case KeyEvent.KEYCODE_4:
@@ -3169,8 +3335,29 @@
             }
         }
 
+        if (nativeCursorIsPlugin()) {
+            nativeUpdatePluginReceivesEvents();
+            invalidate();
+        } else if (nativeCursorIsTextInput()) {
+            // This message will put the node in focus, for the DOM's notion
+            // of focus, and make the focuscontroller active
+            mWebViewCore.sendMessage(EventHub.CLICK);
+            // This will bring up the WebTextView and put it in focus, for
+            // our view system's notion of focus
+            rebuildWebTextView();
+            // Now we need to pass the event to it
+            return mWebTextView.onKeyDown(keyCode, event);
+        } else if (nativeHasFocusNode()) {
+            // In this case, the cursor is not on a text input, but the focus
+            // might be.  Check it, and if so, hand over to the WebTextView.
+            rebuildWebTextView();
+            if (inEditingMode()) {
+                return mWebTextView.onKeyDown(keyCode, event);
+            }
+        }
+
         // TODO: should we pass all the keys to DOM or check the meta tag
-        if (nativeFocusNodeWantsKeyEvents() || true) {
+        if (nativeCursorWantsKeyEvents() || true) {
             // pass the key to DOM
             mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
             // return true as DOM handles the key
@@ -3183,20 +3370,19 @@
 
     @Override
     public boolean onKeyUp(int keyCode, KeyEvent event) {
-        if (LOGV_ENABLED) {
+        if (DebugFlags.WEB_VIEW) {
             Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
-                    + ", " + event);
+                    + ", " + event + ", unicode=" + event.getUnicodeChar());
         }
 
         if (mNativeClass == 0) {
             return false;
         }
 
-        // special CALL handling when focus node's href is "tel:XXX"
-        if (keyCode == KeyEvent.KEYCODE_CALL && nativeUpdateFocusNode()) {
-            FocusNode node = mFocusNode;
-            String text = node.mText;
-            if (!node.mIsTextField && !node.mIsTextArea && text != null
+        // special CALL handling when cursor node's href is "tel:XXX"
+        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
+            String text = nativeCursorText();
+            if (!nativeCursorIsTextInput() && text != null
                     && text.startsWith(SCHEME_TEL)) {
                 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
                 getContext().startActivity(intent);
@@ -3223,7 +3409,7 @@
             return false;
         }
 
-        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 
+        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
                 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
             if (commitCopy()) {
                 return true;
@@ -3237,55 +3423,30 @@
             return false;
         }
 
-        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER
-                || keyCode == KeyEvent.KEYCODE_ENTER) {
+        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
             // remove the long press message first
-            mPrivateHandler.removeMessages(LONG_PRESS_ENTER);
-            mGotEnterDown = false;
+            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
+            mGotCenterDown = false;
 
-            if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) {
-                if (mShiftIsPressed) {
-                    return false;
-                }
-                if (getSettings().supportZoom()) {
-                    if (mTouchMode == TOUCH_DOUBLECLICK_MODE) {
-                        zoomScrollOut();
-                    } else {
-                        if (LOGV_ENABLED) {
-                            Log.v(LOGTAG, "TOUCH_DOUBLECLICK_MODE");
-                        }
-                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
-                                .obtainMessage(SWITCH_TO_ENTER), TAP_TIMEOUT);
-                        mTouchMode = TOUCH_DOUBLECLICK_MODE;
-                    }
-                    return true;
-                }
+            if (mShiftIsPressed) {
+                return false;
             }
-
-            Rect visibleRect = sendOurVisibleRect();
-            // Note that sendOurVisibleRect calls viewToContent, so the
-            // coordinates should be in content coordinates.
-            if (nativeUpdateFocusNode()) {
-                if (Rect.intersects(mFocusNode.mBounds, visibleRect)) {
-                    nativeSetFollowedLink(true);
-                    mWebViewCore.sendMessage(EventHub.SET_FINAL_FOCUS,
-                            EventHub.BLOCK_FOCUS_CHANGE_UNTIL_KEY_UP, 0,
-                            new WebViewCore.FocusData(mFocusData));
-                    playSoundEffect(SoundEffectConstants.CLICK);
-                    if (!mCallbackProxy.uiOverrideUrlLoading(mFocusNode.mText)) {
-                        // use CLICK instead of KEY_DOWN/KEY_UP so that we can
-                        // trigger mouse click events
-                        mWebViewCore.sendMessage(EventHub.CLICK);
-                    }
+            if (getSettings().supportZoom()
+                    && mTouchMode == TOUCH_DOUBLECLICK_MODE) {
+                zoomScrollOut();
+            } else {
+                mPrivateHandler.sendMessageDelayed(mPrivateHandler
+                        .obtainMessage(SWITCH_TO_CLICK), TAP_TIMEOUT);
+                if (DebugFlags.WEB_VIEW) {
+                    Log.v(LOGTAG, "TOUCH_DOUBLECLICK_MODE");
                 }
-                return true;
+                mTouchMode = TOUCH_DOUBLECLICK_MODE;
             }
-            // Bubble up the key event as WebView doesn't handle it
-            return false;
+            return true;
         }
 
         // TODO: should we pass all the keys to DOM or check the meta tag
-        if (nativeFocusNodeWantsKeyEvents() || true) {
+        if (nativeCursorWantsKeyEvents() || true) {
             // pass the key to DOM
             mWebViewCore.sendMessage(EventHub.KEY_UP, event);
             // return true as DOM handles the key
@@ -3295,16 +3456,14 @@
         // Bubble up the key event as WebView doesn't handle it
         return false;
     }
-    
+
     /**
      * @hide
      */
     public void emulateShiftHeld() {
         mExtendSelection = false;
         mShiftIsPressed = true;
-        int contentX = viewToContent((int) mLastTouchX + mScrollX);
-        int contentY = viewToContent((int) mLastTouchY + mScrollY);
-        nativeClearFocus(contentX, contentY);
+        nativeHideCursor();
     }
 
     private boolean commitCopy() {
@@ -3352,16 +3511,13 @@
         // Clean up the zoom controller
         mZoomButtonsController.setVisible(false);
     }
-    
+
     // Implementation for OnHierarchyChangeListener
     public void onChildViewAdded(View parent, View child) {}
-    
+
     public void onChildViewRemoved(View p, View child) {
         if (child == this) {
-            if (inEditingMode()) {
-                clearTextEntry();
-                mNeedsUpdateTextEntry = true;
-            }
+            clearTextEntry();
         }
     }
 
@@ -3374,26 +3530,25 @@
     public void onGlobalFocusChanged(View oldFocus, View newFocus) {
     }
 
-    // To avoid drawing the focus ring, and remove the TextView when our window
+    // To avoid drawing the cursor ring, and remove the TextView when our window
     // loses focus.
     @Override
     public void onWindowFocusChanged(boolean hasWindowFocus) {
         if (hasWindowFocus) {
             if (hasFocus()) {
                 // If our window regained focus, and we have focus, then begin
-                // drawing the focus ring, and restore the TextView if
-                // necessary.
-                mDrawFocusRing = true;
-                if (mNeedsUpdateTextEntry) {
-                    updateTextEntry();
-                }
+                // drawing the cursor ring
+                mDrawCursorRing = true;
                 if (mNativeClass != 0) {
                     nativeRecordButtons(true, false, true);
+                    if (inEditingMode()) {
+                        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0);
+                    }
                 }
             } else {
                 // If our window gained focus, but we do not have it, do not
-                // draw the focus ring.
-                mDrawFocusRing = false;
+                // draw the cursor ring.
+                mDrawCursorRing = false;
                 // We do not call nativeRecordButtons here because we assume
                 // that when we lost focus, or window focus, it got called with
                 // false for the first parameter
@@ -3402,39 +3557,49 @@
             if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) {
                 /*
                  * The zoom controls come in their own window, so our window
-                 * loses focus. Our policy is to not draw the focus ring if
+                 * loses focus. Our policy is to not draw the cursor ring if
                  * our window is not focused, but this is an exception since
                  * the user can still navigate the web page with the zoom
                  * controls showing.
                  */
-                // If our window has lost focus, stop drawing the focus ring
-                mDrawFocusRing = false;
+                // If our window has lost focus, stop drawing the cursor ring
+                mDrawCursorRing = false;
             }
             mGotKeyDown = false;
             mShiftIsPressed = false;
             if (mNativeClass != 0) {
                 nativeRecordButtons(false, false, true);
             }
+            setFocusControllerInactive();
         }
         invalidate();
         super.onWindowFocusChanged(hasWindowFocus);
     }
 
+    /*
+     * Pass a message to WebCore Thread, telling the WebCore::Page's
+     * FocusController to be  "inactive" so that it will
+     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
+     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
+     */
+    private void setFocusControllerInactive() {
+        // Do not need to also check whether mWebViewCore is null, because
+        // mNativeClass is only set if mWebViewCore is non null
+        if (mNativeClass == 0) return;
+        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0);
+    }
+
     @Override
     protected void onFocusChanged(boolean focused, int direction,
             Rect previouslyFocusedRect) {
-        if (LOGV_ENABLED) {
+        if (DebugFlags.WEB_VIEW) {
             Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
         }
         if (focused) {
             // When we regain focus, if we have window focus, resume drawing
-            // the focus ring, and add the TextView if necessary.
+            // the cursor ring
             if (hasWindowFocus()) {
-                mDrawFocusRing = true;
-                if (mNeedsUpdateTextEntry) {
-                    updateTextEntry();
-                    mNeedsUpdateTextEntry = false;
-                }
+                mDrawCursorRing = true;
                 if (mNativeClass != 0) {
                     nativeRecordButtons(true, false, true);
                 }
@@ -3445,12 +3610,13 @@
             }
         } else {
             // When we lost focus, unless focus went to the TextView (which is
-            // true if we are in editing mode), stop drawing the focus ring.
+            // true if we are in editing mode), stop drawing the cursor ring.
             if (!inEditingMode()) {
-                mDrawFocusRing = false;
+                mDrawCursorRing = false;
                 if (mNativeClass != 0) {
                     nativeRecordButtons(false, false, true);
                 }
+                setFocusControllerInactive();
             }
             mGotKeyDown = false;
         }
@@ -3479,10 +3645,11 @@
     @Override
     protected void onScrollChanged(int l, int t, int oldl, int oldt) {
         super.onScrollChanged(l, t, oldl, oldt);
+
         sendOurVisibleRect();
     }
-    
-    
+
+
     @Override
     public boolean dispatchKeyEvent(KeyEvent event) {
         boolean dispatch = true;
@@ -3526,7 +3693,7 @@
             return false;
         }
 
-        if (LOGV_ENABLED) {
+        if (DebugFlags.WEB_VIEW) {
             Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode="
                     + mTouchMode);
         }
@@ -3551,7 +3718,7 @@
         if (mForwardTouchEvents && mTouchMode != SCROLL_ZOOM_OUT
                 && mTouchMode != SCROLL_ZOOM_ANIMATION_IN
                 && mTouchMode != SCROLL_ZOOM_ANIMATION_OUT
-                && (action != MotionEvent.ACTION_MOVE || 
+                && (action != MotionEvent.ACTION_MOVE ||
                         eventTime - mLastSentTouchTime > TOUCH_SENT_INTERVAL)) {
             WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
             ted.mAction = action;
@@ -3582,7 +3749,7 @@
                     mSelectX = mScrollX + (int) x;
                     mSelectY = mScrollY + (int) y;
                     mTouchMode = TOUCH_SELECT_MODE;
-                    if (LOGV_ENABLED) {
+                    if (DebugFlags.WEB_VIEW) {
                         Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY);
                     }
                     nativeMoveSelection(viewToContent(mSelectX)
@@ -3610,7 +3777,7 @@
                 break;
             }
             case MotionEvent.ACTION_MOVE: {
-                if (mTouchMode == TOUCH_DONE_MODE 
+                if (mTouchMode == TOUCH_DONE_MODE
                         || mTouchMode == SCROLL_ZOOM_ANIMATION_IN
                         || mTouchMode == SCROLL_ZOOM_ANIMATION_OUT) {
                     // no dragging during scroll zoom animation
@@ -3627,7 +3794,7 @@
                     if (mTouchMode == TOUCH_SELECT_MODE) {
                         mSelectX = mScrollX + (int) x;
                         mSelectY = mScrollY + (int) y;
-                        if (LOGV_ENABLED) {
+                        if (DebugFlags.WEB_VIEW) {
                             Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY);
                         }
                         nativeMoveSelection(viewToContent(mSelectX)
@@ -3660,12 +3827,9 @@
 
                     mTouchMode = TOUCH_DRAG_MODE;
                     WebViewCore.pauseUpdate(mWebViewCore);
-                    int contentX = viewToContent((int) x + mScrollX);
-                    int contentY = viewToContent((int) y + mScrollY);
-                    if (inEditingMode()) {
-                        mTextEntry.updateCachedTextfield();
+                    if (!mDragFromTextInput) {
+                        nativeHideCursor();
                     }
-                    nativeClearFocus(contentX, contentY);
                     // remove the zoom anchor if there is any
                     if (mZoomScale != 0) {
                         mWebViewCore
@@ -3675,7 +3839,7 @@
                     if (settings.supportZoom()
                             && settings.getBuiltInZoomControls()
                             && !mZoomButtonsController.isVisible()
-                            && (canZoomScrollOut() || 
+                            && (canZoomScrollOut() ||
                                     mMinZoomScale < mMaxZoomScale)) {
                         mZoomButtonsController.setVisible(true);
                     }
@@ -3701,7 +3865,7 @@
                             }
                             // reverse direction means lock in the snap mode
                             if ((ax > MAX_SLOPE_FOR_DIAG * ay) &&
-                                    ((mSnapPositive && 
+                                    ((mSnapPositive &&
                                     deltaX < -mMinLockSnapReverseDistance)
                                     || (!mSnapPositive &&
                                     deltaX > mMinLockSnapReverseDistance))) {
@@ -3715,9 +3879,9 @@
                             }
                             // reverse direction means lock in the snap mode
                             if ((ay > MAX_SLOPE_FOR_DIAG * ax) &&
-                                    ((mSnapPositive && 
+                                    ((mSnapPositive &&
                                     deltaY < -mMinLockSnapReverseDistance)
-                                    || (!mSnapPositive && 
+                                    || (!mSnapPositive &&
                                     deltaY > mMinLockSnapReverseDistance))) {
                                 mSnapScrollMode = SNAP_Y_LOCK;
                             }
@@ -3782,7 +3946,7 @@
                         // no action during scroll animation
                         break;
                     case SCROLL_ZOOM_OUT:
-                        if (LOGV_ENABLED) {
+                        if (DebugFlags.WEB_VIEW) {
                             Log.v(LOGTAG, "ACTION_UP SCROLL_ZOOM_OUT"
                                     + " eventTime - mLastTouchTime="
                                     + (eventTime - mLastTouchTime));
@@ -3840,18 +4004,13 @@
                 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
                 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
                 mTouchMode = TOUCH_DONE_MODE;
-                int contentX = viewToContent((int) mLastTouchX + mScrollX);
-                int contentY = viewToContent((int) mLastTouchY + mScrollY);
-                if (inEditingMode()) {
-                    mTextEntry.updateCachedTextfield();
-                }
-                nativeClearFocus(contentX, contentY);
+                nativeHideCursor();
                 break;
             }
         }
         return true;
     }
-    
+
     private long mTrackballFirstTime = 0;
     private long mTrackballLastTime = 0;
     private float mTrackballRemainsX = 0.0f;
@@ -3873,14 +4032,14 @@
     private boolean mShiftIsPressed = false;
     private boolean mTrackballDown = false;
     private long mTrackballUpTime = 0;
-    private long mLastFocusTime = 0;
-    private Rect mLastFocusBounds;
+    private long mLastCursorTime = 0;
+    private Rect mLastCursorBounds;
 
     // Set by default; BrowserActivity clears to interpret trackball data
-    // directly for movement. Currently, the framework only passes 
+    // directly for movement. Currently, the framework only passes
     // arrow key events, not trackball events, from one child to the next
     private boolean mMapTrackballToArrowKeys = true;
-    
+
     public void setMapTrackballToArrowKeys(boolean setMap) {
         mMapTrackballToArrowKeys = setMap;
     }
@@ -3898,26 +4057,27 @@
             return true;
         }
         if (ev.getAction() == MotionEvent.ACTION_DOWN) {
-            mPrivateHandler.removeMessages(SWITCH_TO_ENTER);
+            mPrivateHandler.removeMessages(SWITCH_TO_CLICK);
             mTrackballDown = true;
-            if (mNativeClass != 0) {
-                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
+            if (mNativeClass == 0) {
+                return false;
             }
-            if (time - mLastFocusTime <= TRACKBALL_TIMEOUT
-                    && !mLastFocusBounds.equals(nativeGetFocusRingBounds())) {
-                nativeSelectBestAt(mLastFocusBounds);
+            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
+            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
+                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
+                nativeSelectBestAt(mLastCursorBounds);
             }
-            if (LOGV_ENABLED) {
+            if (DebugFlags.WEB_VIEW) {
                 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
-                        + " time=" + time 
-                        + " mLastFocusTime=" + mLastFocusTime);
+                        + " time=" + time
+                        + " mLastCursorTime=" + mLastCursorTime);
             }
             if (isInTouchMode()) requestFocusFromTouch();
             return false; // let common code in onKeyDown at it
-        } 
+        }
         if (ev.getAction() == MotionEvent.ACTION_UP) {
-            // LONG_PRESS_ENTER is set in common onKeyDown
-            mPrivateHandler.removeMessages(LONG_PRESS_ENTER);
+            // LONG_PRESS_CENTER is set in common onKeyDown
+            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
             mTrackballDown = false;
             mTrackballUpTime = time;
             if (mShiftIsPressed) {
@@ -3927,42 +4087,42 @@
                     mExtendSelection = true;
                 }
             }
-            if (LOGV_ENABLED) {
+            if (DebugFlags.WEB_VIEW) {
                 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
-                        + " time=" + time 
+                        + " time=" + time
                 );
             }
             return false; // let common code in onKeyUp at it
         }
         if (mMapTrackballToArrowKeys && mShiftIsPressed == false) {
-            if (LOGV_ENABLED) Log.v(LOGTAG, "onTrackballEvent gmail quit");
+            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
             return false;
         }
-        // no move if we're still waiting on SWITCH_TO_ENTER timeout
+        // no move if we're still waiting on SWITCH_TO_CLICK timeout
         if (mTouchMode == TOUCH_DOUBLECLICK_MODE) {
-            if (LOGV_ENABLED) Log.v(LOGTAG, "onTrackballEvent 2 click quit");
+            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent 2 click quit");
             return true;
         }
         if (mTrackballDown) {
-            if (LOGV_ENABLED) Log.v(LOGTAG, "onTrackballEvent down quit");
+            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
             return true; // discard move if trackball is down
         }
         if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
-            if (LOGV_ENABLED) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
+            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
             return true;
         }
         // TODO: alternatively we can do panning as touch does
         switchOutDrawHistory();
         if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
-            if (LOGV_ENABLED) {
-                Log.v(LOGTAG, "onTrackballEvent time=" 
+            if (DebugFlags.WEB_VIEW) {
+                Log.v(LOGTAG, "onTrackballEvent time="
                         + time + " last=" + mTrackballLastTime);
             }
             mTrackballFirstTime = time;
             mTrackballXMove = mTrackballYMove = 0;
         }
         mTrackballLastTime = time;
-        if (LOGV_ENABLED) {
+        if (DebugFlags.WEB_VIEW) {
             Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
         }
         mTrackballRemainsX += ev.getX();
@@ -3970,7 +4130,7 @@
         doTrackball(time);
         return true;
     }
-    
+
     void moveSelection(float xRate, float yRate) {
         if (mNativeClass == 0)
             return;
@@ -3984,8 +4144,8 @@
                 , mSelectX));
         mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
                 , mSelectY));
-        if (LOGV_ENABLED) {
-            Log.v(LOGTAG, "moveSelection" 
+        if (DebugFlags.WEB_VIEW) {
+            Log.v(LOGTAG, "moveSelection"
                     + " mSelectX=" + mSelectX
                     + " mSelectY=" + mSelectY
                     + " mScrollX=" + mScrollX
@@ -3997,10 +4157,10 @@
         nativeMoveSelection(viewToContent(mSelectX)
                 , viewToContent(mSelectY), mExtendSelection);
         int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
-                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 
+                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
                 : 0;
         int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
-                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 
+                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
                 : 0;
         pinScrollBy(scrollX, scrollY, true, 0);
         Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
@@ -4057,7 +4217,7 @@
         if (elapsed == 0) {
             elapsed = TRACKBALL_TIMEOUT;
         }
-        float xRate = mTrackballRemainsX * 1000 / elapsed; 
+        float xRate = mTrackballRemainsX * 1000 / elapsed;
         float yRate = mTrackballRemainsY * 1000 / elapsed;
         if (mShiftIsPressed) {
             moveSelection(xRate, yRate);
@@ -4067,7 +4227,7 @@
         float ax = Math.abs(xRate);
         float ay = Math.abs(yRate);
         float maxA = Math.max(ax, ay);
-        if (LOGV_ENABLED) {
+        if (DebugFlags.WEB_VIEW) {
             Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
                     + " xRate=" + xRate
                     + " yRate=" + yRate
@@ -4084,9 +4244,9 @@
             int maxWH = Math.max(width, height);
             mZoomScrollX += scaleTrackballX(xRate, maxWH);
             mZoomScrollY += scaleTrackballY(yRate, maxWH);
-            if (LOGV_ENABLED) {
+            if (DebugFlags.WEB_VIEW) {
                 Log.v(LOGTAG, "doTrackball SCROLL_ZOOM_OUT"
-                        + " mZoomScrollX=" + mZoomScrollX 
+                        + " mZoomScrollX=" + mZoomScrollX
                         + " mZoomScrollY=" + mZoomScrollY);
             }
             mZoomScrollX = Math.min(width, Math.max(0, mZoomScrollX));
@@ -4104,18 +4264,18 @@
         int oldScrollX = mScrollX;
         int oldScrollY = mScrollY;
         if (count > 0) {
-            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 
-                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 
+            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
+                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
                     mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
                     KeyEvent.KEYCODE_DPAD_RIGHT;
             count = Math.min(count, TRACKBALL_MOVE_COUNT);
-            if (LOGV_ENABLED) {
-                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 
+            if (DebugFlags.WEB_VIEW) {
+                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
                         + " count=" + count
                         + " mTrackballRemainsX=" + mTrackballRemainsX
                         + " mTrackballRemainsY=" + mTrackballRemainsY);
             }
-            if (navHandledKey(selectKeyCode, count, false, time)) {
+            if (navHandledKey(selectKeyCode, count, false, time, false)) {
                 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
             }
             mTrackballRemainsX = mTrackballRemainsY = 0;
@@ -4123,12 +4283,12 @@
         if (count >= TRACKBALL_SCROLL_COUNT) {
             int xMove = scaleTrackballX(xRate, width);
             int yMove = scaleTrackballY(yRate, height);
-            if (LOGV_ENABLED) {
+            if (DebugFlags.WEB_VIEW) {
                 Log.v(LOGTAG, "doTrackball pinScrollBy"
                         + " count=" + count
                         + " xMove=" + xMove + " yMove=" + yMove
-                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 
-                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 
+                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
+                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
                         );
             }
             if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
@@ -4141,18 +4301,17 @@
                 pinScrollBy(xMove, yMove, true, 0);
             }
             mUserScroll = true;
-        } 
-        mWebViewCore.sendMessage(EventHub.UNBLOCK_FOCUS);        
+        }
     }
 
     public void flingScroll(int vx, int vy) {
         int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
         int maxY = Math.max(computeVerticalScrollRange() - getViewHeight(), 0);
-        
+
         mScroller.fling(mScrollX, mScrollY, vx, vy, 0, maxX, 0, maxY);
         invalidate();
     }
-    
+
     private void doFling() {
         if (mVelocityTracker == null) {
             return;
@@ -4171,7 +4330,7 @@
                 vx = 0;
             }
         }
-        
+
         if (true /* EMG release: make our fling more like Maps' */) {
             // maps cuts their velocity in half
             vx = vx * 3 / 4;
@@ -4190,6 +4349,8 @@
 
     private boolean zoomWithPreview(float scale) {
         float oldScale = mActualScale;
+        mInitialScrollX = mScrollX;
+        mInitialScrollY = mScrollY;
 
         // snap to DEFAULT_SCALE if it is close
         if (scale > (mDefaultScale - 0.05) && scale < (mDefaultScale + 0.05)) {
@@ -4232,7 +4393,7 @@
         }
         if (mZoomControls == null) {
             mZoomControls = createZoomControls();
-            
+
             /*
              * need to be set to VISIBLE first so that getMeasuredHeight() in
              * {@link #onSizeChanged()} can return the measured value for proper
@@ -4241,7 +4402,7 @@
             mZoomControls.setVisibility(View.VISIBLE);
             mZoomControlRunnable = new Runnable() {
                 public void run() {
-                    
+
                     /* Don't dismiss the controls if the user has
                      * focus on them. Wait and check again later.
                      */
@@ -4293,7 +4454,7 @@
     /**
      * Gets the {@link ZoomButtonsController} which can be used to add
      * additional buttons to the zoom controls window.
-     * 
+     *
      * @return The instance of {@link ZoomButtonsController} used by this class,
      *         or null if it is unavailable.
      * @hide
@@ -4331,19 +4492,63 @@
         int contentY = viewToContent((int) mLastTouchY + mScrollY);
         Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
                 contentX + mNavSlop, contentY + mNavSlop);
-        // If we were already focused on a textfield, update its cache.
-        if (inEditingMode()) {
-            mTextEntry.updateCachedTextfield();
-        }
         nativeSelectBestAt(rect);
     }
 
+    /**
+     * Scroll the focused text field/area to match the WebTextView
+     * @param x New x position of the WebTextView in view coordinates
+     * @param y New y position of the WebTextView in view coordinates
+     */
+    /*package*/ void scrollFocusedTextInput(int x, int y) {
+        if (!inEditingMode() || mWebViewCore == null) {
+            return;
+        }
+        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, viewToContent(x),
+                viewToContent(y));
+    }
+
+    /**
+     * Set our starting point and time for a drag from the WebTextView.
+     */
+    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
+        if (!inEditingMode()) {
+            return;
+        }
+        mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
+        mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
+        mLastTouchTime = eventTime;
+        if (!mScroller.isFinished()) {
+            mScroller.abortAnimation();
+            mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE);
+        }
+        mSnapScrollMode = SNAP_NONE;
+        mVelocityTracker = VelocityTracker.obtain();
+        mTouchMode = TOUCH_DRAG_START_MODE;
+    }
+
+    /**
+     * Given a motion event from the WebTextView, set its location to our
+     * coordinates, and handle the event.
+     */
+    /*package*/ boolean textFieldDrag(MotionEvent event) {
+        if (!inEditingMode()) {
+            return false;
+        }
+        mDragFromTextInput = true;
+        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
+                (float) (mWebTextView.getTop() - mScrollY));
+        boolean result = onTouchEvent(event);
+        mDragFromTextInput = false;
+        return result;
+    }
+
     /*package*/ void shortPressOnTextField() {
         if (inEditingMode()) {
-            View v = mTextEntry;
+            View v = mWebTextView;
             int x = viewToContent((v.getLeft() + v.getRight()) >> 1);
             int y = viewToContent((v.getTop() + v.getBottom()) >> 1);
-            nativeMotionUp(x, y, mNavSlop, true);
+            nativeMotionUp(x, y, mNavSlop);
         }
     }
 
@@ -4355,14 +4560,13 @@
         // mLastTouchX and mLastTouchY are the point in the current viewport
         int contentX = viewToContent((int) mLastTouchX + mScrollX);
         int contentY = viewToContent((int) mLastTouchY + mScrollY);
-        if (nativeMotionUp(contentX, contentY, mNavSlop, true)) {
+        if (nativeMotionUp(contentX, contentY, mNavSlop)) {
             if (mLogEvent) {
                 Checkin.updateStats(mContext.getContentResolver(),
                         Checkin.Stats.Tag.BROWSER_SNAP_CENTER, 1, 0.0);
             }
         }
-        if (nativeUpdateFocusNode() && !mFocusNode.mIsTextField
-                && !mFocusNode.mIsTextArea) {
+        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
             playSoundEffect(SoundEffectConstants.CLICK);
         }
     }
@@ -4373,11 +4577,21 @@
         mCallbackProxy.uiOverrideUrlLoading(url);
     }
 
+    // called by JNI
+    private void sendPluginState(int state) {
+        WebViewCore.PluginStateData psd = new WebViewCore.PluginStateData();
+        psd.mFrame = nativeCursorFramePointer();
+        psd.mNode = nativeCursorNodePointer();
+        psd.mState = state;
+        mWebViewCore.sendMessage(EventHub.PLUGIN_STATE, psd);
+    }
+
     @Override
     public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
         boolean result = false;
         if (inEditingMode()) {
-            result = mTextEntry.requestFocus(direction, previouslyFocusedRect);
+            result = mWebTextView.requestFocus(direction,
+                    previouslyFocusedRect);
         } else {
             result = super.requestFocus(direction, previouslyFocusedRect);
             if (mWebViewCore.getSettings().getNeedInitialFocus()) {
@@ -4401,8 +4615,8 @@
                     default:
                         return result;
                 }
-                if (mNativeClass != 0 && !nativeUpdateFocusNode()) {
-                    navHandledKey(fakeKeyDirection, 1, true, 0);
+                if (mNativeClass != 0 && !nativeHasCursorNode()) {
+                    navHandledKey(fakeKeyDirection, 1, true, 0, true);
                 }
             }
         }
@@ -4470,14 +4684,19 @@
 
         int scrollYDelta = 0;
 
-        if (rect.bottom > screenBottom && rect.top > screenTop) {
-            if (rect.height() > height) {
-                scrollYDelta += (rect.top - screenTop);
+        if (rect.bottom > screenBottom) {
+            int oneThirdOfScreenHeight = height / 3;
+            if (rect.height() > 2 * oneThirdOfScreenHeight) {
+                // If the rectangle is too tall to fit in the bottom two thirds
+                // of the screen, place it at the top.
+                scrollYDelta = rect.top - screenTop;
             } else {
-                scrollYDelta += (rect.bottom - screenBottom);
+                // If the rectangle will still fit on screen, we want its
+                // top to be in the top third of the screen.
+                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
             }
         } else if (rect.top < screenTop) {
-            scrollYDelta -= (screenTop - rect.top);
+            scrollYDelta = rect.top - screenTop;
         }
 
         int width = getWidth() - getVerticalScrollbarWidth();
@@ -4502,33 +4721,35 @@
 
         return false;
     }
-    
+
     /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
             String replace, int newStart, int newEnd) {
-        HashMap arg = new HashMap();
-        arg.put("focusData", new WebViewCore.FocusData(mFocusData));
-        arg.put("replace", replace);
-        arg.put("start", new Integer(newStart));
-        arg.put("end", new Integer(newEnd));
+        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
+        arg.mReplace = replace;
+        arg.mNewStart = newStart;
+        arg.mNewEnd = newEnd;
         mTextGeneration++;
+        arg.mTextGeneration = mTextGeneration;
         mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
     }
 
     /* package */ void passToJavaScript(String currentText, KeyEvent event) {
-        HashMap arg = new HashMap();
-        arg.put("focusData", new WebViewCore.FocusData(mFocusData));
-        arg.put("event", event);
-        arg.put("currentText", currentText);
+        if (nativeCursorWantsKeyEvents() && !nativeCursorMatchesFocus()) {
+            mWebViewCore.sendMessage(EventHub.CLICK);
+        }
+        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
+        arg.mEvent = event;
+        arg.mCurrentText = currentText;
         // Increase our text generation number, and pass it to webcore thread
         mTextGeneration++;
         mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
         // WebKit's document state is not saved until about to leave the page.
-        // To make sure the host application, like Browser, has the up to date 
-        // document state when it goes to background, we force to save the 
+        // To make sure the host application, like Browser, has the up to date
+        // document state when it goes to background, we force to save the
         // document state.
         mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
         mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
-                new WebViewCore.FocusData(mFocusData), 1000);
+                cursorData(), 1000);
     }
 
     /* package */ WebViewCore getWebViewCore() {
@@ -4546,9 +4767,9 @@
     class PrivateHandler extends Handler {
         @Override
         public void handleMessage(Message msg) {
-            if (LOGV_ENABLED) {
-                Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what 
-                        > INVAL_RECT_MSG_ID ? Integer.toString(msg.what) 
+            if (DebugFlags.WEB_VIEW) {
+                Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what
+                        > INVAL_RECT_MSG_ID ? Integer.toString(msg.what)
                         : HandlerDebugString[msg.what - REMEMBER_PASSWORD]);
             }
             switch (msg.what) {
@@ -4577,23 +4798,42 @@
                     if (!mPreventDrag) {
                         mTouchMode = TOUCH_DONE_MODE;
                         performLongClick();
-                        updateTextEntry();
+                        rebuildWebTextView();
                     }
                     break;
                 }
-                case SWITCH_TO_ENTER:
-                    if (LOGV_ENABLED) Log.v(LOGTAG, "SWITCH_TO_ENTER");
+                case SWITCH_TO_CLICK:
+                    // The user clicked with the trackball, and did not click a
+                    // second time, so perform the action of a trackball single
+                    // click
                     mTouchMode = TOUCH_DONE_MODE;
-                    onKeyUp(KeyEvent.KEYCODE_ENTER
-                            , new KeyEvent(KeyEvent.ACTION_UP
-                            , KeyEvent.KEYCODE_ENTER));
+                    Rect visibleRect = sendOurVisibleRect();
+                    // Note that sendOurVisibleRect calls viewToContent, so the
+                    // coordinates should be in content coordinates.
+                    if (!nativeCursorIntersects(visibleRect)) {
+                        break;
+                    }
+                    nativeSetFollowedLink(true);
+                    nativeUpdatePluginReceivesEvents();
+                    WebViewCore.CursorData data = cursorData();
+                    mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
+                    playSoundEffect(SoundEffectConstants.CLICK);
+                    boolean isTextInput = nativeCursorIsTextInput();
+                    if (isTextInput || !mCallbackProxy.uiOverrideUrlLoading(
+                                nativeCursorText())) {
+                        mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
+                                nativeCursorNodePointer());
+                    }
+                    if (isTextInput) {
+                        rebuildWebTextView();
+                    }
                     break;
                 case SCROLL_BY_MSG_ID:
                     setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
                     break;
                 case SYNC_SCROLL_TO_MSG_ID:
                     if (mUserScroll) {
-                        // if user has scrolled explicitly, don't sync the 
+                        // if user has scrolled explicitly, don't sync the
                         // scroll position any more
                         mUserScroll = false;
                         break;
@@ -4602,7 +4842,7 @@
                 case SCROLL_TO_MSG_ID:
                     if (setContentScrollTo(msg.arg1, msg.arg2)) {
                         // if we can't scroll to the exact position due to pin,
-                        // send a message to WebCore to re-scroll when we get a 
+                        // send a message to WebCore to re-scroll when we get a
                         // new picture
                         mUserScroll = false;
                         mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
@@ -4614,7 +4854,7 @@
                     break;
                 case NEW_PICTURE_MSG_ID:
                     // called for new content
-                    final WebViewCore.DrawData draw = 
+                    final WebViewCore.DrawData draw =
                             (WebViewCore.DrawData) msg.obj;
                     final Point viewSize = draw.mViewPoint;
                     if (mZoomScale > 0) {
@@ -4637,9 +4877,9 @@
                     // received in the fixed dimension.
                     final boolean updateLayout = viewSize.x == mLastWidthSent
                             && viewSize.y == mLastHeightSent;
-                    recordNewContentSize(draw.mWidthHeight.x, 
+                    recordNewContentSize(draw.mWidthHeight.x,
                             draw.mWidthHeight.y, updateLayout);
-                    if (LOGV_ENABLED) {
+                    if (DebugFlags.WEB_VIEW) {
                         Rect b = draw.mInvalRegion.getBounds();
                         Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
                                 b.left+","+b.top+","+b.right+","+b.bottom+"}");
@@ -4655,22 +4895,23 @@
                     break;
                 case UPDATE_TEXTFIELD_TEXT_MSG_ID:
                     // Make sure that the textfield is currently focused
-                    // and representing the same node as the pointer.  
-                    if (inEditingMode() && 
-                            mTextEntry.isSameTextField(msg.arg1)) {
+                    // and representing the same node as the pointer.
+                    if (inEditingMode() &&
+                            mWebTextView.isSameTextField(msg.arg1)) {
                         if (msg.getData().getBoolean("password")) {
-                            Spannable text = (Spannable) mTextEntry.getText();
+                            Spannable text = (Spannable) mWebTextView.getText();
                             int start = Selection.getSelectionStart(text);
                             int end = Selection.getSelectionEnd(text);
-                            mTextEntry.setInPassword(true);
+                            mWebTextView.setInPassword(true);
                             // Restore the selection, which may have been
                             // ruined by setInPassword.
-                            Spannable pword = (Spannable) mTextEntry.getText();
+                            Spannable pword =
+                                    (Spannable) mWebTextView.getText();
                             Selection.setSelection(pword, start, end);
                         // If the text entry has created more events, ignore
                         // this one.
                         } else if (msg.arg2 == mTextGeneration) {
-                            mTextEntry.setTextAndKeepSelection(
+                            mWebTextView.setTextAndKeepSelection(
                                     (String) msg.obj);
                         }
                     }
@@ -4679,14 +4920,8 @@
                     if (mNativeClass == 0) {
                         break;
                     }
-// Do not reset the focus or clear the text; the user may have already
-// navigated or entered text at this point. The focus should have gotten 
-// reset, if need be, when the focus cache was built. Similarly, the text
-// view should already be torn down and rebuilt if needed.
-//                    nativeResetFocus();
-//                    clearTextEntry();
-                    HashMap scaleLimit = (HashMap) msg.obj;
-                    int minScale = (Integer) scaleLimit.get("minScale");
+                    ScaleLimitData scaleLimit = (ScaleLimitData) msg.obj;
+                    int minScale = scaleLimit.mMinScale;
                     if (minScale == 0) {
                         mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
                         mMinZoomScaleFixed = false;
@@ -4694,7 +4929,7 @@
                         mMinZoomScale = (float) (minScale / 100.0);
                         mMinZoomScaleFixed = true;
                     }
-                    int maxScale = (Integer) scaleLimit.get("maxScale");
+                    int maxScale = scaleLimit.mMaxScale;
                     if (maxScale == 0) {
                         mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
                     } else {
@@ -4715,6 +4950,7 @@
                     if (mInitialScale > 0) {
                         scale = mInitialScale / 100.0f;
                     } else  {
+                        if (initialScale < 0) break;
                         if (mWebViewCore.getSettings().getUseWideViewPort()) {
                             // force viewSizeChanged by setting mLastWidthSent
                             // to 0
@@ -4731,31 +4967,27 @@
                         }
                     }
                     setNewZoomScale(scale, false);
+                    // As we are on a new page, remove the WebTextView.  This
+                    // is necessary for page loads driven by webkit, and in
+                    // particular when the user was on a password field, so
+                    // the WebTextView was visible.
+                    clearTextEntry();
                     break;
-                case MARK_NODE_INVALID_ID:
-                    nativeMarkNodeInvalid(msg.arg1);
-                    break;
-                case NOTIFY_FOCUS_SET_MSG_ID:
-                    if (mNativeClass != 0) {
-                        nativeNotifyFocusSet(inEditingMode());
+                case MOVE_OUT_OF_PLUGIN:
+                    if (nativePluginEatsNavKey()) {
+                        navHandledKey(msg.arg1, 1, false, 0, true);
                     }
                     break;
                 case UPDATE_TEXT_ENTRY_MSG_ID:
-                    // this is sent after finishing resize in WebViewCore. Make 
+                    // this is sent after finishing resize in WebViewCore. Make
                     // sure the text edit box is still on the  screen.
-                    boolean alreadyThere = inEditingMode();
-                    if (alreadyThere && nativeUpdateFocusNode()) {
-                        FocusNode node = mFocusNode;
-                        if (node.mIsTextField || node.mIsTextArea) {
-                            mTextEntry.bringIntoView();
-                        }
+                    if (inEditingMode() && nativeCursorIsTextInput()) {
+                        mWebTextView.bringIntoView();
+                        rebuildWebTextView();
                     }
-                    updateTextEntry();
                     break;
-                case RECOMPUTE_FOCUS_MSG_ID:
-                    if (mNativeClass != 0) {
-                        nativeRecomputeFocus();
-                    }
+                case CLEAR_TEXT_ENTRY:
+                    clearTextEntry();
                     break;
                 case INVAL_RECT_MSG_ID: {
                     Rect r = (Rect)msg.obj;
@@ -4768,17 +5000,15 @@
                     }
                     break;
                 }
-                case UPDATE_TEXT_ENTRY_ADAPTER:
-                    HashMap data = (HashMap) msg.obj;
-                    if (mTextEntry.isSameTextField(msg.arg1)) {
-                        AutoCompleteAdapter adapter =
-                                (AutoCompleteAdapter) data.get("adapter");
-                        mTextEntry.setAdapterCustom(adapter);
+                case REQUEST_FORM_DATA:
+                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
+                    if (mWebTextView.isSameTextField(msg.arg1)) {
+                        mWebTextView.setAdapterCustom(adapter);
                     }
                     break;
                 case UPDATE_CLIPBOARD:
                     String str = (String) msg.obj;
-                    if (LOGV_ENABLED) {
+                    if (DebugFlags.WEB_VIEW) {
                         Log.v(LOGTAG, "UPDATE_CLIPBOARD " + str);
                     }
                     try {
@@ -4793,12 +5023,12 @@
                     WebViewCore.resumeUpdate(mWebViewCore);
                     break;
 
-                case LONG_PRESS_ENTER:
+                case LONG_PRESS_CENTER:
                     // as this is shared by keydown and trackballdown, reset all
                     // the states
-                    mGotEnterDown = false;
+                    mGotCenterDown = false;
                     mTrackballDown = false;
-                    // LONG_PRESS_ENTER is sent as a delayed message. If we
+                    // LONG_PRESS_CENTER is sent as a delayed message. If we
                     // switch to windows overview, the WebView will be
                     // temporarily removed from the view system. In that case,
                     // do nothing.
@@ -4820,6 +5050,14 @@
                     }
                     break;
 
+                case REQUEST_KEYBOARD:
+                    if (msg.arg1 == 0) {
+                        hideSoftKeyboard();
+                    } else {
+                        displaySoftKeyboard(false);
+                    }
+                    break;
+
                 default:
                     super.handleMessage(msg);
                     break;
@@ -4829,16 +5067,12 @@
 
     // Class used to use a dropdown for a <select> element
     private class InvokeListBox implements Runnable {
-        // Strings for the labels in the listbox.
-        private String[]    mArray;
-        // Array representing whether each item is enabled.
-        private boolean[]   mEnableArray;
         // Whether the listbox allows multiple selection.
         private boolean     mMultiple;
         // Passed in to a list with multiple selection to tell
         // which items are selected.
         private int[]       mSelectedArray;
-        // Passed in to a list with single selection to tell 
+        // Passed in to a list with single selection to tell
         // where the initial selection is.
         private int         mSelection;
 
@@ -4857,14 +5091,14 @@
         }
 
         /**
-         *  Subclass ArrayAdapter so we can disable OptionGroupLabels, 
+         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
          *  and allow filtering.
          */
         private class MyArrayListAdapter extends ArrayAdapter<Container> {
             public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
-                super(context, 
+                super(context,
                             multiple ? com.android.internal.R.layout.select_dialog_multichoice :
-                            com.android.internal.R.layout.select_dialog_singlechoice, 
+                            com.android.internal.R.layout.select_dialog_singlechoice,
                             objects);
             }
 
@@ -4922,7 +5156,7 @@
             }
         }
 
-        private InvokeListBox(String[] array, boolean[] enabled, int 
+        private InvokeListBox(String[] array, boolean[] enabled, int
                 selection) {
             mSelection = selection;
             mMultiple = false;
@@ -4985,31 +5219,36 @@
         public void run() {
             final ListView listView = (ListView) LayoutInflater.from(mContext)
                     .inflate(com.android.internal.R.layout.select_dialog, null);
-            final MyArrayListAdapter adapter = new 
+            final MyArrayListAdapter adapter = new
                     MyArrayListAdapter(mContext, mContainers, mMultiple);
             AlertDialog.Builder b = new AlertDialog.Builder(mContext)
                     .setView(listView).setCancelable(true)
                     .setInverseBackgroundForced(true);
-                    
+
             if (mMultiple) {
                 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int which) {
                         mWebViewCore.sendMessage(
-                                EventHub.LISTBOX_CHOICES, 
+                                EventHub.LISTBOX_CHOICES,
                                 adapter.getCount(), 0,
                                 listView.getCheckedItemPositions());
                     }});
-                b.setNegativeButton(android.R.string.cancel, null);
+                b.setNegativeButton(android.R.string.cancel,
+                        new DialogInterface.OnClickListener() {
+                    public void onClick(DialogInterface dialog, int which) {
+                        mWebViewCore.sendMessage(
+                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
+                }});
             }
             final AlertDialog dialog = b.create();
             listView.setAdapter(adapter);
             listView.setFocusableInTouchMode(true);
             // There is a bug (1250103) where the checks in a ListView with
             // multiple items selected are associated with the positions, not
-            // the ids, so the items do not properly retain their checks when 
+            // the ids, so the items do not properly retain their checks when
             // filtered.  Do not allow filtering on multiple lists until
             // that bug is fixed.
-            
+
             listView.setTextFilterEnabled(!mMultiple);
             if (mMultiple) {
                 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
@@ -5072,48 +5311,40 @@
     }
 
     // called by JNI
-    private void sendFinalFocus(int frame, int node, int x, int y) {
-        WebViewCore.FocusData focusData = new WebViewCore.FocusData();
-        focusData.mFrame = frame;
-        focusData.mNode = node;
-        focusData.mX = x;
-        focusData.mY = y;
-        mWebViewCore.sendMessage(EventHub.SET_FINAL_FOCUS, 
-                EventHub.NO_FOCUS_CHANGE_BLOCK, 0, focusData);
+    private void sendMoveMouse(int frame, int node, int x, int y) {
+        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
+                new WebViewCore.CursorData(frame, node, x, y));
+    }
+
+    /*
+     * Send a mouse move event to the webcore thread.
+     *
+     * @param removeFocus Pass true if the "mouse" cursor is now over a node
+     *                    which wants key events, but it is not the focus. This
+     *                    will make the visual appear as though nothing is in
+     *                    focus.  Remove the WebTextView, if present, and stop
+     *                    drawing the blinking caret.
+     * called by JNI
+     */
+    private void sendMoveMouseIfLatest(boolean removeFocus) {
+        if (removeFocus) {
+            clearTextEntry();
+            setFocusControllerInactive();
+        }
+        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
+                cursorData());
     }
 
     // called by JNI
-    private void setFocusData(int moveGeneration, int buildGeneration,
-            int frame, int node, int x, int y, boolean ignoreNullFocus) {
-        mFocusData.mMoveGeneration = moveGeneration;
-        mFocusData.mBuildGeneration = buildGeneration;
-        mFocusData.mFrame = frame;
-        mFocusData.mNode = node;
-        mFocusData.mX = x;
-        mFocusData.mY = y;
-        mFocusData.mIgnoreNullFocus = ignoreNullFocus;
-    }
-    
-    // called by JNI
-    private void sendKitFocus() {
-        WebViewCore.FocusData focusData = new WebViewCore.FocusData(mFocusData);
-        mWebViewCore.sendMessage(EventHub.SET_KIT_FOCUS, focusData);
-    }
-
-    // called by JNI
-    private void sendMotionUp(int touchGeneration, int buildGeneration,
-            int frame, int node, int x, int y, int size, boolean isClick,
-            boolean retry) {
+    private void sendMotionUp(int touchGeneration,
+            int frame, int node, int x, int y, int size) {
         WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
         touchUpData.mMoveGeneration = touchGeneration;
-        touchUpData.mBuildGeneration = buildGeneration;
         touchUpData.mSize = size;
-        touchUpData.mIsClick = isClick;
-        touchUpData.mRetry = retry;
-        mFocusData.mFrame = touchUpData.mFrame = frame;
-        mFocusData.mNode = touchUpData.mNode = node;
-        mFocusData.mX = touchUpData.mX = x;
-        mFocusData.mY = touchUpData.mY = y;
+        touchUpData.mFrame = frame;
+        touchUpData.mNode = node;
+        touchUpData.mX = x;
+        touchUpData.mY = y;
         mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
     }
 
@@ -5152,56 +5383,72 @@
     private void viewInvalidate() {
         invalidate();
     }
-    
+
     // return true if the key was handled
-    private boolean navHandledKey(int keyCode, int count, boolean noScroll
-            , long time) {
+    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
+            long time, boolean ignorePlugin) {
         if (mNativeClass == 0) {
             return false;
         }
-        mLastFocusTime = time;
-        mLastFocusBounds = nativeGetFocusRingBounds();
-        boolean keyHandled = nativeMoveFocus(keyCode, count, noScroll) == false;
-        if (LOGV_ENABLED) {
-            Log.v(LOGTAG, "navHandledKey mLastFocusBounds=" + mLastFocusBounds
-                    + " mLastFocusTime=" + mLastFocusTime
+        if (ignorePlugin == false && nativePluginEatsNavKey()) {
+            KeyEvent event = new KeyEvent(time, time, KeyEvent.ACTION_DOWN
+                , keyCode, count, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
+                | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
+                | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
+                , 0, 0, 0);
+            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
+            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
+            return true;
+        }
+        mLastCursorTime = time;
+        mLastCursorBounds = nativeGetCursorRingBounds();
+        boolean keyHandled
+                = nativeMoveCursor(keyCode, count, noScroll) == false;
+        if (DebugFlags.WEB_VIEW) {
+            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
+                    + " mLastCursorTime=" + mLastCursorTime
                     + " handled=" + keyHandled);
         }
         if (keyHandled == false || mHeightCanMeasure == false) {
             return keyHandled;
         }
-        Rect contentFocus = nativeGetFocusRingBounds();
-        if (contentFocus.isEmpty()) return keyHandled;
-        Rect viewFocus = contentToView(contentFocus);
+        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
+        if (contentCursorRingBounds.isEmpty()) return keyHandled;
+        Rect viewCursorRingBounds = contentToView(contentCursorRingBounds);
         Rect visRect = new Rect();
         calcOurVisibleRect(visRect);
         Rect outset = new Rect(visRect);
         int maxXScroll = visRect.width() / 2;
         int maxYScroll = visRect.height() / 2;
         outset.inset(-maxXScroll, -maxYScroll);
-        if (Rect.intersects(outset, viewFocus) == false) {
+        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
             return keyHandled;
         }
         // FIXME: Necessary because ScrollView/ListView do not scroll left/right
-        int maxH = Math.min(viewFocus.right - visRect.right, maxXScroll);
+        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
+                maxXScroll);
         if (maxH > 0) {
             pinScrollBy(maxH, 0, true, 0);
         } else {
-            maxH = Math.max(viewFocus.left - visRect.left, -maxXScroll);
+            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
+                    -maxXScroll);
             if (maxH < 0) {
                 pinScrollBy(maxH, 0, true, 0);
             }
         }
-        if (mLastFocusBounds.isEmpty()) return keyHandled;
-        if (mLastFocusBounds.equals(contentFocus)) return keyHandled;
-        if (LOGV_ENABLED) {
-            Log.v(LOGTAG, "navHandledKey contentFocus=" + contentFocus);
+        if (mLastCursorBounds.isEmpty()) return keyHandled;
+        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
+            return keyHandled;
         }
-        requestRectangleOnScreen(viewFocus);
+        if (DebugFlags.WEB_VIEW) {
+            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
+                    + contentCursorRingBounds);
+        }
+        requestRectangleOnScreen(viewCursorRingBounds);
         mUserScroll = true;
         return keyHandled;
     }
-    
+
     /**
      * Set the background color. It's white by default. Pass
      * zero to make the view transparent.
@@ -5216,7 +5463,7 @@
         nativeDebugDump();
         mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
     }
-    
+
     /**
      *  Update our cache with updatedText.
      *  @param updatedText  The new text to put in our cache.
@@ -5226,52 +5473,73 @@
         // we recognize that it is up to date.
         nativeUpdateCachedTextfield(updatedText, mTextGeneration);
     }
-    
-    // Never call this version except by updateCachedTextfield(String) -
-    // we always want to pass in our generation number.
-    private native void     nativeUpdateCachedTextfield(String updatedText, 
-            int generation);
-    private native void     nativeClearFocus(int x, int y);
+
+    /* package */ native void nativeClearCursor();
     private native void     nativeCreate(int ptr);
+    private native int      nativeCursorFramePointer();
+    private native Rect     nativeCursorNodeBounds();
+    /* package */ native int nativeCursorNodePointer();
+    /* package */ native boolean nativeCursorMatchesFocus();
+    private native boolean  nativeCursorIntersects(Rect visibleRect);
+    private native boolean  nativeCursorIsAnchor();
+    private native boolean  nativeCursorIsPlugin();
+    private native boolean  nativeCursorIsTextInput();
+    private native Point    nativeCursorPosition();
+    private native String   nativeCursorText();
+    /**
+     * Returns true if the native cursor node says it wants to handle key events
+     * (ala plugins). This can only be called if mNativeClass is non-zero!
+     */
+    private native boolean  nativeCursorWantsKeyEvents();
     private native void     nativeDebugDump();
     private native void     nativeDestroy();
-    private native void     nativeDrawFocusRing(Canvas content);
+    private native void     nativeDrawCursorRing(Canvas content);
+    private native void     nativeDrawMatches(Canvas canvas);
     private native void     nativeDrawSelection(Canvas content
             , int x, int y, boolean extendSelection);
     private native void     nativeDrawSelectionRegion(Canvas content);
-    private native boolean  nativeUpdateFocusNode();
-    private native Rect     nativeGetFocusRingBounds();
-    private native Rect     nativeGetNavBounds();
+    private native void     nativeDumpDisplayTree(String urlOrNull);
+    private native int      nativeFindAll(String findLower, String findUpper);
+    private native void     nativeFindNext(boolean forward);
+    private native boolean  nativeFocusCandidateIsPassword();
+    private native boolean  nativeFocusCandidateIsRtlText();
+    private native boolean  nativeFocusCandidateIsTextField();
+    private native boolean  nativeFocusCandidateIsTextInput();
+    private native int      nativeFocusCandidateMaxLength();
+    /* package */ native String   nativeFocusCandidateName();
+    private native Rect     nativeFocusCandidateNodeBounds();
+    /* package */ native int nativeFocusCandidatePointer();
+    private native String   nativeFocusCandidateText();
+    private native int      nativeFocusCandidateTextSize();
+    /* package */ native int nativeFocusNodePointer();
+    private native Rect     nativeGetCursorRingBounds();
+    private native Region   nativeGetSelection();
+    private native boolean  nativeHasCursorNode();
+    private native boolean  nativeHasFocusNode();
+    private native void     nativeHideCursor();
+    private native String   nativeImageURI(int x, int y);
     private native void     nativeInstrumentReport();
-    private native void     nativeMarkNodeInvalid(int node);
     // return true if the page has been scrolled
-    private native boolean  nativeMotionUp(int x, int y, int slop, boolean isClick);
+    private native boolean  nativeMotionUp(int x, int y, int slop);
     // returns false if it handled the key
-    private native boolean  nativeMoveFocus(int keyCode, int count, 
+    private native boolean  nativeMoveCursor(int keyCode, int count,
             boolean noScroll);
-    private native void     nativeNotifyFocusSet(boolean inEditingMode);
-    private native void     nativeRecomputeFocus();
+    private native int      nativeMoveGeneration();
+    private native void     nativeMoveSelection(int x, int y,
+            boolean extendSelection);
+    private native boolean  nativePluginEatsNavKey();
     // Like many other of our native methods, you must make sure that
     // mNativeClass is not null before calling this method.
     private native void     nativeRecordButtons(boolean focused,
             boolean pressed, boolean invalidate);
-    private native void     nativeResetFocus();
-    private native void     nativeResetNavClipBounds();
     private native void     nativeSelectBestAt(Rect rect);
     private native void     nativeSetFindIsDown();
     private native void     nativeSetFollowedLink(boolean followed);
     private native void     nativeSetHeightCanMeasure(boolean measure);
-    private native void     nativeSetNavBounds(Rect rect);
-    private native void     nativeSetNavClipBounds(Rect rect);
-    private native String   nativeImageURI(int x, int y);
-    /**
-     * Returns true if the native focus nodes says it wants to handle key events
-     * (ala plugins). This can only be called if mNativeClass is non-zero!
-     */
-    private native boolean  nativeFocusNodeWantsKeyEvents();
-    private native void     nativeMoveSelection(int x, int y
-            , boolean extendSelection);
-    private native Region   nativeGetSelection();
-
-    private native void nativeDumpDisplayTree(String urlOrNull);
+    private native int      nativeTextGeneration();
+    // Never call this version except by updateCachedTextfield(String) -
+    // we always want to pass in our generation number.
+    private native void     nativeUpdateCachedTextfield(String updatedText,
+            int generation);
+    private native void     nativeUpdatePluginReceivesEvents();
 }
diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java
index a5fa41e..4993fcf 100644
--- a/core/java/android/webkit/WebViewCore.java
+++ b/core/java/android/webkit/WebViewCore.java
@@ -32,17 +32,16 @@
 import android.util.Log;
 import android.util.SparseBooleanArray;
 import android.view.KeyEvent;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
 
 import java.util.ArrayList;
-import java.util.HashMap;
 
 import junit.framework.Assert;
 
 final class WebViewCore {
 
     private static final String LOGTAG = "webcore";
-    static final boolean DEBUG = false;
-    static final boolean LOGV_ENABLED = DEBUG;
 
     static {
         // Load libwebcore during static initialization. This happens in the
@@ -96,7 +95,7 @@
     private int mViewportMaximumScale = 0;
 
     private boolean mViewportUserScalable = true;
-    
+
     private int mRestoredScale = WebView.DEFAULT_SCALE_PERCENT;
     private int mRestoredX = 0;
     private int mRestoredY = 0;
@@ -143,6 +142,8 @@
         // The WebIconDatabase needs to be initialized within the UI thread so
         // just request the instance here.
         WebIconDatabase.getInstance();
+        // Create the WebStorage singleton
+        WebStorage.getInstance();
         // Send a message to initialize the WebViewCore.
         Message init = sWebCoreHandler.obtainMessage(
                 WebCoreThread.INITIALIZE, this);
@@ -162,6 +163,8 @@
         mSettings.syncSettingsAndCreateHandler(mBrowserFrame);
         // Create the handler and transfer messages for the IconDatabase
         WebIconDatabase.getInstance().createHandler();
+        // Create the handler for WebStorage
+        WebStorage.getInstance().createHandler();
         // The transferMessages call will transfer all pending messages to the
         // WebCore thread handler.
         mEventHub.transferMessages();
@@ -225,6 +228,16 @@
     }
 
     /**
+     * Add an error message to the client's console.
+     * @param message The message to add
+     * @param lineNumber the line on which the error occurred
+     * @param sourceID the filename of the source that caused the error.
+     */
+    protected void addMessageToConsole(String message, int lineNumber, String sourceID) {
+        mCallbackProxy.addMessageToConsole(message, lineNumber, sourceID);
+    }
+
+    /**
      * Invoke a javascript alert.
      * @param message The message displayed in the alert.
      */
@@ -233,6 +246,27 @@
     }
 
     /**
+     * Notify the user that the origin has exceeded it's database quota.
+     * @param url The URL that caused the overflow.
+     * @param databaseIdentifier The identifier of the database.
+     * @param currentQuota The current quota for the origin.
+     */
+    protected void exceededDatabaseQuota(String url,
+                                         String databaseIdentifier,
+                                         long currentQuota) {
+        // Inform the callback proxy of the quota overflow. Send an object
+        // that encapsulates a call to the nativeSetDatabaseQuota method to
+        // awaken the sleeping webcore thread when a decision from the
+        // client to allow or deny quota is available.
+        mCallbackProxy.onExceededDatabaseQuota(url, databaseIdentifier,
+                currentQuota, new WebStorage.QuotaUpdater() {
+                                  public void updateQuota(long quota) {
+                                      nativeSetDatabaseQuota(quota);
+                                  }
+                              });
+    }
+
+    /**
      * Invoke a javascript confirm dialog.
      * @param message The message displayed in the dialog.
      * @return True if the user confirmed or false if the user cancelled.
@@ -277,31 +311,36 @@
     // JNI methods
     //-------------------------------------------------------------------------
 
-    static native String nativeFindAddress(String addr);
+    static native String nativeFindAddress(String addr, boolean caseInsensitive);
 
     /**
      * Empty the picture set.
      */
     private native void nativeClearContent();
-    
+
     /**
      * Create a flat picture from the set of pictures.
      */
     private native void nativeCopyContentToPicture(Picture picture);
-   
+
     /**
      * Draw the picture set with a background color. Returns true
-     * if some individual picture took too long to draw and can be 
+     * if some individual picture took too long to draw and can be
      * split into parts. Called from the UI thread.
      */
     private native boolean nativeDrawContent(Canvas canvas, int color);
-    
+
+    /**
+     * check to see if picture is blank and in progress
+     */
+    private native boolean nativePictureReady();
+
     /**
      * Redraw a portion of the picture set. The Point wh returns the
      * width and height of the overall picture.
      */
     private native boolean nativeRecordContent(Region invalRegion, Point wh);
-    
+
     /**
      * Splits slow parts of the picture set. Called from the webkit
      * thread after nativeDrawContent returns true.
@@ -309,9 +348,10 @@
     private native void nativeSplitContent();
 
     private native boolean nativeKey(int keyCode, int unichar,
-            int repeatCount, boolean isShift, boolean isAlt, boolean isDown);
+            int repeatCount, boolean isShift, boolean isAlt, boolean isSym,
+            boolean isDown);
 
-    private native boolean nativeClick();
+    private native void nativeClick(int framePtr, int nodePtr);
 
     private native void nativeSendListBoxChoices(boolean[] choices, int size);
 
@@ -329,60 +369,59 @@
             float scale, int realScreenWidth, int screenHeight);
 
     private native int nativeGetContentMinPrefWidth();
-    
-    // Start: functions that deal with text editing
-    private native void nativeReplaceTextfieldText(int frame, int node, int x, 
-            int y, int oldStart, int oldEnd, String replace, int newStart, 
-            int newEnd);
 
-    private native void passToJs(int frame, int node, int x, int y, int gen,
+    // Start: functions that deal with text editing
+    private native void nativeReplaceTextfieldText(
+            int oldStart, int oldEnd, String replace, int newStart, int newEnd,
+            int textGeneration);
+
+    private native void passToJs(int gen,
             String currentText, int keyCode, int keyValue, boolean down,
             boolean cap, boolean fn, boolean sym);
 
+    private native void nativeSetFocusControllerActive(boolean active);
+
     private native void nativeSaveDocumentState(int frame);
 
-    private native void nativeSetFinalFocus(int framePtr, int nodePtr, int x,
-            int y, boolean block);
+    private native void nativeMoveMouse(int framePtr, int x, int y);
 
-    private native void nativeSetKitFocus(int moveGeneration,
-            int buildGeneration, int framePtr, int nodePtr, int x, int y,
-            boolean ignoreNullFocus);
+    private native void nativeMoveMouseIfLatest(int moveGeneration,
+            int framePtr, int x, int y);
 
     private native String nativeRetrieveHref(int framePtr, int nodePtr);
-    
-    private native void nativeTouchUp(int touchGeneration, 
-            int buildGeneration, int framePtr, int nodePtr, int x, int y, 
-            int size, boolean isClick, boolean retry);
+
+    private native void nativeTouchUp(int touchGeneration,
+            int framePtr, int nodePtr, int x, int y,
+            int size);
 
     private native boolean nativeHandleTouchEvent(int action, int x, int y);
 
-    private native void nativeUnblockFocus();
-    
     private native void nativeUpdateFrameCache();
-    
+
     private native void nativeSetSnapAnchor(int x, int y);
-    
+
     private native void nativeSnapToAnchor();
-    
+
     private native void nativeSetBackgroundColor(int color);
-    
+
     private native void nativeDumpDomTree(boolean useFile);
 
     private native void nativeDumpRenderTree(boolean useFile);
 
     private native void nativeDumpNavTree();
 
-    private native void nativeRefreshPlugins(boolean reloadOpenPages);
-    
+    private native void nativeSetJsFlags(String flags);
+
     /**
      *  Delete text from start to end in the focused textfield. If there is no
-     *  focus, or if start == end, silently fail.  If start and end are out of 
+     *  focus, or if start == end, silently fail.  If start and end are out of
      *  order, swap them.
      *  @param  start   Beginning of selection to delete.
      *  @param  end     End of selection to delete.
+     *  @param  textGeneration Text generation number when delete was pressed.
      */
-    private native void nativeDeleteSelection(int frame, int node, int x, int y,
-        int start, int end);
+    private native void nativeDeleteSelection(int start, int end,
+            int textGeneration);
 
     /**
      *  Set the selection to (start, end) in the focused textfield. If start and
@@ -390,15 +429,24 @@
      *  @param  start   Beginning of selection.
      *  @param  end     End of selection.
      */
-    private native void nativeSetSelection(int frame, int node, int x, int y,
-        int start, int end);
+    private native void nativeSetSelection(int start, int end);
 
     private native String nativeGetSelection(Region sel);
-    
+
     // Register a scheme to be treated as local scheme so that it can access
     // local asset files for resources
     private native void nativeRegisterURLSchemeAsLocal(String scheme);
 
+    /*
+     * Inform webcore that the user has decided whether to allow or deny new
+     * quota for the current origin and that the main thread should wake up
+     * now.
+     * @param quota The new quota.
+     */
+    private native void nativeSetDatabaseQuota(long quota);
+
+    private native void nativeUpdatePluginState(int framePtr, int nodePtr, int state);
+
     // EventHub for processing messages
     private final EventHub mEventHub;
     // WebCore thread handler
@@ -447,7 +495,7 @@
                                     CacheManager.endCacheTransaction();
                                     CacheManager.startCacheTransaction();
                                     sendMessageDelayed(
-                                            obtainMessage(CACHE_TICKER), 
+                                            obtainMessage(CACHE_TICKER),
                                             CACHE_TICKER_INTERVAL);
                                 }
                                 break;
@@ -472,36 +520,62 @@
         }
     }
 
-    static class FocusData {
-        FocusData() {}
-        FocusData(FocusData d) {
-            mMoveGeneration = d.mMoveGeneration;
-            mBuildGeneration = d.mBuildGeneration;
-            mFrame = d.mFrame;
-            mNode = d.mNode;
-            mX = d.mX;
-            mY = d.mY;
-            mIgnoreNullFocus = d.mIgnoreNullFocus;
+    static class BaseUrlData {
+        String mBaseUrl;
+        String mData;
+        String mMimeType;
+        String mEncoding;
+        String mFailUrl;
+    }
+
+    static class CursorData {
+        CursorData() {}
+        CursorData(int frame, int node, int x, int y) {
+            mFrame = frame;
+            mX = x;
+            mY = y;
         }
         int mMoveGeneration;
-        int mBuildGeneration;
         int mFrame;
-        int mNode;
         int mX;
         int mY;
-        boolean mIgnoreNullFocus;
+    }
+
+    static class JSInterfaceData {
+        Object mObject;
+        String mInterfaceName;
+    }
+
+    static class JSKeyData {
+        String mCurrentText;
+        KeyEvent mEvent;
+    }
+
+    static class PostUrlData {
+        String mUrl;
+        byte[] mPostData;
+    }
+
+    static class DeleteSelectionData {
+        int mStart;
+        int mEnd;
+        int mTextGeneration;
+    }
+
+    static class ReplaceTextData {
+        String mReplace;
+        int mNewStart;
+        int mNewEnd;
+        int mTextGeneration;
     }
 
     static class TouchUpData {
         int mMoveGeneration;
-        int mBuildGeneration;
         int mFrame;
         int mNode;
         int mX;
         int mY;
         int mSize;
-        boolean mIsClick;
-        boolean mRetry;
     }
 
     static class TouchEventData {
@@ -510,7 +584,14 @@
         int mY;
     }
 
+    static class PluginStateData {
+        int mFrame;
+        int mNode;
+        int mState;
+    }
+
         static final String[] HandlerDebugString = {
+            "SCROLL_TEXT_INPUT", // = 99
             "LOAD_URL", // = 100;
             "STOP_LOADING", // = 101;
             "RELOAD", // = 102;
@@ -536,29 +617,32 @@
             "DELETE_SELECTION", // = 122;
             "LISTBOX_CHOICES", // = 123;
             "SINGLE_LISTBOX_CHOICE", // = 124;
-            "125",
+            "MESSAGE_RELAY", // = 125;
             "SET_BACKGROUND_COLOR", // = 126;
-            "UNBLOCK_FOCUS", // = 127;
+            "PLUGIN_STATE", // = 127;
             "SAVE_DOCUMENT_STATE", // = 128;
             "GET_SELECTION", // = 129;
             "WEBKIT_DRAW", // = 130;
             "SYNC_SCROLL", // = 131;
-            "REFRESH_PLUGINS", // = 132;
-            // this will replace REFRESH_PLUGINS in the next release
-            "POST_URL", // = 142;
+            "POST_URL", // = 132;
             "SPLIT_PICTURE_SET", // = 133;
             "CLEAR_CONTENT", // = 134;
-            "SET_FINAL_FOCUS", // = 135;
-            "SET_KIT_FOCUS", // = 136;
-            "REQUEST_FOCUS_HREF", // = 137;
+            "SET_MOVE_MOUSE", // = 135;
+            "SET_MOVE_MOUSE_IF_LATEST", // = 136;
+            "REQUEST_CURSOR_HREF", // = 137;
             "ADD_JS_INTERFACE", // = 138;
             "LOAD_DATA", // = 139;
             "TOUCH_UP", // = 140;
             "TOUCH_EVENT", // = 141;
+            "SET_ACTIVE", // = 142;
+            "ON_PAUSE",     // = 143
+            "ON_RESUME",    // = 144
+            "FREE_MEMORY",  // = 145
         };
 
     class EventHub {
         // Message Ids
+        static final int SCROLL_TEXT_INPUT = 99;
         static final int LOAD_URL = 100;
         static final int STOP_LOADING = 101;
         static final int RELOAD = 102;
@@ -584,22 +668,21 @@
         static final int DELETE_SELECTION = 122;
         static final int LISTBOX_CHOICES = 123;
         static final int SINGLE_LISTBOX_CHOICE = 124;
+        static final int MESSAGE_RELAY = 125;
         static final int SET_BACKGROUND_COLOR = 126;
-        static final int UNBLOCK_FOCUS = 127;
+        static final int PLUGIN_STATE = 127; // plugin notifications
         static final int SAVE_DOCUMENT_STATE = 128;
         static final int GET_SELECTION = 129;
         static final int WEBKIT_DRAW = 130;
         static final int SYNC_SCROLL = 131;
-        static final int REFRESH_PLUGINS = 132;
-        // this will replace REFRESH_PLUGINS in the next release
-        static final int POST_URL = 142;
+        static final int POST_URL = 132;
         static final int SPLIT_PICTURE_SET = 133;
         static final int CLEAR_CONTENT = 134;
-        
+
         // UI nav messages
-        static final int SET_FINAL_FOCUS = 135;
-        static final int SET_KIT_FOCUS = 136;
-        static final int REQUEST_FOCUS_HREF = 137;
+        static final int SET_MOVE_MOUSE = 135;
+        static final int SET_MOVE_MOUSE_IF_LATEST = 136;
+        static final int REQUEST_CURSOR_HREF = 137;
         static final int ADD_JS_INTERFACE = 138;
         static final int LOAD_DATA = 139;
 
@@ -608,6 +691,17 @@
         // message used to pass UI touch events to WebCore
         static final int TOUCH_EVENT = 141;
 
+        // Used to tell the focus controller not to draw the blinking cursor,
+        // based on whether the WebView has focus and whether the WebView's
+        // cursor matches the webpage's focus.
+        static final int SET_ACTIVE = 142;
+
+        // lifecycle activities for just this DOM (unlike pauseTimers, which
+        // is global)
+        static final int ON_PAUSE = 143;
+        static final int ON_RESUME = 144;
+        static final int FREE_MEMORY = 145;
+
         // Network-based messaging
         static final int CLEAR_SSL_PREF_TABLE = 150;
 
@@ -620,12 +714,10 @@
         static final int DUMP_RENDERTREE = 171;
         static final int DUMP_NAVTREE = 172;
 
+        static final int SET_JS_FLAGS = 173;
+
         // private message ids
         private static final int DESTROY =     200;
-        
-        // flag values passed to message SET_FINAL_FOCUS
-        static final int NO_FOCUS_CHANGE_BLOCK = 0;
-        static final int BLOCK_FOCUS_CHANGE_UNTIL_KEY_UP = 1;
 
         // Private handler for WebCore messages.
         private Handler mHandler;
@@ -654,10 +746,13 @@
             mHandler = new Handler() {
                 @Override
                 public void handleMessage(Message msg) {
-                    if (LOGV_ENABLED) {
-                        Log.v(LOGTAG, msg.what < LOAD_URL || msg.what 
-                                > TOUCH_EVENT ? Integer.toString(msg.what)
-                                : HandlerDebugString[msg.what - LOAD_URL]);
+                    if (DebugFlags.WEB_VIEW_CORE) {
+                        Log.v(LOGTAG, (msg.what < SCROLL_TEXT_INPUT || msg.what
+                                > FREE_MEMORY ? Integer.toString(msg.what)
+                                : HandlerDebugString[msg.what
+                                        - SCROLL_TEXT_INPUT])
+                                + " arg1=" + msg.arg1 + " arg2=" + msg.arg2
+                                + " obj=" + msg.obj);
                     }
                     switch (msg.what) {
                         case WEBKIT_DRAW:
@@ -672,20 +767,22 @@
                             mNativeClass = 0;
                             break;
 
+                        case SCROLL_TEXT_INPUT:
+                            nativeScrollFocusedTextInput(msg.arg1, msg.arg2);
+                            break;
+
                         case LOAD_URL:
                             loadUrl((String) msg.obj);
                             break;
 
                         case POST_URL: {
-                            HashMap param = (HashMap) msg.obj;
-                            String url = (String) param.get("url");
-                            byte[] data = (byte[]) param.get("data");
-                            mBrowserFrame.postUrl(url, data);
+                            PostUrlData param = (PostUrlData) msg.obj;
+                            mBrowserFrame.postUrl(param.mUrl, param.mPostData);
                             break;
                         }
                         case LOAD_DATA:
-                            HashMap loadParams = (HashMap) msg.obj;
-                            String baseUrl = (String) loadParams.get("baseUrl");
+                            BaseUrlData loadParams = (BaseUrlData) msg.obj;
+                            String baseUrl = loadParams.mBaseUrl;
                             if (baseUrl != null) {
                                 int i = baseUrl.indexOf(':');
                                 if (i > 0) {
@@ -698,7 +795,7 @@
                                      * we automatically add the scheme of the
                                      * baseUrl for local access as long as it is
                                      * not http(s)/ftp(s)/about/javascript
-                                     */ 
+                                     */
                                     String scheme = baseUrl.substring(0, i);
                                     if (!scheme.startsWith("http") &&
                                             !scheme.startsWith("ftp") &&
@@ -709,16 +806,16 @@
                                 }
                             }
                             mBrowserFrame.loadData(baseUrl,
-                                    (String) loadParams.get("data"),
-                                    (String) loadParams.get("mimeType"),
-                                    (String) loadParams.get("encoding"),
-                                    (String) loadParams.get("failUrl"));
+                                    loadParams.mData,
+                                    loadParams.mMimeType,
+                                    loadParams.mEncoding,
+                                    loadParams.mFailUrl);
                             break;
 
                         case STOP_LOADING:
-                            // If the WebCore has committed the load, but not 
-                            // finished the first layout yet, we need to set 
-                            // first layout done to trigger the interpreted side sync 
+                            // If the WebCore has committed the load, but not
+                            // finished the first layout yet, we need to set
+                            // first layout done to trigger the interpreted side sync
                             // up with native side
                             if (mBrowserFrame.committed()
                                     && !mBrowserFrame.firstLayoutDone()) {
@@ -741,7 +838,7 @@
                             break;
 
                         case CLICK:
-                            nativeClick();
+                            nativeClick(msg.arg1, msg.arg2);
                             break;
 
                         case VIEW_SIZE_CHANGED:
@@ -752,9 +849,10 @@
                         case SET_SCROLL_OFFSET:
                             // note: these are in document coordinates
                             // (inv-zoom)
-                            nativeSetScrollOffset(msg.arg1, msg.arg2);
+                            Point pt = (Point) msg.obj;
+                            nativeSetScrollOffset(msg.arg1, pt.x, pt.y);
                             break;
-                            
+
                         case SET_GLOBAL_BOUNDS:
                             Rect r = (Rect) msg.obj;
                             nativeSetGlobalBounds(r.left, r.top, r.width(),
@@ -765,7 +863,7 @@
                             // If it is a standard load and the load is not
                             // committed yet, we interpret BACK as RELOAD
                             if (!mBrowserFrame.committed() && msg.arg1 == -1 &&
-                                    (mBrowserFrame.loadType() == 
+                                    (mBrowserFrame.loadType() ==
                                     BrowserFrame.FRAME_LOADTYPE_STANDARD)) {
                                 mBrowserFrame.reload(true);
                             } else {
@@ -802,6 +900,24 @@
                             }
                             break;
 
+                        case ON_PAUSE:
+                            nativePause();
+                            break;
+
+                        case ON_RESUME:
+                            nativeResume();
+                            break;
+
+                        case FREE_MEMORY:
+                            clearCache(false);
+                            nativeFreeMemory();
+                            break;
+
+                        case PLUGIN_STATE:
+                            PluginStateData psd = (PluginStateData) msg.obj;
+                            nativeUpdatePluginState(psd.mFrame, psd.mNode, psd.mState);
+                            break;
+
                         case SET_NETWORK_STATE:
                             if (BrowserFrame.sJavaBridge == null) {
                                 throw new IllegalStateException("No WebView " +
@@ -812,10 +928,7 @@
                             break;
 
                         case CLEAR_CACHE:
-                            mBrowserFrame.clearCache();
-                            if (msg.arg1 == 1) {
-                                CacheManager.removeAllCacheFiles();
-                            }
+                            clearCache(msg.arg1 == 1);
                             break;
 
                         case CLEAR_HISTORY:
@@ -823,29 +936,21 @@
                                     close(mBrowserFrame.mNativeFrame);
                             break;
 
-                        case REPLACE_TEXT: 
-                            HashMap jMap = (HashMap) msg.obj;
-                            FocusData fData = (FocusData) jMap.get("focusData");
-                            String replace = (String) jMap.get("replace");
-                            int newStart = 
-                                    ((Integer) jMap.get("start")).intValue();
-                            int newEnd = 
-                                    ((Integer) jMap.get("end")).intValue();
-                            nativeReplaceTextfieldText(fData.mFrame,
-                                    fData.mNode, fData.mX, fData.mY, msg.arg1,
-                                    msg.arg2, replace, newStart, newEnd);
+                        case REPLACE_TEXT:
+                            ReplaceTextData rep = (ReplaceTextData) msg.obj;
+                            nativeReplaceTextfieldText(msg.arg1, msg.arg2,
+                                    rep.mReplace, rep.mNewStart, rep.mNewEnd,
+                                    rep.mTextGeneration);
                             break;
 
                         case PASS_TO_JS: {
-                            HashMap jsMap = (HashMap) msg.obj;
-                            FocusData fDat = (FocusData) jsMap.get("focusData");
-                            KeyEvent evt = (KeyEvent) jsMap.get("event");
+                            JSKeyData jsData = (JSKeyData) msg.obj;
+                            KeyEvent evt = jsData.mEvent;
                             int keyCode = evt.getKeyCode();
                             int keyValue = evt.getUnicodeChar();
                             int generation = msg.arg1;
-                            passToJs(fDat.mFrame, fDat.mNode, fDat.mX, fDat.mY,
-                                    generation,
-                                    (String) jsMap.get("currentText"),
+                            passToJs(generation,
+                                    jsData.mCurrentText,
                                     keyCode,
                                     keyValue,
                                     evt.isDown(),
@@ -855,8 +960,8 @@
                         }
 
                         case SAVE_DOCUMENT_STATE: {
-                            FocusData fDat = (FocusData) msg.obj;
-                            nativeSaveDocumentState(fDat.mFrame);
+                            CursorData cDat = (CursorData) msg.obj;
+                            nativeSaveDocumentState(cDat.mFrame);
                             break;
                         }
 
@@ -868,11 +973,9 @@
                         case TOUCH_UP:
                             TouchUpData touchUpData = (TouchUpData) msg.obj;
                             nativeTouchUp(touchUpData.mMoveGeneration,
-                                    touchUpData.mBuildGeneration,
                                     touchUpData.mFrame, touchUpData.mNode,
-                                    touchUpData.mX, touchUpData.mY, 
-                                    touchUpData.mSize, touchUpData.mIsClick,
-                                    touchUpData.mRetry);
+                                    touchUpData.mX, touchUpData.mY,
+                                    touchUpData.mSize);
                             break;
 
                         case TOUCH_EVENT: {
@@ -885,13 +988,14 @@
                             break;
                         }
 
+                        case SET_ACTIVE:
+                            nativeSetFocusControllerActive(msg.arg1 == 1);
+                            break;
+
                         case ADD_JS_INTERFACE:
-                            HashMap map = (HashMap) msg.obj;
-                            Object obj = map.get("object");
-                            String interfaceName = (String)
-                                    map.get("interfaceName");
-                            mBrowserFrame.addJavascriptInterface(obj,
-                                    interfaceName);
+                            JSInterfaceData jsData = (JSInterfaceData) msg.obj;
+                            mBrowserFrame.addJavascriptInterface(jsData.mObject,
+                                    jsData.mInterfaceName);
                             break;
 
                         case REQUEST_EXT_REPRESENTATION:
@@ -903,35 +1007,27 @@
                             mBrowserFrame.documentAsText((Message) msg.obj);
                             break;
 
-                        case SET_FINAL_FOCUS:
-                            FocusData finalData = (FocusData) msg.obj;
-                            nativeSetFinalFocus(finalData.mFrame,
-                                     finalData.mNode, finalData.mX, 
-                                     finalData.mY, msg.arg1 
-                                     != EventHub.NO_FOCUS_CHANGE_BLOCK);
+                        case SET_MOVE_MOUSE:
+                            CursorData cursorData = (CursorData) msg.obj;
+                            nativeMoveMouse(cursorData.mFrame,
+                                     cursorData.mX, cursorData.mY);
                             break;
 
-                        case UNBLOCK_FOCUS:
-                            nativeUnblockFocus();
+                        case SET_MOVE_MOUSE_IF_LATEST:
+                            CursorData cData = (CursorData) msg.obj;
+                            nativeMoveMouseIfLatest(cData.mMoveGeneration,
+                                    cData.mFrame,
+                                    cData.mX, cData.mY);
                             break;
 
-                        case SET_KIT_FOCUS:
-                            FocusData focusData = (FocusData) msg.obj;
-                            nativeSetKitFocus(focusData.mMoveGeneration,
-                                    focusData.mBuildGeneration,
-                                    focusData.mFrame, focusData.mNode,
-                                    focusData.mX, focusData.mY,
-                                    focusData.mIgnoreNullFocus);
-                            break;
-
-                        case REQUEST_FOCUS_HREF: {
+                        case REQUEST_CURSOR_HREF: {
                             Message hrefMsg = (Message) msg.obj;
                             String res = nativeRetrieveHref(msg.arg1, msg.arg2);
                             hrefMsg.getData().putString("url", res);
                             hrefMsg.sendToTarget();
                             break;
                         }
-                            
+
                         case UPDATE_CACHE_AND_TEXT_ENTRY:
                             nativeUpdateFrameCache();
                             // FIXME: this should provide a minimal rectangle
@@ -951,21 +1047,19 @@
                         case SET_SNAP_ANCHOR:
                             nativeSetSnapAnchor(msg.arg1, msg.arg2);
                             break;
-                            
+
                         case DELETE_SELECTION:
-                            FocusData delData = (FocusData) msg.obj;
-                            nativeDeleteSelection(delData.mFrame,
-                                     delData.mNode, delData.mX, 
-                                     delData.mY, msg.arg1, msg.arg2);
+                            DeleteSelectionData deleteSelectionData
+                                    = (DeleteSelectionData) msg.obj;
+                            nativeDeleteSelection(deleteSelectionData.mStart,
+                                    deleteSelectionData.mEnd,
+                                    deleteSelectionData.mTextGeneration);
                             break;
 
                         case SET_SELECTION:
-                            FocusData selData = (FocusData) msg.obj;
-                            nativeSetSelection(selData.mFrame,
-                                     selData.mNode, selData.mX, 
-                                     selData.mY, msg.arg1, msg.arg2);
+                            nativeSetSelection(msg.arg1, msg.arg2);
                             break;
-                            
+
                         case LISTBOX_CHOICES:
                             SparseBooleanArray choices = (SparseBooleanArray)
                                     msg.obj;
@@ -974,18 +1068,18 @@
                             for (int c = 0; c < choicesSize; c++) {
                                 choicesArray[c] = choices.get(c);
                             }
-                            nativeSendListBoxChoices(choicesArray, 
+                            nativeSendListBoxChoices(choicesArray,
                                     choicesSize);
                             break;
 
                         case SINGLE_LISTBOX_CHOICE:
                             nativeSendListBoxChoice(msg.arg1);
                             break;
-                            
+
                         case SET_BACKGROUND_COLOR:
                             nativeSetBackgroundColor(msg.arg1);
                             break;
-                            
+
                         case GET_SELECTION:
                             String str = nativeGetSelection((Region) msg.obj);
                             Message.obtain(mWebView.mPrivateHandler
@@ -1005,26 +1099,32 @@
                             nativeDumpNavTree();
                             break;
 
+                        case SET_JS_FLAGS:
+                            nativeSetJsFlags((String)msg.obj);
+                            break;
+
                         case SYNC_SCROLL:
                             mWebkitScrollX = msg.arg1;
                             mWebkitScrollY = msg.arg2;
                             break;
 
-                        case REFRESH_PLUGINS:
-                            nativeRefreshPlugins(msg.arg1 != 0);
-                            break;
-                            
                         case SPLIT_PICTURE_SET:
                             nativeSplitContent();
                             mSplitPictureIsScheduled = false;
                             break;
-                            
+
                         case CLEAR_CONTENT:
                             // Clear the view so that onDraw() will draw nothing
                             // but white background
                             // (See public method WebView.clearView)
                             nativeClearContent();
                             break;
+
+                        case MESSAGE_RELAY:
+                            if (msg.obj instanceof Message) {
+                                ((Message) msg.obj).sendToTarget();
+                            }
+                            break;
                     }
                 }
             };
@@ -1114,7 +1214,7 @@
     //-------------------------------------------------------------------------
 
     void stopLoading() {
-        if (LOGV_ENABLED) Log.v(LOGTAG, "CORE stopLoading");
+        if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "CORE stopLoading");
         if (mBrowserFrame != null) {
             mBrowserFrame.stopLoading();
         }
@@ -1189,20 +1289,42 @@
     // WebViewCore private methods
     //-------------------------------------------------------------------------
 
+    private void clearCache(boolean includeDiskFiles) {
+        mBrowserFrame.clearCache();
+        if (includeDiskFiles) {
+            CacheManager.removeAllCacheFiles();
+        }
+    }
+
     private void loadUrl(String url) {
-        if (LOGV_ENABLED) Log.v(LOGTAG, " CORE loadUrl " + url);
+        if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, " CORE loadUrl " + url);
         mBrowserFrame.loadUrl(url);
     }
 
     private void key(KeyEvent evt, boolean isDown) {
-        if (LOGV_ENABLED) {
+        if (DebugFlags.WEB_VIEW_CORE) {
             Log.v(LOGTAG, "CORE key at " + System.currentTimeMillis() + ", "
                     + evt);
         }
-        if (!nativeKey(evt.getKeyCode(), evt.getUnicodeChar(),
+        int keyCode = evt.getKeyCode();
+        if (!nativeKey(keyCode, evt.getUnicodeChar(),
                 evt.getRepeatCount(), evt.isShiftPressed(), evt.isAltPressed(),
-                isDown)) {
+                evt.isSymPressed(),
+                isDown) && keyCode != KeyEvent.KEYCODE_ENTER) {
+            if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
+                    && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
+                if (DebugFlags.WEB_VIEW_CORE) {
+                    Log.v(LOGTAG, "key: arrow unused by plugin: " + keyCode);
+                }
+                if (mWebView != null && evt.isDown()) {
+                    Message.obtain(mWebView.mPrivateHandler,
+                            WebView.MOVE_OUT_OF_PLUGIN, keyCode).sendToTarget();
+                }
+                return;
+            }
             // bubble up the event handling
+            // but do not bubble up the ENTER key, which would open the search
+            // bar without any text.
             mCallbackProxy.onUnhandledKeyEvent(evt);
         }
     }
@@ -1213,7 +1335,7 @@
 
     // notify webkit that our virtual view size changed size (after inv-zoom)
     private void viewSizeChanged(int w, int h, float scale) {
-        if (LOGV_ENABLED) Log.v(LOGTAG, "CORE onSizeChanged");
+        if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "CORE onSizeChanged");
         if (w == 0) {
             Log.w(LOGTAG, "skip viewSizeChanged as w is 0");
             return;
@@ -1222,7 +1344,7 @@
                 && (w < mViewportWidth || mViewportWidth == -1)) {
             int width = mViewportWidth;
             if (mViewportWidth == -1) {
-                if (mSettings.getLayoutAlgorithm() == 
+                if (mSettings.getLayoutAlgorithm() ==
                         WebSettings.LayoutAlgorithm.NORMAL) {
                     width = WebView.ZOOM_OUT_WIDTH;
                 } else {
@@ -1253,7 +1375,7 @@
         if (needInvalidate) {
             // ensure {@link #webkitDraw} is called as we were blocking in
             // {@link #contentDraw} when mCurrentViewWidth is 0
-            if (LOGV_ENABLED) Log.v(LOGTAG, "viewSizeChanged");
+            if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "viewSizeChanged");
             contentDraw();
         }
         mEventHub.sendMessage(Message.obtain(null,
@@ -1269,7 +1391,7 @@
 
     // Used to avoid posting more than one draw message.
     private boolean mDrawIsScheduled;
-    
+
     // Used to avoid posting more than one split picture message.
     private boolean mSplitPictureIsScheduled;
 
@@ -1278,7 +1400,7 @@
 
     // Used to end scale+scroll mode, accessed by both threads
     boolean mEndScaleZoom = false;
-    
+
     public class DrawData {
         public DrawData() {
             mInvalRegion = new Region();
@@ -1288,21 +1410,21 @@
         public Point mViewPoint;
         public Point mWidthHeight;
     }
-    
+
     private void webkitDraw() {
         mDrawIsScheduled = false;
         DrawData draw = new DrawData();
-        if (LOGV_ENABLED) Log.v(LOGTAG, "webkitDraw start");
-        if (nativeRecordContent(draw.mInvalRegion, draw.mWidthHeight) 
+        if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "webkitDraw start");
+        if (nativeRecordContent(draw.mInvalRegion, draw.mWidthHeight)
                 == false) {
-            if (LOGV_ENABLED) Log.v(LOGTAG, "webkitDraw abort");
+            if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "webkitDraw abort");
             return;
         }
         if (mWebView != null) {
             // Send the native view size that was used during the most recent
             // layout.
             draw.mViewPoint = new Point(mCurrentViewWidth, mCurrentViewHeight);
-            if (LOGV_ENABLED) Log.v(LOGTAG, "webkitDraw NEW_PICTURE_MSG_ID");
+            if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "webkitDraw NEW_PICTURE_MSG_ID");
             Message.obtain(mWebView.mPrivateHandler,
                     WebView.NEW_PICTURE_MSG_ID, draw).sendToTarget();
             if (mWebkitScrollX != 0 || mWebkitScrollY != 0) {
@@ -1350,6 +1472,10 @@
         }
     }
 
+    /* package */ boolean pictureReady() {
+        return nativePictureReady();
+    }
+
     /*package*/ Picture copyContentPicture() {
         Picture result = new Picture();
         nativeCopyContentToPicture(result);
@@ -1363,9 +1489,9 @@
         sWebCoreHandler.sendMessageAtFrontOfQueue(sWebCoreHandler
                 .obtainMessage(WebCoreThread.REDUCE_PRIORITY));
         // Note: there is one possible failure mode. If pauseUpdate() is called
-        // from UI thread while in webcore thread WEBKIT_DRAW is just pulled out 
-        // of the queue and about to be executed. mDrawIsScheduled may be set to 
-        // false in webkitDraw(). So update won't be blocked. But at least the 
+        // from UI thread while in webcore thread WEBKIT_DRAW is just pulled out
+        // of the queue and about to be executed. mDrawIsScheduled may be set to
+        // false in webkitDraw(). So update won't be blocked. But at least the
         // webcore thread priority is still lowered.
         if (core != null) {
             synchronized (core) {
@@ -1385,7 +1511,7 @@
             synchronized (core) {
                 core.mDrawIsScheduled = false;
                 core.mDrawIsPaused = false;
-                if (LOGV_ENABLED) Log.v(LOGTAG, "resumeUpdate");
+                if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "resumeUpdate");
                 core.contentDraw();
             }
         }
@@ -1434,7 +1560,7 @@
             mEventHub.sendMessage(Message.obtain(null, EventHub.WEBKIT_DRAW));
         }
     }
-    
+
     // called by JNI
     private void contentScrollBy(int dx, int dy, boolean animate) {
         if (!mBrowserFrame.firstLayoutDone()) {
@@ -1442,9 +1568,14 @@
             return;
         }
         if (mWebView != null) {
-            Message.obtain(mWebView.mPrivateHandler,
-                    WebView.SCROLL_BY_MSG_ID, dx, dy, 
-                    new Boolean(animate)).sendToTarget();
+            Message msg = Message.obtain(mWebView.mPrivateHandler,
+                    WebView.SCROLL_BY_MSG_ID, dx, dy, new Boolean(animate));
+            if (mDrawIsScheduled) {
+                mEventHub.sendMessage(Message.obtain(null,
+                        EventHub.MESSAGE_RELAY, msg));
+            } else {
+                msg.sendToTarget();
+            }
         }
     }
 
@@ -1461,8 +1592,14 @@
             return;
         }
         if (mWebView != null) {
-            Message.obtain(mWebView.mPrivateHandler,
-                    WebView.SCROLL_TO_MSG_ID, x, y).sendToTarget();
+            Message msg = Message.obtain(mWebView.mPrivateHandler,
+                    WebView.SCROLL_TO_MSG_ID, x, y);
+            if (mDrawIsScheduled) {
+                mEventHub.sendMessage(Message.obtain(null,
+                        EventHub.MESSAGE_RELAY, msg));
+            } else {
+                msg.sendToTarget();
+            }
         }
     }
 
@@ -1479,24 +1616,14 @@
             return;
         }
         if (mWebView != null) {
-            Message.obtain(mWebView.mPrivateHandler,
-                    WebView.SPAWN_SCROLL_TO_MSG_ID, x, y).sendToTarget();
-        }
-    }
-
-    // called by JNI
-    private void sendMarkNodeInvalid(int node) {
-        if (mWebView != null) {
-            Message.obtain(mWebView.mPrivateHandler,
-                    WebView.MARK_NODE_INVALID_ID, node, 0).sendToTarget();
-        }
-    }
-
-    // called by JNI
-    private void sendNotifyFocusSet() {
-        if (mWebView != null) {
-            Message.obtain(mWebView.mPrivateHandler,
-                    WebView.NOTIFY_FOCUS_SET_MSG_ID).sendToTarget();
+            Message msg = Message.obtain(mWebView.mPrivateHandler,
+                    WebView.SPAWN_SCROLL_TO_MSG_ID, x, y);
+            if (mDrawIsScheduled) {
+                mEventHub.sendMessage(Message.obtain(null,
+                        EventHub.MESSAGE_RELAY, msg));
+            } else {
+                msg.sendToTarget();
+            }
         }
     }
 
@@ -1511,14 +1638,6 @@
         contentDraw();
     }
 
-    // called by JNI
-    private void sendRecomputeFocus() {
-        if (mWebView != null) {
-            Message.obtain(mWebView.mPrivateHandler,
-                    WebView.RECOMPUTE_FOCUS_MSG_ID).sendToTarget();
-        }
-    }
-
     /*  Called by JNI. The coordinates are in doc coordinates, so they need to
         be scaled before they can be used by the view system, which happens
         in WebView since it (and its thread) know the current scale factor.
@@ -1536,12 +1655,12 @@
     }
 
     private native void setViewportSettingsFromNative();
-    
+
     // called by JNI
-    private void didFirstLayout() {
+    private void didFirstLayout(boolean standardLoad) {
         // Trick to ensure that the Picture has the exact height for the content
         // by forcing to layout with 0 height after the page is ready, which is
-        // indicated by didFirstLayout. This is essential to get rid of the 
+        // indicated by didFirstLayout. This is essential to get rid of the
         // white space in the GMail which uses WebView for message view.
         if (mWebView != null && mWebView.mHeightCanMeasure) {
             mWebView.mLastHeightSent = 0;
@@ -1609,9 +1728,9 @@
 
         // now notify webview
         if (mWebView != null) {
-            HashMap scaleLimit = new HashMap();
-            scaleLimit.put("minScale", mViewportMinimumScale);
-            scaleLimit.put("maxScale", mViewportMaximumScale);
+            WebView.ScaleLimitData scaleLimit = new WebView.ScaleLimitData();
+            scaleLimit.mMinScale = mViewportMinimumScale;
+            scaleLimit.mMaxScale = mViewportMaximumScale;
 
             if (mRestoredScale > 0) {
                 Message.obtain(mWebView.mPrivateHandler,
@@ -1619,16 +1738,14 @@
                         scaleLimit).sendToTarget();
                 mRestoredScale = 0;
             } else {
+                // if standardLoad is true, use mViewportInitialScale, otherwise
+                // pass -1 to the WebView to indicate no change of the scale.
                 Message.obtain(mWebView.mPrivateHandler,
-                        WebView.DID_FIRST_LAYOUT_MSG_ID, mViewportInitialScale,
+                        WebView.DID_FIRST_LAYOUT_MSG_ID,
+                        standardLoad ? mViewportInitialScale : -1,
                         mViewportWidth, scaleLimit).sendToTarget();
             }
 
-            // if no restored offset, move the new page to (0, 0)
-            Message.obtain(mWebView.mPrivateHandler, WebView.SCROLL_TO_MSG_ID,
-                    mRestoredX, mRestoredY).sendToTarget();
-            mRestoredX = mRestoredY = 0;
-
             // force an early draw for quick feedback after the first layout
             if (mCurrentViewWidth != 0) {
                 synchronized (this) {
@@ -1636,10 +1753,19 @@
                         mEventHub.removeMessages(EventHub.WEBKIT_DRAW);
                     }
                     mDrawIsScheduled = true;
+                    // if no restored offset, move the new page to (0, 0)
+                    mEventHub.sendMessageAtFrontOfQueue(Message.obtain(null,
+                            EventHub.MESSAGE_RELAY, Message.obtain(
+                                    mWebView.mPrivateHandler,
+                                    WebView.SCROLL_TO_MSG_ID, mRestoredX,
+                                    mRestoredY)));
                     mEventHub.sendMessageAtFrontOfQueue(Message.obtain(null,
                             EventHub.WEBKIT_DRAW));
                 }
             }
+
+            // reset restored offset
+            mRestoredX = mRestoredY = 0;
         }
     }
 
@@ -1664,15 +1790,27 @@
             String text, int textGeneration) {
         if (mWebView != null) {
             Message msg = Message.obtain(mWebView.mPrivateHandler,
-                    WebView.UPDATE_TEXTFIELD_TEXT_MSG_ID, ptr, 
+                    WebView.UPDATE_TEXTFIELD_TEXT_MSG_ID, ptr,
                     textGeneration, text);
             msg.getData().putBoolean("password", changeToPassword);
             msg.sendToTarget();
         }
     }
 
+    // called by JNI
+    private void clearTextEntry() {
+        if (mWebView == null) return;
+        Message.obtain(mWebView.mPrivateHandler,
+                WebView.CLEAR_TEXT_ENTRY).sendToTarget();
+    }
+
+    /**
+     * Scroll the focused textfield to (x, y) in document space
+     */
+    private native void nativeScrollFocusedTextInput(int x, int y);
+
     // these must be in document space (i.e. not scaled/zoomed).
-    private native void nativeSetScrollOffset(int dx, int dy);
+    private native void nativeSetScrollOffset(int gen, int dx, int dy);
 
     private native void nativeSetGlobalBounds(int x, int y, int w, int h);
 
@@ -1690,6 +1828,89 @@
         if (mWebView != null) {
             mWebView.requestListBox(array, enabledArray, selection);
         }
-        
+
     }
+
+    // called by JNI
+    private void requestKeyboard(boolean showKeyboard) {
+        if (mWebView != null) {
+            Message.obtain(mWebView.mPrivateHandler,
+                    WebView.REQUEST_KEYBOARD, showKeyboard ? 1 : 0, 0)
+                    .sendToTarget();
+        }
+    }
+
+    // This class looks like a SurfaceView to native code. In java, we can
+    // assume the passed in SurfaceView is this class so we can talk to the
+    // ViewManager through the ChildView.
+    private class SurfaceViewProxy extends SurfaceView
+            implements SurfaceHolder.Callback {
+        private final ViewManager.ChildView mChildView;
+        private int mPointer;
+        SurfaceViewProxy(Context context, ViewManager.ChildView childView,
+                int pointer) {
+            super(context);
+            setWillNotDraw(false); // this prevents the black box artifact
+            getHolder().addCallback(this);
+            mChildView = childView;
+            mChildView.mView = this;
+            mPointer = pointer;
+        }
+        void destroy() {
+            mPointer = 0;
+            mChildView.removeView();
+        }
+        void attach(int x, int y, int width, int height) {
+            mChildView.attachView(x, y, width, height);
+        }
+
+        // SurfaceHolder.Callback methods
+        public void surfaceCreated(SurfaceHolder holder) {
+            if (mPointer != 0) {
+                nativeSurfaceChanged(mPointer, 0, 0, 0, 0);
+            }
+        }
+        public void surfaceChanged(SurfaceHolder holder, int format, int width,
+                int height) {
+            if (mPointer != 0) {
+                nativeSurfaceChanged(mPointer, 1, format, width, height);
+            }
+        }
+        public void surfaceDestroyed(SurfaceHolder holder) {
+            if (mPointer != 0) {
+                nativeSurfaceChanged(mPointer, 2, 0, 0, 0);
+            }
+        }
+    }
+
+    // PluginWidget functions for mainting SurfaceViews for the Surface drawing
+    // model.
+    private SurfaceView createSurface(int nativePointer) {
+        if (mWebView == null) {
+            return null;
+        }
+        return new SurfaceViewProxy(mContext,
+                mWebView.mViewManager.createView(), nativePointer);
+    }
+
+    private void destroySurface(SurfaceView surface) {
+        SurfaceViewProxy proxy = (SurfaceViewProxy) surface;
+        proxy.destroy();
+    }
+
+    private void attachSurface(SurfaceView surface, int x, int y,
+            int width, int height) {
+        SurfaceViewProxy proxy = (SurfaceViewProxy) surface;
+        proxy.attach(x, y, width, height);
+    }
+
+    // Callback for the SurfaceHolder.Callback. Called for all the surface
+    // callbacks. The state parameter is one of Created(0), Changed(1),
+    // Destroyed(2).
+    private native void nativeSurfaceChanged(int pointer, int state, int format,
+            int width, int height);
+
+    private native void nativePause();
+    private native void nativeResume();
+    private native void nativeFreeMemory();
 }
diff --git a/core/java/android/webkit/WebViewDatabase.java b/core/java/android/webkit/WebViewDatabase.java
index 1004e30..4e76254 100644
--- a/core/java/android/webkit/WebViewDatabase.java
+++ b/core/java/android/webkit/WebViewDatabase.java
@@ -48,7 +48,9 @@
     // 6 -> 7 Change cache localPath from int to String
     // 7 -> 8 Move cache to its own db
     // 8 -> 9 Store both scheme and host when storing passwords
-    private static final int CACHE_DATABASE_VERSION = 1;
+    private static final int CACHE_DATABASE_VERSION = 3;
+    // 1 -> 2 Add expires String
+    // 2 -> 3 Add content-disposition
 
     private static WebViewDatabase mInstance = null;
 
@@ -107,6 +109,8 @@
 
     private static final String CACHE_EXPIRES_COL = "expires";
 
+    private static final String CACHE_EXPIRES_STRING_COL = "expiresstring";
+
     private static final String CACHE_MIMETYPE_COL = "mimetype";
 
     private static final String CACHE_ENCODING_COL = "encoding";
@@ -117,6 +121,8 @@
 
     private static final String CACHE_CONTENTLENGTH_COL = "contentlength";
 
+    private static final String CACHE_CONTENTDISPOSITION_COL = "contentdisposition";
+
     // column id strings for "password" table
     private static final String PASSWORD_HOST_COL = "host";
 
@@ -150,11 +156,13 @@
     private static int mCacheLastModifyColIndex;
     private static int mCacheETagColIndex;
     private static int mCacheExpiresColIndex;
+    private static int mCacheExpiresStringColIndex;
     private static int mCacheMimeTypeColIndex;
     private static int mCacheEncodingColIndex;
     private static int mCacheHttpStatusColIndex;
     private static int mCacheLocationColIndex;
     private static int mCacheContentLengthColIndex;
+    private static int mCacheContentDispositionColIndex;
 
     private static int mCacheTransactionRefcount;
 
@@ -220,6 +228,8 @@
                         .getColumnIndex(CACHE_ETAG_COL);
                 mCacheExpiresColIndex = mCacheInserter
                         .getColumnIndex(CACHE_EXPIRES_COL);
+                mCacheExpiresStringColIndex = mCacheInserter
+                        .getColumnIndex(CACHE_EXPIRES_STRING_COL);
                 mCacheMimeTypeColIndex = mCacheInserter
                         .getColumnIndex(CACHE_MIMETYPE_COL);
                 mCacheEncodingColIndex = mCacheInserter
@@ -230,6 +240,8 @@
                         .getColumnIndex(CACHE_LOCATION_COL);
                 mCacheContentLengthColIndex = mCacheInserter
                         .getColumnIndex(CACHE_CONTENTLENGTH_COL);
+                mCacheContentDispositionColIndex = mCacheInserter
+                        .getColumnIndex(CACHE_CONTENTDISPOSITION_COL);
             }
         }
 
@@ -320,11 +332,12 @@
                     + " TEXT, " + CACHE_FILE_PATH_COL + " TEXT, "
                     + CACHE_LAST_MODIFY_COL + " TEXT, " + CACHE_ETAG_COL
                     + " TEXT, " + CACHE_EXPIRES_COL + " INTEGER, "
+                    + CACHE_EXPIRES_STRING_COL + " TEXT, "
                     + CACHE_MIMETYPE_COL + " TEXT, " + CACHE_ENCODING_COL
                     + " TEXT," + CACHE_HTTP_STATUS_COL + " INTEGER, "
                     + CACHE_LOCATION_COL + " TEXT, " + CACHE_CONTENTLENGTH_COL
-                    + " INTEGER, " + " UNIQUE (" + CACHE_URL_COL
-                    + ") ON CONFLICT REPLACE);");
+                    + " INTEGER, " + CACHE_CONTENTDISPOSITION_COL + " TEXT, "
+                    + " UNIQUE (" + CACHE_URL_COL + ") ON CONFLICT REPLACE);");
             mCacheDatabase.execSQL("CREATE INDEX cacheUrlIndex ON cache ("
                     + CACHE_URL_COL + ")");
         }
@@ -537,8 +550,8 @@
         }
 
         Cursor cursor = mCacheDatabase.rawQuery("SELECT filepath, lastmodify, etag, expires, "
-                    + "mimetype, encoding, httpstatus, location, contentlength "
-                    + "FROM cache WHERE url = ?",
+                    + "expiresstring, mimetype, encoding, httpstatus, location, contentlength, "
+                    + "contentdisposition FROM cache WHERE url = ?",
                 new String[] { url });
 
         try {
@@ -548,11 +561,13 @@
                 ret.lastModified = cursor.getString(1);
                 ret.etag = cursor.getString(2);
                 ret.expires = cursor.getLong(3);
-                ret.mimeType = cursor.getString(4);
-                ret.encoding = cursor.getString(5);
-                ret.httpStatusCode = cursor.getInt(6);
-                ret.location = cursor.getString(7);
-                ret.contentLength = cursor.getLong(8);
+                ret.expiresString = cursor.getString(4);
+                ret.mimeType = cursor.getString(5);
+                ret.encoding = cursor.getString(6);
+                ret.httpStatusCode = cursor.getInt(7);
+                ret.location = cursor.getString(8);
+                ret.contentLength = cursor.getLong(9);
+                ret.contentdisposition = cursor.getString(10);
                 return ret;
             }
         } finally {
@@ -591,11 +606,14 @@
         mCacheInserter.bind(mCacheLastModifyColIndex, c.lastModified);
         mCacheInserter.bind(mCacheETagColIndex, c.etag);
         mCacheInserter.bind(mCacheExpiresColIndex, c.expires);
+        mCacheInserter.bind(mCacheExpiresStringColIndex, c.expiresString);
         mCacheInserter.bind(mCacheMimeTypeColIndex, c.mimeType);
         mCacheInserter.bind(mCacheEncodingColIndex, c.encoding);
         mCacheInserter.bind(mCacheHttpStatusColIndex, c.httpStatusCode);
         mCacheInserter.bind(mCacheLocationColIndex, c.location);
         mCacheInserter.bind(mCacheContentLengthColIndex, c.contentLength);
+        mCacheInserter.bind(mCacheContentDispositionColIndex,
+                c.contentdisposition);
         mCacheInserter.execute();
     }
 
diff --git a/core/java/android/webkit/gears/ApacheHttpRequestAndroid.java b/core/java/android/webkit/gears/ApacheHttpRequestAndroid.java
index 74d27ed..b3d7f69 100644
--- a/core/java/android/webkit/gears/ApacheHttpRequestAndroid.java
+++ b/core/java/android/webkit/gears/ApacheHttpRequestAndroid.java
@@ -38,7 +38,6 @@
 import java.io.OutputStream;
 import java.io.IOException;
 import java.lang.StringBuilder;
-import java.util.Date;
 import java.util.Map;
 import java.util.HashMap;
 import java.util.Iterator;
@@ -57,7 +56,6 @@
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
 import org.apache.http.conn.ssl.StrictHostnameVerifier;
-import org.apache.http.impl.cookie.DateUtils;
 import org.apache.http.util.CharArrayBuffer;
 
 import java.util.concurrent.locks.Condition;
@@ -863,12 +861,9 @@
         mResponseHeaders = new HashMap<String, String[]>();
         String contentLength = Long.toString(cacheResult.getContentLength());
         setResponseHeader(KEY_CONTENT_LENGTH, contentLength);
-        long expires = cacheResult.getExpires();
-        if (expires >= 0) {
-            // "Expires" header is valid and finite. Milliseconds since 1970
-            // epoch, formatted as RFC-1123.
-            String expiresString = DateUtils.formatDate(new Date(expires));
-            setResponseHeader(KEY_EXPIRES, expiresString);
+        String expires = cacheResult.getExpiresString();
+        if (expires != null) {
+            setResponseHeader(KEY_EXPIRES, expires);
         }
         String lastModified = cacheResult.getLastModified();
         if (lastModified != null) {
diff --git a/core/java/android/widget/AbsSeekBar.java b/core/java/android/widget/AbsSeekBar.java
index 04cb8a0..f92eb99 100644
--- a/core/java/android/widget/AbsSeekBar.java
+++ b/core/java/android/widget/AbsSeekBar.java
@@ -320,11 +320,6 @@
         
         final int max = getMax();
         progress += scale * max;
-        if (progress < 0) {
-            progress = 0;
-        } else if (progress > max) {
-            progress = max;
-        }
         
         setProgress((int) progress, true);
     }
diff --git a/core/java/android/widget/AdapterView.java b/core/java/android/widget/AdapterView.java
index 7d2fcbc..fe6d91a 100644
--- a/core/java/android/widget/AdapterView.java
+++ b/core/java/android/widget/AdapterView.java
@@ -163,7 +163,7 @@
     /**
      * View to show if there are no items to show.
      */
-    View mEmptyView;
+    private View mEmptyView;
 
     /**
      * The number of items in the current adapter.
diff --git a/core/java/android/widget/AlphabetIndexer.java b/core/java/android/widget/AlphabetIndexer.java
index f50676a..59b2c2a 100644
--- a/core/java/android/widget/AlphabetIndexer.java
+++ b/core/java/android/widget/AlphabetIndexer.java
@@ -28,7 +28,7 @@
  * invalidates the cache if changes occur in the cursor.
  * <p/>
  * Your adapter is responsible for updating the cursor by calling {@link #setCursor} if the
- * cursor changes. {@link #getPositionForSection} method does the binary search for the starting 
+ * cursor changes. {@link #getPositionForSection} method does the binary search for the starting
  * index of a given section (alphabet).
  */
 public class AlphabetIndexer extends DataSetObserver implements SectionIndexer {
@@ -37,33 +37,33 @@
      * Cursor that is used by the adapter of the list view.
      */
     protected Cursor mDataCursor;
-    
+
     /**
      * The index of the cursor column that this list is sorted on.
      */
     protected int mColumnIndex;
-    
+
     /**
      * The string of characters that make up the indexing sections.
      */
     protected CharSequence mAlphabet;
-    
+
     /**
      * Cached length of the alphabet array.
      */
     private int mAlphabetLength;
-    
+
     /**
      * This contains a cache of the computed indices so far. It will get reset whenever
      * the dataset changes or the cursor changes.
      */
     private SparseIntArray mAlphaMap;
-    
+
     /**
      * Use a collator to compare strings in a localized manner.
      */
     private java.text.Collator mCollator;
-    
+
     /**
      * The section array converted from the alphabet string.
      */
@@ -72,9 +72,9 @@
     /**
      * Constructs the indexer.
      * @param cursor the cursor containing the data set
-     * @param sortedColumnIndex the column number in the cursor that is sorted 
+     * @param sortedColumnIndex the column number in the cursor that is sorted
      *        alphabetically
-     * @param alphabet string containing the alphabet, with space as the first character. 
+     * @param alphabet string containing the alphabet, with space as the first character.
      *        For example, use the string " ABCDEFGHIJKLMNOPQRSTUVWXYZ" for English indexing.
      *        The characters must be uppercase and be sorted in ascii/unicode order. Basically
      *        characters in the alphabet will show up as preview letters.
@@ -104,7 +104,7 @@
     public Object[] getSections() {
         return mAlphabetArray;
     }
-    
+
     /**
      * Sets a new cursor as the data set and resets the cache of indices.
      * @param cursor the new cursor to use as the data set
@@ -124,9 +124,16 @@
      * Default implementation compares the first character of word with letter.
      */
     protected int compare(String word, String letter) {
-        return mCollator.compare(word.substring(0, 1), letter);
+        final String firstLetter;
+        if (word.length() == 0) {
+            firstLetter = " ";
+        } else {
+            firstLetter = word.substring(0, 1);
+        }
+
+        return mCollator.compare(firstLetter, letter);
     }
-    
+
     /**
      * Performs a binary search or cache lookup to find the first row that
      * matches a given section's starting letter.
@@ -143,7 +150,7 @@
         if (cursor == null || mAlphabet == null) {
             return 0;
         }
-        
+
         // Check bounds
         if (sectionIndex <= 0) {
             return 0;
@@ -164,7 +171,7 @@
         int key = letter;
         // Check map
         if (Integer.MIN_VALUE != (pos = alphaMap.get(key, Integer.MIN_VALUE))) {
-            // Is it approximate? Using negative value to indicate that it's 
+            // Is it approximate? Using negative value to indicate that it's
             // an approximation and positive value when it is the accurate
             // position.
             if (pos < 0) {
@@ -204,7 +211,7 @@
             }
             int diff = compare(curName, targetLetter);
             if (diff != 0) {
-                // Commenting out approximation code because it doesn't work for certain 
+                // TODO: Commenting out approximation code because it doesn't work for certain
                 // lists with custom comparators
                 // Enter approximation in hash if a better solution doesn't exist
                 // String startingLetter = Character.toString(getFirstLetter(curName));
@@ -259,9 +266,9 @@
                 return i;
             }
         }
-        return 0; // Don't recognize the letter - falls under zero'th section    
+        return 0; // Don't recognize the letter - falls under zero'th section
     }
-    
+
     /*
      * @hide
      */
diff --git a/core/java/android/widget/AutoCompleteTextView.java b/core/java/android/widget/AutoCompleteTextView.java
index 6848a55..e613ec4 100644
--- a/core/java/android/widget/AutoCompleteTextView.java
+++ b/core/java/android/widget/AutoCompleteTextView.java
@@ -193,7 +193,7 @@
         setFocusable(true);
 
         addTextChangedListener(new MyWatcher());
-
+        
         mPassThroughClickListener = new PassThroughClickListener();
         super.setOnClickListener(mPassThroughClickListener);
     }
@@ -321,8 +321,6 @@
      * @return the background drawable
      * 
      * @attr ref android.R.styleable#PopupWindow_popupBackground
-     *
-     * @hide Pending API council approval
      */
     public Drawable getDropDownBackground() {
         return mPopup.getBackground();
@@ -334,8 +332,6 @@
      * @param d the drawable to set as the background
      * 
      * @attr ref android.R.styleable#PopupWindow_popupBackground
-     *
-     * @hide Pending API council approval
      */
     public void setDropDownBackgroundDrawable(Drawable d) {
         mPopup.setBackgroundDrawable(d);
@@ -347,14 +343,48 @@
      * @param id the id of the drawable to set as the background
      * 
      * @attr ref android.R.styleable#PopupWindow_popupBackground
-     *
-     * @hide Pending API council approval
      */
     public void setDropDownBackgroundResource(int id) {
         mPopup.setBackgroundDrawable(getResources().getDrawable(id));
     }
-
+    
     /**
+     * <p>Sets the vertical offset used for the auto-complete drop-down list.</p>
+     * 
+     * @param offset the vertical offset
+     */
+    public void setDropDownVerticalOffset(int offset) {
+        mDropDownVerticalOffset = offset;
+    }
+    
+    /**
+     * <p>Gets the vertical offset used for the auto-complete drop-down list.</p>
+     * 
+     * @return the vertical offset
+     */
+    public int getDropDownVerticalOffset() {
+        return mDropDownVerticalOffset;
+    }
+    
+    /**
+     * <p>Sets the horizontal offset used for the auto-complete drop-down list.</p>
+     * 
+     * @param offset the horizontal offset
+     */
+    public void setDropDownHorizontalOffset(int offset) {
+        mDropDownHorizontalOffset = offset;
+    }
+    
+    /**
+     * <p>Gets the horizontal offset used for the auto-complete drop-down list.</p>
+     * 
+     * @return the horizontal offset
+     */
+    public int getDropDownHorizontalOffset() {
+        return mDropDownHorizontalOffset;
+    }
+
+     /**
      * <p>Sets the animation style of the auto-complete drop-down list.</p>
      *
      * <p>If the drop-down is showing, calling this method will take effect only
@@ -381,50 +411,6 @@
     public int getDropDownAnimationStyle() {
         return mPopup.getAnimationStyle();
     }
-    
-    /**
-     * <p>Sets the vertical offset used for the auto-complete drop-down list.</p>
-     * 
-     * @param offset the vertical offset
-     *
-     * @hide Pending API council approval
-     */
-    public void setDropDownVerticalOffset(int offset) {
-        mDropDownVerticalOffset = offset;
-    }
-    
-    /**
-     * <p>Gets the vertical offset used for the auto-complete drop-down list.</p>
-     * 
-     * @return the vertical offset
-     *
-     * @hide Pending API council approval
-     */
-    public int getDropDownVerticalOffset() {
-        return mDropDownVerticalOffset;
-    }
-    
-    /**
-     * <p>Sets the horizontal offset used for the auto-complete drop-down list.</p>
-     * 
-     * @param offset the horizontal offset
-     *
-     * @hide Pending API council approval
-     */
-    public void setDropDownHorizontalOffset(int offset) {
-        mDropDownHorizontalOffset = offset;
-    }
-    
-    /**
-     * <p>Gets the horizontal offset used for the auto-complete drop-down list.</p>
-     * 
-     * @return the horizontal offset
-     *
-     * @hide Pending API council approval
-     */
-    public int getDropDownHorizontalOffset() {
-        return mDropDownHorizontalOffset;
-    }
 
     /**
      * @return Whether the drop-down is visible as long as there is {@link #enoughToFilter()}
@@ -1570,7 +1556,7 @@
          */
         CharSequence fixText(CharSequence invalidText);
     }
-
+    
     /**
      * Allows us a private hook into the on click event without preventing users from setting
      * their own click listener.
@@ -1586,5 +1572,5 @@
             if (mWrapped != null) mWrapped.onClick(v);
         }
     }
-
+    
 }
diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java
index f8a6f89..515b581 100644
--- a/core/java/android/widget/ListView.java
+++ b/core/java/android/widget/ListView.java
@@ -3285,11 +3285,12 @@
 
     /**
      * Returns the checked state of the specified position. The result is only
-     * valid if the choice mode has not been set to {@link #CHOICE_MODE_SINGLE}
+     * valid if the choice mode has been set to {@link #CHOICE_MODE_SINGLE}
      * or {@link #CHOICE_MODE_MULTIPLE}.
      *
      * @param position The item whose checked state to return
-     * @return The item's checked state
+     * @return The item's checked state or <code>false</code> if choice mode
+     *         is invalid
      *
      * @see #setChoiceMode(int)
      */
@@ -3303,7 +3304,7 @@
 
     /**
      * Returns the currently checked item. The result is only valid if the choice
-     * mode has not been set to {@link #CHOICE_MODE_SINGLE}.
+     * mode has been set to {@link #CHOICE_MODE_SINGLE}.
      *
      * @return The position of the currently checked item or
      *         {@link #INVALID_POSITION} if nothing is selected
@@ -3320,10 +3321,12 @@
 
     /**
      * Returns the set of checked items in the list. The result is only valid if
-     * the choice mode has not been set to {@link #CHOICE_MODE_SINGLE}.
+     * the choice mode has not been set to {@link #CHOICE_MODE_NONE}.
      *
      * @return  A SparseBooleanArray which will return true for each call to
-     *          get(int position) where position is a position in the list.
+     *          get(int position) where position is a position in the list,
+     *          or <code>null</code> if the choice mode is set to
+     *          {@link #CHOICE_MODE_NONE}.
      */
     public SparseBooleanArray getCheckedItemPositions() {
         if (mChoiceMode != CHOICE_MODE_NONE) {
diff --git a/core/java/android/widget/Scroller.java b/core/java/android/widget/Scroller.java
index c9ace0a..381641f 100644
--- a/core/java/android/widget/Scroller.java
+++ b/core/java/android/widget/Scroller.java
@@ -17,6 +17,7 @@
 package android.widget;
 
 import android.content.Context;
+import android.hardware.SensorManager;
 import android.view.ViewConfiguration;
 import android.view.animation.AnimationUtils;
 import android.view.animation.Interpolator;
@@ -79,9 +80,9 @@
         mFinished = true;
         mInterpolator = interpolator;
         float ppi = context.getResources().getDisplayMetrics().density * 160.0f;
-        mDeceleration = 9.8f   // g (m/s^2)
-                      * 39.37f // inch/meter
-                      * ppi    // pixels per inch
+        mDeceleration = SensorManager.GRAVITY_EARTH   // g (m/s^2)
+                      * 39.37f                        // inch/meter
+                      * ppi                           // pixels per inch
                       * ViewConfiguration.getScrollFriction();
     }
     
@@ -347,7 +348,11 @@
     }
     
     /**
-     * 
+     * Stops the animation. Contrary to {@link #forceFinished(boolean)},
+     * aborting the animating cause the scroller to move to the final x and y
+     * position
+     *
+     * @see #forceFinished(boolean)
      */
     public void abortAnimation() {
         mCurrX = mFinalX;
@@ -356,10 +361,12 @@
     }
     
     /**
-     * Extend the scroll animation. This allows a running animation to 
-     * scroll further and longer, when used with setFinalX() or setFinalY().
+     * Extend the scroll animation. This allows a running animation to scroll
+     * further and longer, when used with {@link #setFinalX(int)} or {@link #setFinalY(int)}.
      *
      * @param extend Additional time to scroll in milliseconds.
+     * @see #setFinalX(int)
+     * @see #setFinalY(int)
      */
     public void extendDuration(int extend) {
         int passed = timePassed();
@@ -367,18 +374,37 @@
         mDurationReciprocal = 1.0f / (float)mDuration;
         mFinished = false;
     }
-    
+
+    /**
+     * Returns the time elapsed since the beginning of the scrolling.
+     *
+     * @return The elapsed time in milliseconds.
+     */
     public int timePassed() {
         return (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);
     }
-    
+
+    /**
+     * Sets the final position (X) for this scroller.
+     *
+     * @param newX The new X offset as an absolute distance from the origin.
+     * @see #extendDuration(int)
+     * @see #setFinalY(int)
+     */
     public void setFinalX(int newX) {
         mFinalX = newX;
         mDeltaX = mFinalX - mStartX;
         mFinished = false;
     }
 
-   public void setFinalY(int newY) {
+    /**
+     * Sets the final position (Y) for this scroller.
+     *
+     * @param newY The new Y offset as an absolute distance from the origin.
+     * @see #extendDuration(int)
+     * @see #setFinalX(int)
+     */
+    public void setFinalY(int newY) {
         mFinalY = newY;
         mDeltaY = mFinalY - mStartY;
         mFinished = false;
diff --git a/core/java/android/widget/SimpleCursorTreeAdapter.java b/core/java/android/widget/SimpleCursorTreeAdapter.java
index c456f56..a1c65f0 100644
--- a/core/java/android/widget/SimpleCursorTreeAdapter.java
+++ b/core/java/android/widget/SimpleCursorTreeAdapter.java
@@ -26,9 +26,16 @@
  * defined in an XML file. You can specify which columns you want, which views
  * you want to display the columns, and the XML file that defines the appearance
  * of these views. Separate XML files for child and groups are possible.
- * TextViews bind the values to their text property (see
- * {@link TextView#setText(CharSequence)}). ImageViews bind the values to their
- * image's Uri property (see {@link ImageView#setImageURI(android.net.Uri)}).
+ *
+ * Binding occurs in two phases. First, if a
+ * {@link android.widget.SimpleCursorTreeAdapter.ViewBinder} is available,
+ * {@link ViewBinder#setViewValue(android.view.View, android.database.Cursor, int)}
+ * is invoked. If the returned value is true, binding has occurred. If the
+ * returned value is false and the view to bind is a TextView,
+ * {@link #setViewText(TextView, String)} is invoked. If the returned value
+ * is false and the view to bind is an ImageView,
+ * {@link #setViewImage(ImageView, String)} is invoked. If no appropriate
+ * binding can be found, an {@link IllegalStateException} is thrown.
  */
 public abstract class SimpleCursorTreeAdapter extends ResourceCursorTreeAdapter {
     /** The indices of columns that contain data to display for a group. */
@@ -48,6 +55,11 @@
     private int[] mChildTo;
     
     /**
+     * View binder, if supplied
+     */
+    private ViewBinder mViewBinder;
+
+    /**
      * Constructor.
      * 
      * @param context The context where the {@link ExpandableListView}
@@ -193,21 +205,53 @@
         initFromColumns(childCursor, childFromNames, mChildFrom);
     }
     
+    /**
+     * Returns the {@link ViewBinder} used to bind data to views.
+     *
+     * @return a ViewBinder or null if the binder does not exist
+     *
+     * @see #setViewBinder(android.widget.SimpleCursorTreeAdapter.ViewBinder)
+     */
+    public ViewBinder getViewBinder() {
+        return mViewBinder;
+    }
+
+    /**
+     * Sets the binder used to bind data to views.
+     *
+     * @param viewBinder the binder used to bind data to views, can be null to
+     *        remove the existing binder
+     *
+     * @see #getViewBinder()
+     */
+    public void setViewBinder(ViewBinder viewBinder) {
+        mViewBinder = viewBinder;
+    }
+
     private void bindView(View view, Context context, Cursor cursor, int[] from, int[] to) {
+        final ViewBinder binder = mViewBinder;
+        
         for (int i = 0; i < to.length; i++) {
             View v = view.findViewById(to[i]);
             if (v != null) {
-                String text = cursor.getString(from[i]);
-                if (text == null) {
-                    text = "";
+                boolean bound = false;
+                if (binder != null) {
+                    bound = binder.setViewValue(v, cursor, from[i]);
                 }
-                if (v instanceof TextView) {
-                    ((TextView) v).setText(text);
-                } else if (v instanceof ImageView) {
-                    setViewImage((ImageView) v, text);
-                } else {
-                    throw new IllegalStateException("SimpleCursorAdapter can bind values only to" +
-                            " TextView and ImageView!");
+                
+                if (!bound) {
+                    String text = cursor.getString(from[i]);
+                    if (text == null) {
+                        text = "";
+                    }
+                    if (v instanceof TextView) {
+                        setViewText((TextView) v, text);
+                    } else if (v instanceof ImageView) {
+                        setViewImage((ImageView) v, text);
+                    } else {
+                        throw new IllegalStateException("SimpleCursorTreeAdapter can bind values" +
+                                " only to TextView and ImageView!");
+                    }
                 }
             }
         }
@@ -238,4 +282,48 @@
             v.setImageURI(Uri.parse(value));
         }
     }
+
+    /**
+     * Called by bindView() to set the text for a TextView but only if
+     * there is no existing ViewBinder or if the existing ViewBinder cannot
+     * handle binding to an TextView.
+     *
+     * Intended to be overridden by Adapters that need to filter strings
+     * retrieved from the database.
+     * 
+     * @param v TextView to receive text
+     * @param text the text to be set for the TextView
+     */
+    public void setViewText(TextView v, String text) {
+        v.setText(text);
+    }
+
+    /**
+     * This class can be used by external clients of SimpleCursorTreeAdapter
+     * to bind values from the Cursor to views.
+     *
+     * You should use this class to bind values from the Cursor to views
+     * that are not directly supported by SimpleCursorTreeAdapter or to
+     * change the way binding occurs for views supported by
+     * SimpleCursorTreeAdapter.
+     *
+     * @see SimpleCursorTreeAdapter#setViewImage(ImageView, String) 
+     * @see SimpleCursorTreeAdapter#setViewText(TextView, String)
+     */
+    public static interface ViewBinder {
+        /**
+         * Binds the Cursor column defined by the specified index to the specified view.
+         *
+         * When binding is handled by this ViewBinder, this method must return true.
+         * If this method returns false, SimpleCursorTreeAdapter will attempts to handle
+         * the binding on its own.
+         *
+         * @param view the view to bind the data to
+         * @param cursor the cursor to get the data from
+         * @param columnIndex the column at which the data can be found in the cursor
+         *
+         * @return true if the data was bound to the view, false otherwise
+         */
+        boolean setViewValue(View view, Cursor cursor, int columnIndex);
+    }
 }
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 3fab692..0421612 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -5769,7 +5769,7 @@
      * Causes words in the text that are longer than the view is wide
      * to be ellipsized instead of broken in the middle.  You may also
      * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
-     * to constrain the text toa single line.  Use <code>null</code>
+     * to constrain the text to a single line.  Use <code>null</code>
      * to turn off ellipsizing.
      *
      * @attr ref android.R.styleable#TextView_ellipsize
diff --git a/core/java/android/widget/VideoView.java b/core/java/android/widget/VideoView.java
index 20dd8a6..5bc2507 100644
--- a/core/java/android/widget/VideoView.java
+++ b/core/java/android/widget/VideoView.java
@@ -51,11 +51,26 @@
     private Uri         mUri;
     private int         mDuration;
 
+    // all possible internal states
+    private static final int STATE_ERROR              = -1;
+    private static final int STATE_IDLE               = 0;
+    private static final int STATE_PREPARING          = 1;
+    private static final int STATE_PREPARED           = 2;
+    private static final int STATE_PLAYING            = 3;
+    private static final int STATE_PAUSED             = 4;
+    private static final int STATE_PLAYBACK_COMPLETED = 5;
+
+    // mCurrentState is a VideoView object's current state.
+    // mTargetState is the state that a method caller intends to reach.
+    // For instance, regardless the VideoView object's current state,
+    // calling pause() intends to bring the object to a target state
+    // of STATE_PAUSED.
+    private int mCurrentState = STATE_IDLE;
+    private int mTargetState  = STATE_IDLE;
+
     // All the stuff we need for playing and showing a video
     private SurfaceHolder mSurfaceHolder = null;
     private MediaPlayer mMediaPlayer = null;
-    private boolean     mIsPrepared;
-    private boolean     mIsPlaybackCompleted;
     private int         mVideoWidth;
     private int         mVideoHeight;
     private int         mSurfaceWidth;
@@ -65,8 +80,7 @@
     private MediaPlayer.OnPreparedListener mOnPreparedListener;
     private int         mCurrentBufferPercentage;
     private OnErrorListener mOnErrorListener;
-    private boolean     mStartWhenPrepared;
-    private int         mSeekWhenPrepared;
+    private int         mSeekWhenPrepared;  // recording the seek position while preparing
 
     public VideoView(Context context) {
         super(context);
@@ -80,7 +94,6 @@
     
     public VideoView(Context context, AttributeSet attrs, int defStyle) {
         super(context, attrs, defStyle);
-
         initVideoView();
     }
 
@@ -143,6 +156,8 @@
         setFocusable(true);
         setFocusableInTouchMode(true);
         requestFocus();
+        mCurrentState = STATE_IDLE;
+        mTargetState  = STATE_IDLE;
     }
 
     public void setVideoPath(String path) {
@@ -151,7 +166,6 @@
 
     public void setVideoURI(Uri uri) {
         mUri = uri;
-        mStartWhenPrepared = false;
         mSeekWhenPrepared = 0;
         openVideo();
         requestLayout();
@@ -163,6 +177,8 @@
             mMediaPlayer.stop();
             mMediaPlayer.release();
             mMediaPlayer = null;
+            mCurrentState = STATE_IDLE;
+            mTargetState  = STATE_IDLE;
         }
     }
 
@@ -176,18 +192,14 @@
         Intent i = new Intent("com.android.music.musicservicecommand");
         i.putExtra("command", "pause");
         mContext.sendBroadcast(i);
-        
-        if (mMediaPlayer != null) {
-            mMediaPlayer.reset();
-            mMediaPlayer.release();
-            mMediaPlayer = null;
-        }
+
+        // we shouldn't clear the target state, because somebody might have
+        // called start() previously
+        release(false);
         try {
             mMediaPlayer = new MediaPlayer();
             mMediaPlayer.setOnPreparedListener(mPreparedListener);
             mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
-            mIsPrepared = false;
-            Log.v(TAG, "reset duration to -1 in openVideo");
             mDuration = -1;
             mMediaPlayer.setOnCompletionListener(mCompletionListener);
             mMediaPlayer.setOnErrorListener(mErrorListener);
@@ -198,12 +210,19 @@
             mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
             mMediaPlayer.setScreenOnWhilePlaying(true);
             mMediaPlayer.prepareAsync();
+            // we don't set the target state here either, but preserve the
+            // target state that was there before.
+            mCurrentState = STATE_PREPARING;
             attachMediaController();
         } catch (IOException ex) {
             Log.w(TAG, "Unable to open content: " + mUri, ex);
+            mCurrentState = STATE_ERROR;
+            mTargetState = STATE_ERROR;
             return;
         } catch (IllegalArgumentException ex) {
             Log.w(TAG, "Unable to open content: " + mUri, ex);
+            mCurrentState = STATE_ERROR;
+            mTargetState = STATE_ERROR;
             return;
         }
     }
@@ -222,7 +241,7 @@
             View anchorView = this.getParent() instanceof View ?
                     (View)this.getParent() : this;
             mMediaController.setAnchorView(anchorView);
-            mMediaController.setEnabled(mIsPrepared);
+            mMediaController.setEnabled(isInPlaybackState());
         }
     }
     
@@ -239,8 +258,7 @@
     
     MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
         public void onPrepared(MediaPlayer mp) {
-            // briefly show the mediacontroller
-            mIsPrepared = true;
+            mCurrentState = STATE_PREPARED;
             if (mOnPreparedListener != null) {
                 mOnPreparedListener.onPrepared(mMediaPlayer);
             }
@@ -249,6 +267,10 @@
             }
             mVideoWidth = mp.getVideoWidth();
             mVideoHeight = mp.getVideoHeight();
+            int seekToPosition = mSeekWhenPrepared;  // mSeekWhenPrepared may be changed after seekTo() call
+            if (seekToPosition != 0) {
+                seekTo(seekToPosition);
+            }
             if (mVideoWidth != 0 && mVideoHeight != 0) {
                 //Log.i("@@@@", "video size: " + mVideoWidth +"/"+ mVideoHeight);
                 getHolder().setFixedSize(mVideoWidth, mVideoHeight);
@@ -256,18 +278,13 @@
                     // We didn't actually change the size (it was already at the size
                     // we need), so we won't get a "surface changed" callback, so
                     // start the video here instead of in the callback.
-                    if (mSeekWhenPrepared != 0) {
-                        mMediaPlayer.seekTo(mSeekWhenPrepared);
-                        mSeekWhenPrepared = 0;
-                    }
-                    if (mStartWhenPrepared) {
+                    if (mTargetState == STATE_PLAYING) {
                         start();
-                        mStartWhenPrepared = false;
                         if (mMediaController != null) {
                             mMediaController.show();
                         }
                     } else if (!isPlaying() &&
-                            (mSeekWhenPrepared != 0 || getCurrentPosition() > 0)) {
+                               (seekToPosition != 0 || getCurrentPosition() > 0)) {
                        if (mMediaController != null) {
                            // Show the media controls when we're paused into a video and make 'em stick.
                            mMediaController.show(0);
@@ -277,13 +294,8 @@
             } else {
                 // We don't know the video size yet, but should start anyway.
                 // The video size might be reported to us later.
-                if (mSeekWhenPrepared != 0) {
-                    mMediaPlayer.seekTo(mSeekWhenPrepared);
-                    mSeekWhenPrepared = 0;
-                }
-                if (mStartWhenPrepared) {
+                if (mTargetState == STATE_PLAYING) {
                     start();
-                    mStartWhenPrepared = false;
                 }
             }
         }
@@ -292,7 +304,8 @@
     private MediaPlayer.OnCompletionListener mCompletionListener =
         new MediaPlayer.OnCompletionListener() {
         public void onCompletion(MediaPlayer mp) {
-            mIsPlaybackCompleted = true;
+            mCurrentState = STATE_PLAYBACK_COMPLETED;
+            mTargetState = STATE_PLAYBACK_COMPLETED;
             if (mMediaController != null) {
                 mMediaController.hide();
             }
@@ -306,6 +319,8 @@
         new MediaPlayer.OnErrorListener() {
         public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
             Log.d(TAG, "Error: " + framework_err + "," + impl_err);
+            mCurrentState = STATE_ERROR;
+            mTargetState = STATE_ERROR;
             if (mMediaController != null) {
                 mMediaController.hide();
             }
@@ -402,14 +417,13 @@
         {
             mSurfaceWidth = w;
             mSurfaceHeight = h;
-            if (mMediaPlayer != null && mIsPrepared && mVideoWidth == w && mVideoHeight == h) {
+            boolean isValidState =  (mTargetState == STATE_PLAYING);
+            boolean hasValidSize = (mVideoWidth == w && mVideoHeight == h);
+            if (mMediaPlayer != null && isValidState && hasValidSize) {
                 if (mSeekWhenPrepared != 0) {
-                    mMediaPlayer.seekTo(mSeekWhenPrepared);
-                    mSeekWhenPrepared = 0;
+                    seekTo(mSeekWhenPrepared);
                 }
-                if (!mIsPlaybackCompleted) {
-                    start();
-                } 
+                start();
                 if (mMediaController != null) {
                     mMediaController.show();
                 }
@@ -427,17 +441,28 @@
             // after we return from this we can't use the surface any more
             mSurfaceHolder = null;
             if (mMediaController != null) mMediaController.hide();
-            if (mMediaPlayer != null) {
-                mMediaPlayer.reset();
-                mMediaPlayer.release();
-                mMediaPlayer = null;
-            }
+            release(true);
         }
     };
 
+    /*
+     * release the media player in any state
+     */
+    private void release(boolean cleartargetstate) {
+        if (mMediaPlayer != null) {
+            mMediaPlayer.reset();
+            mMediaPlayer.release();
+            mMediaPlayer = null;
+            mCurrentState = STATE_IDLE;
+            if (cleartargetstate) {
+                mTargetState  = STATE_IDLE;
+            }
+        }
+    }
+
     @Override
     public boolean onTouchEvent(MotionEvent ev) {
-        if (mIsPrepared && mMediaPlayer != null && mMediaController != null) {
+        if (isInPlaybackState() && mMediaController != null) {
             toggleMediaControlsVisiblity();
         }
         return false;
@@ -445,7 +470,7 @@
     
     @Override
     public boolean onTrackballEvent(MotionEvent ev) {
-        if (mIsPrepared && mMediaPlayer != null && mMediaController != null) {
+        if (isInPlaybackState() && mMediaController != null) {
             toggleMediaControlsVisiblity();
         }
         return false;
@@ -454,15 +479,13 @@
     @Override
     public boolean onKeyDown(int keyCode, KeyEvent event)
     {
-        if (mIsPrepared &&
-                keyCode != KeyEvent.KEYCODE_BACK &&
-                keyCode != KeyEvent.KEYCODE_VOLUME_UP &&
-                keyCode != KeyEvent.KEYCODE_VOLUME_DOWN &&
-                keyCode != KeyEvent.KEYCODE_MENU &&
-                keyCode != KeyEvent.KEYCODE_CALL &&
-                keyCode != KeyEvent.KEYCODE_ENDCALL &&
-                mMediaPlayer != null &&
-                mMediaController != null) {
+        boolean isKeyCodeSupported = keyCode != KeyEvent.KEYCODE_BACK &&
+                                     keyCode != KeyEvent.KEYCODE_VOLUME_UP &&
+                                     keyCode != KeyEvent.KEYCODE_VOLUME_DOWN &&
+                                     keyCode != KeyEvent.KEYCODE_MENU &&
+                                     keyCode != KeyEvent.KEYCODE_CALL &&
+                                     keyCode != KeyEvent.KEYCODE_ENDCALL;
+        if (isInPlaybackState() && isKeyCodeSupported && mMediaController != null) {
             if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK ||
                     keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
                 if (mMediaPlayer.isPlaying()) {
@@ -494,26 +517,26 @@
     }
     
     public void start() {
-        mIsPlaybackCompleted = false;
-        if (mMediaPlayer != null && mIsPrepared) {
-                mMediaPlayer.start();
-                mStartWhenPrepared = false;
-        } else {
-            mStartWhenPrepared = true;
+        if (isInPlaybackState()) {
+            mMediaPlayer.start();
+            mCurrentState = STATE_PLAYING;
         }
+        mTargetState = STATE_PLAYING;
     }
     
     public void pause() {
-        if (mMediaPlayer != null && mIsPrepared) {
+        if (isInPlaybackState()) {
             if (mMediaPlayer.isPlaying()) {
                 mMediaPlayer.pause();
+                mCurrentState = STATE_PAUSED;
             }
         }
-        mStartWhenPrepared = false;
+        mTargetState = STATE_PAUSED;
     }
     
+    // cache duration as mDuration for faster access
     public int getDuration() {
-        if (mMediaPlayer != null && mIsPrepared) {
+        if (isInPlaybackState()) {
             if (mDuration > 0) {
                 return mDuration;
             }
@@ -525,25 +548,23 @@
     }
     
     public int getCurrentPosition() {
-        if (mMediaPlayer != null && mIsPrepared) {
+        if (isInPlaybackState()) {
             return mMediaPlayer.getCurrentPosition();
         }
         return 0;
     }
     
     public void seekTo(int msec) {
-        if (mMediaPlayer != null && mIsPrepared) {
+        if (isInPlaybackState()) {
             mMediaPlayer.seekTo(msec);
+            mSeekWhenPrepared = 0;
         } else {
             mSeekWhenPrepared = msec;
         }
     }    
             
     public boolean isPlaying() {
-        if (mMediaPlayer != null && mIsPrepared) {
-            return mMediaPlayer.isPlaying();
-        }
-        return false;
+        return isInPlaybackState() && mMediaPlayer.isPlaying();
     }
     
     public int getBufferPercentage() {
@@ -552,4 +573,11 @@
         }
         return 0;
     }
+
+    private boolean isInPlaybackState() {
+        return (mMediaPlayer != null &&
+                mCurrentState != STATE_ERROR &&
+                mCurrentState != STATE_IDLE &&
+                mCurrentState != STATE_PREPARING);
+    }
 }
diff --git a/core/java/com/android/internal/content/SyncStateContentProviderHelper.java b/core/java/com/android/internal/content/SyncStateContentProviderHelper.java
new file mode 100644
index 0000000..d2931a4b
--- /dev/null
+++ b/core/java/com/android/internal/content/SyncStateContentProviderHelper.java
@@ -0,0 +1,115 @@
+/*
+ * 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 com.android.internal.content;
+
+import com.android.internal.util.ArrayUtils;
+
+import android.database.Cursor;
+import android.database.DatabaseUtils;
+import android.database.sqlite.SQLiteDatabase;
+import android.accounts.Account;
+import android.content.ContentValues;
+import android.provider.SyncStateContract;
+
+/**
+ * Extends the schema of a ContentProvider to include the _sync_state table
+ * and implements query/insert/update/delete to access that table using the
+ * authority "syncstate". This can be used to store the sync state for a
+ * set of accounts.
+ *
+ * @hide
+ */
+public class SyncStateContentProviderHelper {
+    private static final String SELECT_BY_ACCOUNT =
+            SyncStateContract.Columns.ACCOUNT_NAME + "=? AND "
+                    + SyncStateContract.Columns.ACCOUNT_TYPE + "=?";
+
+    private static final String SYNC_STATE_TABLE = "_sync_state";
+    private static final String SYNC_STATE_META_TABLE = "_sync_state_metadata";
+    private static final String SYNC_STATE_META_VERSION_COLUMN = "version";
+
+    private static long DB_VERSION = 1;
+
+    private static final String[] ACCOUNT_PROJECTION =
+            new String[]{SyncStateContract.Columns.ACCOUNT_NAME,
+                    SyncStateContract.Columns.ACCOUNT_TYPE};
+
+    public static final String PATH = "syncstate";
+
+    public void createDatabase(SQLiteDatabase db) {
+        db.execSQL("DROP TABLE IF EXISTS " + SYNC_STATE_TABLE);
+        db.execSQL("CREATE TABLE " + SYNC_STATE_TABLE + " ("
+                + SyncStateContract.Columns._ID + " INTEGER PRIMARY KEY,"
+                + SyncStateContract.Columns.ACCOUNT_NAME + " TEXT NOT NULL,"
+                + SyncStateContract.Columns.ACCOUNT_TYPE + " TEXT NOT NULL,"
+                + SyncStateContract.Columns.DATA + " TEXT,"
+                + "UNIQUE(" + SyncStateContract.Columns.ACCOUNT_NAME + ", "
+                + SyncStateContract.Columns.ACCOUNT_TYPE + "));");
+
+        db.execSQL("DROP TABLE IF EXISTS " + SYNC_STATE_META_TABLE);
+        db.execSQL("CREATE TABLE " + SYNC_STATE_META_TABLE + " ("
+                + SYNC_STATE_META_VERSION_COLUMN + " INTEGER);");
+        ContentValues values = new ContentValues();
+        values.put(SYNC_STATE_META_VERSION_COLUMN, DB_VERSION);
+        db.insert(SYNC_STATE_META_TABLE, SYNC_STATE_META_VERSION_COLUMN, values);
+    }
+
+    public void onDatabaseOpened(SQLiteDatabase db) {
+        long version = DatabaseUtils.longForQuery(db,
+                "SELECT " + SYNC_STATE_META_VERSION_COLUMN + " FROM " + SYNC_STATE_META_TABLE,
+                null);
+        if (version != DB_VERSION) {
+            createDatabase(db);
+        }
+    }
+
+    public Cursor query(SQLiteDatabase db, String[] projection,
+            String selection, String[] selectionArgs, String sortOrder) {
+        return db.query(SYNC_STATE_TABLE, projection, selection, selectionArgs,
+                null, null, sortOrder);
+    }
+
+    public long insert(SQLiteDatabase db, ContentValues values) {
+        return db.replace(SYNC_STATE_TABLE, SyncStateContract.Columns.ACCOUNT_NAME, values);
+    }
+
+    public int delete(SQLiteDatabase db, String userWhere, String[] whereArgs) {
+        return db.delete(SYNC_STATE_TABLE, userWhere, whereArgs);
+    }
+
+    public int update(SQLiteDatabase db, ContentValues values,
+            String selection, String[] selectionArgs) {
+        return db.update(SYNC_STATE_TABLE, values, selection, selectionArgs);
+    }
+
+    public void onAccountsChanged(SQLiteDatabase db, Account[] accounts) {
+        Cursor c = db.query(SYNC_STATE_TABLE, ACCOUNT_PROJECTION, null, null, null, null, null);
+        try {
+            while (c.moveToNext()) {
+                final String accountName = c.getString(0);
+                final String accountType = c.getString(1);
+                Account account = new Account(accountName, accountType);
+                if (!ArrayUtils.contains(accounts, account)) {
+                    db.delete(SYNC_STATE_TABLE, SELECT_BY_ACCOUNT,
+                            new String[]{accountName, accountType});
+                }
+            }
+        } finally {
+            c.close();
+        }
+    }
+}
\ No newline at end of file
diff --git a/core/java/com/android/internal/os/ZygoteInit.java b/core/java/com/android/internal/os/ZygoteInit.java
index f67a235..989286e 100644
--- a/core/java/com/android/internal/os/ZygoteInit.java
+++ b/core/java/com/android/internal/os/ZygoteInit.java
@@ -93,7 +93,26 @@
 
     /** Controls whether we should preload resources during zygote init. */
     private static final boolean PRELOAD_RESOURCES = true;
-    
+
+    /**
+     * List of methods we "warm up" in the register map cache.  These were
+     * chosen because they appeared on the stack in GCs in multiple
+     * applications.
+     *
+     * This is in a VM-ready format, to minimize string processing.  If a
+     * class is not already loaded, or a method is not found, the entry
+     * will be skipped.
+     *
+     * This doesn't really merit a separately-generated input file at this
+     * time.  The list is fairly short, and the consequences of failure
+     * are minor.
+     */
+    private static final String[] REGISTER_MAP_METHODS = {
+        // (currently not doing any)
+        //"Landroid/app/Activity;.setContentView:(I)V",
+    };
+
+
     /**
      * Invokes a static "main(argv[]) method on class "className".
      * Converts various failing exceptions into RuntimeExceptions, with
@@ -319,6 +338,45 @@
     }
 
     /**
+     * Pre-caches register maps for methods that are commonly used.
+     */
+    private static void cacheRegisterMaps() {
+        String failed = null;
+        int failure;
+        long startTime = System.nanoTime();
+
+        failure = 0;
+
+        for (int i = 0; i < REGISTER_MAP_METHODS.length; i++) {
+            String str = REGISTER_MAP_METHODS[i];
+
+            if (!Debug.cacheRegisterMap(str)) {
+                if (failed == null)
+                    failed = str;
+                failure++;
+            }
+        }
+
+        long delta = System.nanoTime() - startTime;
+
+        if (failure == REGISTER_MAP_METHODS.length) {
+            if (REGISTER_MAP_METHODS.length > 0) {
+                Log.i(TAG,
+                    "Register map caching failed (precise GC not enabled?)");
+            }
+            return;
+        }
+
+        Log.i(TAG, "Register map cache: found " +
+            (REGISTER_MAP_METHODS.length - failure) + " of " +
+            REGISTER_MAP_METHODS.length + " methods in " +
+            (delta / 1000000L) + "ms");
+        if (failure > 0) {
+            Log.i(TAG, "  First failure: " + failed);
+        }
+    }
+
+    /**
      * Load in commonly used resources, so they can be shared across
      * processes.
      *
@@ -510,6 +568,7 @@
             EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                 SystemClock.uptimeMillis());
             preloadClasses();
+            //cacheRegisterMaps();
             preloadResources();
             EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                 SystemClock.uptimeMillis());
diff --git a/core/java/com/google/android/gdata2/client/AndroidGDataClient.java b/core/java/com/google/android/gdata2/client/AndroidGDataClient.java
new file mode 100644
index 0000000..7ac44c9
--- /dev/null
+++ b/core/java/com/google/android/gdata2/client/AndroidGDataClient.java
@@ -0,0 +1,584 @@
+// Copyright 2007 The Android Open Source Project
+
+package com.google.android.gdata2.client;
+
+import com.google.android.net.GoogleHttpClient;
+import com.google.wireless.gdata2.client.GDataClient;
+import com.google.wireless.gdata2.client.HttpException;
+import com.google.wireless.gdata2.client.QueryParams;
+import com.google.wireless.gdata2.data.StringUtils;
+import com.google.wireless.gdata2.parser.ParseException;
+import com.google.wireless.gdata2.serializer.GDataSerializer;
+import com.google.android.gdata2.client.QueryParamsImpl;
+
+import org.apache.http.Header;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.StatusLine;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.entity.InputStreamEntity;
+import org.apache.http.entity.AbstractHttpEntity;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.net.http.AndroidHttpClient;
+import android.text.TextUtils;
+import android.util.Config;
+import android.util.Log;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.io.BufferedInputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLEncoder;
+
+/**
+ * Implementation of a GDataClient using GoogleHttpClient to make HTTP
+ * requests.  Always issues GETs and POSTs, using the X-HTTP-Method-Override
+ * header when a PUT or DELETE is desired, to avoid issues with firewalls, etc.,
+ * that do not allow methods other than GET or POST.
+ */
+public class AndroidGDataClient implements GDataClient {
+
+    private static final String TAG = "GDataClient";
+    private static final boolean DEBUG = false;
+    private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
+
+    private static final String X_HTTP_METHOD_OVERRIDE =
+        "X-HTTP-Method-Override";
+
+    private static final String DEFAULT_USER_AGENT_APP_VERSION = "Android-GData/1.2";
+
+    private static final int MAX_REDIRECTS = 10;
+    private static String DEFAULT_GDATA_VERSION = "2.0";
+
+
+    private String mGDataVersion; 
+    private final GoogleHttpClient mHttpClient;
+    private ContentResolver mResolver;
+
+    /**
+     * Interface for creating HTTP requests.  Used by
+     * {@link AndroidGDataClient#createAndExecuteMethod}, since HttpUriRequest does not allow for
+     * changing the URI after creation, e.g., when you want to follow a redirect.
+     */
+    private interface HttpRequestCreator {
+        HttpUriRequest createRequest(URI uri);
+    }
+
+    private static class GetRequestCreator implements HttpRequestCreator {
+        public GetRequestCreator() {
+        }
+
+        public HttpUriRequest createRequest(URI uri) {
+            HttpGet get = new HttpGet(uri);
+            return get;
+        }
+    }
+
+    private static class PostRequestCreator implements HttpRequestCreator {
+        private final String mMethodOverride;
+        private final HttpEntity mEntity;
+        public PostRequestCreator(String methodOverride, HttpEntity entity) {
+            mMethodOverride = methodOverride;
+            mEntity = entity;
+        }
+
+        public HttpUriRequest createRequest(URI uri) {
+            HttpPost post = new HttpPost(uri);
+            if (mMethodOverride != null) {
+                post.addHeader(X_HTTP_METHOD_OVERRIDE, mMethodOverride);
+            }
+            post.setEntity(mEntity);
+            return post;
+        }
+    }
+
+    // MAJOR TODO: make this work across redirects (if we can reset the InputStream).
+    // OR, read the bits into a local buffer (yuck, the media could be large).
+    private static class MediaPutRequestCreator implements HttpRequestCreator {
+        private final InputStream mMediaInputStream;
+        private final String mContentType;
+        public MediaPutRequestCreator(InputStream mediaInputStream, String contentType) {
+            mMediaInputStream = mediaInputStream;
+            mContentType = contentType;
+        }
+
+        public HttpUriRequest createRequest(URI uri) {
+            HttpPost post = new HttpPost(uri);
+            post.addHeader(X_HTTP_METHOD_OVERRIDE, "PUT");
+            // mMediaInputStream.reset();
+            InputStreamEntity entity = new InputStreamEntity(mMediaInputStream,
+                    -1 /* read until EOF */);
+            entity.setContentType(mContentType);
+            post.setEntity(entity);
+            return post;
+        }
+    }
+
+   
+    /**
+     * Creates a new AndroidGDataClient.
+     * 
+     * @param context The ContentResolver to get URL rewriting rules from
+     * through the Android proxy server, using null to indicate not using proxy.
+     * The context will also be used by GoogleHttpClient for configuration of 
+     * SSL session persistence.
+     */
+    public AndroidGDataClient(Context context) {
+       this(context, DEFAULT_USER_AGENT_APP_VERSION);
+    }
+
+    /**
+     * Creates a new AndroidGDataClient.
+     *
+     * @param context The ContentResolver to get URL rewriting rules from
+     * through the Android proxy server, using null to indicate not using proxy.
+     * The context will also be used by GoogleHttpClient for configuration of
+     * SSL session persistence.
+     * @param appAndVersion The application name and version to be used as the basis of the
+     * User-Agent.  e.g., Android-GData/1.5.0.
+     */
+    public AndroidGDataClient(Context context, String appAndVersion) {
+        this(context, appAndVersion, DEFAULT_GDATA_VERSION);
+    }
+
+    /**
+     * Creates a new AndroidGDataClient.
+     *
+     * @param context The ContentResolver to get URL rewriting rules from
+     * through the Android proxy server, using null to indicate not using proxy.
+     * The context will also be used by GoogleHttpClient for configuration of
+     * SSL session persistence.
+     * @param appAndVersion The application name and version to be used as the basis of the
+     * User-Agent.  e.g., Android-GData/1.5.0. 
+     * @param gdataVersion The gdata service version that should be 
+     * used, e.g. "2.0" 
+     *  
+     */
+    public AndroidGDataClient(Context context, String appAndVersion, String gdataVersion) {
+        mHttpClient = new GoogleHttpClient(context, appAndVersion,
+                true /* gzip capable */);
+        mHttpClient.enableCurlLogging(TAG, Log.VERBOSE);
+        mResolver = context.getContentResolver();
+        mGDataVersion = gdataVersion;
+    }
+
+
+    public void close() {
+        mHttpClient.close();
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see GDataClient#encodeUri(java.lang.String)
+     */
+    public String encodeUri(String uri) {
+        String encodedUri;
+        try {
+            encodedUri = URLEncoder.encode(uri, "UTF-8");
+        } catch (UnsupportedEncodingException uee) {
+            // should not happen.
+            Log.e("JakartaGDataClient",
+                  "UTF-8 not supported -- should not happen.  "
+                  + "Using default encoding.", uee);
+            encodedUri = URLEncoder.encode(uri);
+        }
+        return encodedUri;
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see com.google.wireless.gdata.client.GDataClient#createQueryParams()
+     */
+    public QueryParams createQueryParams() {
+        return new QueryParamsImpl();
+    }
+
+    // follows redirects
+    private InputStream createAndExecuteMethod(HttpRequestCreator creator,
+                                               String uriString,
+                                               String authToken,
+                                               String eTag,
+                                               String protocolVersion)
+        throws HttpException, IOException {
+
+        HttpResponse response = null;
+        int status = 500;
+        int redirectsLeft = MAX_REDIRECTS;
+
+        URI uri;
+        try {
+            uri = new URI(uriString);
+        } catch (URISyntaxException use) {
+            Log.w(TAG, "Unable to parse " + uriString + " as URI.", use);
+            throw new IOException("Unable to parse " + uriString + " as URI: "
+                    + use.getMessage());
+        }
+
+        // we follow redirects ourselves, since we want to follow redirects even on POSTs, which
+        // the HTTP library does not do.  following redirects ourselves also allows us to log
+        // the redirects using our own logging.
+        while (redirectsLeft > 0) {
+
+            HttpUriRequest request = creator.createRequest(uri);
+
+            AndroidHttpClient.modifyRequestToAcceptGzipResponse(request);
+            // only add the auth token if not null (to allow for GData feeds that do not require
+            // authentication.)
+            if (!TextUtils.isEmpty(authToken)) {
+                request.addHeader("Authorization", "GoogleLogin auth=" + authToken);
+            }
+
+            // while by default we have a 2.0 in this variable, it is possible to construct
+            // a client that has an empty version field, to work with 1.0 services. 
+            if (!TextUtils.isEmpty(mGDataVersion)) {
+                request.addHeader("GData-Version", mGDataVersion);
+            }
+
+            // if we have a passed down eTag value, we need to add several headers
+            if (!TextUtils.isEmpty(eTag)) { 
+                String method = request.getMethod();
+                if ("GET".equals(method)) {
+                    // add the none match header, if the resource is not changed
+                    // this request will result in a 304 now.
+                    request.addHeader("If-None-Match", eTag);
+                } else if ("DELETE".equals(method) 
+                           || "PUT".equals(method)) {
+                    // now we send an if-match, but only if the passed in eTag is a strong eTag
+                    // as this only makes sense for a strong eTag
+                     if (eTag.startsWith("W/") == false) {
+                         request.addHeader("If-Match", eTag);
+                     }
+                }
+            }
+
+
+            if (LOCAL_LOGV) {
+                for (Header h : request.getAllHeaders()) {
+                    Log.v(TAG, h.getName() + ": " + h.getValue());
+                }
+            }
+
+            if (Log.isLoggable(TAG, Log.DEBUG)) {
+                    Log.d(TAG, "Executing " + request.getRequestLine().toString());
+            }
+
+            response = null;
+
+            try {
+                response = mHttpClient.execute(request);
+            } catch (IOException ioe) {
+                Log.w(TAG, "Unable to execute HTTP request." + ioe);
+                throw ioe;
+            }
+
+            StatusLine statusLine = response.getStatusLine();
+            if (statusLine == null) {
+                Log.w(TAG, "StatusLine is null.");
+                throw new NullPointerException("StatusLine is null -- should not happen.");
+            }
+
+            if (Log.isLoggable(TAG, Log.DEBUG)) {
+                Log.d(TAG, response.getStatusLine().toString());
+                for (Header h : response.getAllHeaders()) {
+                    Log.d(TAG, h.getName() + ": " + h.getValue());
+                }
+            }
+            status = statusLine.getStatusCode();
+
+            HttpEntity entity = response.getEntity();
+
+            if ((status >= 200) && (status < 300) && entity != null) {
+                InputStream in = AndroidHttpClient.getUngzippedContent(entity);
+                if (Log.isLoggable(TAG, Log.DEBUG)) {
+                    in = logInputStreamContents(in);
+                }
+                return in;
+            }
+
+            // TODO: handle 301, 307?
+            // TODO: let the http client handle the redirects, if we can be sure we'll never get a
+            // redirect on POST.
+            if (status == 302) {
+                // consume the content, so the connection can be closed.
+                entity.consumeContent();
+                Header location = response.getFirstHeader("Location");
+                if (location == null) {
+                    if (Log.isLoggable(TAG, Log.DEBUG)) {
+                        Log.d(TAG, "Redirect requested but no Location "
+                                + "specified.");
+                    }
+                    break;
+                }
+                if (Log.isLoggable(TAG, Log.DEBUG)) {
+                    Log.d(TAG, "Following redirect to " + location.getValue());
+                }
+                try {
+                    uri = new URI(location.getValue());
+                } catch (URISyntaxException use) {
+                    if (Log.isLoggable(TAG, Log.DEBUG)) {
+                        Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use);
+                        throw new IOException("Unable to parse " + location.getValue()
+                                + " as URI.");
+                    }
+                    break;
+                }
+                --redirectsLeft;
+            } else {
+                break;
+            }
+        }
+
+        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+            Log.v(TAG, "Received " + status + " status code.");
+        }
+        String errorMessage = null;
+        HttpEntity entity = response.getEntity();
+        try {
+            if (response != null && entity != null) {
+                InputStream in = AndroidHttpClient.getUngzippedContent(entity);
+                ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                byte[] buf = new byte[8192];
+                int bytesRead = -1;
+                while ((bytesRead = in.read(buf)) != -1) {
+                    baos.write(buf, 0, bytesRead);
+                }
+                // TODO: use appropriate encoding, picked up from Content-Type.
+                errorMessage = new String(baos.toByteArray());
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, errorMessage);
+                }
+            }
+        } finally {
+            if (entity != null) {
+                entity.consumeContent();
+            }
+        }
+        String exceptionMessage = "Received " + status + " status code";
+        if (errorMessage != null) {
+            exceptionMessage += (": " + errorMessage);
+        }
+        throw new HttpException(exceptionMessage, status, null /* InputStream */);
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see GDataClient#getFeedAsStream(java.lang.String, java.lang.String)
+     */
+    public InputStream getFeedAsStream(String feedUrl,
+                                       String authToken,
+                                       String eTag,
+                                       String protocolVersion)
+        throws HttpException, IOException {
+
+        InputStream in = createAndExecuteMethod(new GetRequestCreator(), feedUrl, authToken, eTag, protocolVersion);
+        if (in != null) {
+            return in;
+        }
+        throw new IOException("Unable to access feed.");
+    }
+
+    /**
+     * Log the contents of the input stream.
+     * The original input stream is consumed, so the caller must use the
+     * BufferedInputStream that is returned.
+     * @param in InputStream
+     * @return replacement input stream for caller to use
+     * @throws IOException
+     */
+    private InputStream logInputStreamContents(InputStream in) throws IOException {
+        if (in == null) {
+            return in;
+        }
+        // bufferSize is the (arbitrary) maximum amount to log.
+        // The original InputStream is wrapped in a
+        // BufferedInputStream with a 16K buffer.  This lets
+        // us read up to 16K, write it to the log, and then
+        // reset the stream so the the original client can
+        // then read the data.  The BufferedInputStream
+        // provides the mark and reset support, even when
+        // the original InputStream does not.
+        final int bufferSize = 16384;
+        BufferedInputStream bin = new BufferedInputStream(in, bufferSize);
+        bin.mark(bufferSize);
+        int wanted = bufferSize;
+        int totalReceived = 0;
+        byte buf[] = new byte[wanted];
+        while (wanted > 0) {
+            int got = bin.read(buf, totalReceived, wanted);
+            if (got <= 0) break; // EOF
+            wanted -= got;
+            totalReceived += got;
+        }
+        Log.d(TAG, new String(buf, 0, totalReceived, "UTF-8"));
+        bin.reset();
+        return bin;
+    }
+
+    public InputStream getMediaEntryAsStream(String mediaEntryUrl, String authToken, String eTag, String protocolVersion)
+            throws HttpException, IOException {
+
+        InputStream in = createAndExecuteMethod(new GetRequestCreator(), mediaEntryUrl, authToken, eTag, protocolVersion);
+
+        if (in != null) {
+            return in;
+        }
+        throw new IOException("Unable to access media entry.");
+    }
+
+    /* (non-Javadoc)
+    * @see GDataClient#createEntry
+    */
+    public InputStream createEntry(String feedUrl,
+                                   String authToken,
+                                   String protocolVersion, 
+                                   GDataSerializer entry)
+        throws HttpException, IOException {
+
+        HttpEntity entity = createEntityForEntry(entry, GDataSerializer.FORMAT_CREATE);
+        InputStream in = createAndExecuteMethod(
+                new PostRequestCreator(null /* override */, entity),
+                feedUrl,
+                authToken,
+                null,
+                protocolVersion);
+        if (in != null) {
+            return in;
+        }
+        throw new IOException("Unable to create entry.");
+    }
+
+    /* (non-Javadoc)
+     * @see GDataClient#updateEntry
+     */
+    public InputStream updateEntry(String editUri,
+                                   String authToken,
+                                   String eTag,
+                                   String protocolVersion, 
+                                   GDataSerializer entry)
+        throws HttpException, IOException {
+        HttpEntity entity = createEntityForEntry(entry, GDataSerializer.FORMAT_UPDATE);
+        InputStream in = createAndExecuteMethod(
+                new PostRequestCreator("PUT", entity),
+                editUri,
+                authToken,
+                eTag,
+                protocolVersion);
+        if (in != null) {
+            return in;
+        }
+        throw new IOException("Unable to update entry.");
+    }
+
+    /* (non-Javadoc)
+     * @see GDataClient#deleteEntry
+     */
+    public void deleteEntry(String editUri, String authToken, String eTag)
+        throws HttpException, IOException {
+        if (StringUtils.isEmpty(editUri)) {
+            throw new IllegalArgumentException(
+                    "you must specify an non-empty edit url");
+        }
+        InputStream in =
+            createAndExecuteMethod(
+                    new PostRequestCreator("DELETE", null /* entity */),
+                    editUri,
+                    authToken,
+                    eTag,
+                    null /* protocolVersion, not required for a delete */);
+        if (in == null) {
+            throw new IOException("Unable to delete entry.");
+        }
+        try {
+            in.close();
+        } catch (IOException ioe) {
+            // ignore
+        }
+    }
+
+    public InputStream updateMediaEntry(String editUri, String authToken, String eTag,
+            String protocolVersion, InputStream mediaEntryInputStream, String contentType)
+        throws HttpException, IOException {
+        InputStream in = createAndExecuteMethod(
+                new MediaPutRequestCreator(mediaEntryInputStream, contentType),
+                editUri,
+                authToken,
+                eTag,
+                protocolVersion);
+        if (in != null) {
+            return in;
+        }
+        throw new IOException("Unable to write media entry.");
+    }
+
+    private HttpEntity createEntityForEntry(GDataSerializer entry, int format) throws IOException {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        try {
+            entry.serialize(baos, format);
+        } catch (IOException ioe) {
+            Log.e(TAG, "Unable to serialize entry.", ioe);
+            throw ioe;
+        } catch (ParseException pe) {
+            Log.e(TAG, "Unable to serialize entry.", pe);
+            throw new IOException("Unable to serialize entry: " + pe.getMessage());
+        }
+
+        byte[] entryBytes = baos.toByteArray();
+
+        if (entryBytes != null && Log.isLoggable(TAG, Log.DEBUG)) {
+            try {
+                Log.d(TAG, "Serialized entry: " + new String(entryBytes, "UTF-8"));
+            } catch (UnsupportedEncodingException uee) {
+                // should not happen
+                throw new IllegalStateException("UTF-8 should be supported!",
+                        uee);
+            }
+        }
+
+        AbstractHttpEntity entity = AndroidHttpClient.getCompressedEntity(entryBytes, mResolver);
+        entity.setContentType(entry.getContentType());
+        return entity;
+    }
+
+    /**
+     * Connects to a GData server (specified by the batchUrl) and submits a
+     * batch for processing.  The response from the server is returned as an
+     * {@link InputStream}.  The caller is responsible for calling
+     * {@link InputStream#close()} on the returned {@link InputStream}.
+     *
+     * @param batchUrl The batch url to which the batch is submitted.
+     * @param authToken the authentication token that should be used when
+     * submitting the batch.
+     * @param protocolVersion The version of the protocol that 
+     *                 should be used for this request.
+     * @param batch The batch of entries to submit.
+     * @throws IOException Thrown if an io error occurs while communicating with
+     * the service.
+     * @throws HttpException if the service returns an error response.
+     */
+    public InputStream submitBatch(String batchUrl,
+       String authToken,
+       String protocolVersion,
+       GDataSerializer batch)
+       throws HttpException, IOException
+    {
+        HttpEntity entity = createEntityForEntry(batch, GDataSerializer.FORMAT_BATCH);
+        InputStream in = createAndExecuteMethod(
+                new PostRequestCreator("POST", entity),
+                batchUrl,
+                authToken,
+                null,
+                protocolVersion);
+        if (in != null) {
+            return in;
+        }
+        throw new IOException("Unable to process batch request.");
+    }
+}   
+
diff --git a/core/java/com/google/android/gdata2/client/AndroidXmlParserFactory.java b/core/java/com/google/android/gdata2/client/AndroidXmlParserFactory.java
new file mode 100644
index 0000000..f097706
--- /dev/null
+++ b/core/java/com/google/android/gdata2/client/AndroidXmlParserFactory.java
@@ -0,0 +1,31 @@
+package com.google.android.gdata2.client;
+
+import com.google.wireless.gdata2.parser.xml.XmlParserFactory;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
+
+import android.util.Xml;
+
+/**
+ * XmlParserFactory for the Android platform.
+ */
+public class AndroidXmlParserFactory implements XmlParserFactory {
+
+    /*
+     * (non-javadoc)
+     * @see XmlParserFactory#createParser
+     */
+    public XmlPullParser createParser() throws XmlPullParserException {
+        return Xml.newPullParser();
+    }
+
+    /*
+     * (non-javadoc)
+     * @see XmlParserFactory#createSerializer
+     */
+    public XmlSerializer createSerializer() throws XmlPullParserException {
+        return Xml.newSerializer();
+    }
+}
diff --git a/core/java/com/google/android/gdata2/client/QueryParamsImpl.java b/core/java/com/google/android/gdata2/client/QueryParamsImpl.java
new file mode 100644
index 0000000..a26f4ce
--- /dev/null
+++ b/core/java/com/google/android/gdata2/client/QueryParamsImpl.java
@@ -0,0 +1,99 @@
+package com.google.android.gdata2.client;
+import com.google.wireless.gdata2.client.QueryParams;
+
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Simple implementation of the QueryParams interface.
+ */
+// TODO: deal with categories
+public class QueryParamsImpl extends QueryParams {
+
+    private final Map<String,String> mParams = new HashMap<String,String>();
+
+    /**
+     * Creates a new empty QueryParamsImpl.
+     */
+    public QueryParamsImpl() {
+    }
+
+    @Override
+    public void clear() {
+        setEntryId(null);
+        mParams.clear();
+    }
+
+    @Override
+    public String generateQueryUrl(String feedUrl) {
+
+        if (TextUtils.isEmpty(getEntryId()) &&
+            mParams.isEmpty()) {
+            // nothing to do
+            return feedUrl;
+        }
+
+        // handle entry IDs
+        if (!TextUtils.isEmpty(getEntryId())) {
+            if (!mParams.isEmpty()) {
+                throw new IllegalStateException("Cannot set both an entry ID "
+                        + "and other query paramters.");
+            }
+            return feedUrl + '/' + getEntryId();
+        }
+
+        // otherwise, append the querystring params.
+        StringBuilder sb = new StringBuilder();
+        sb.append(feedUrl);
+        Set<String> params = mParams.keySet();
+        boolean first = true;
+        if (feedUrl.contains("?")) {
+            first = false;
+        } else {
+            sb.append('?');
+        }
+        for (String param : params) {
+            if (first) {
+                first = false;
+            } else {
+                sb.append('&');
+            }
+            sb.append(param);
+            sb.append('=');
+            String value = mParams.get(param);
+            String encodedValue = null;
+
+            try {
+                encodedValue = URLEncoder.encode(value, "UTF-8");
+            } catch (UnsupportedEncodingException uee) {
+                // should not happen.
+                Log.w("QueryParamsImpl",
+                      "UTF-8 not supported -- should not happen.  "
+                      + "Using default encoding.", uee);
+                encodedValue = URLEncoder.encode(value);
+            }
+            sb.append(encodedValue);
+        }
+        return sb.toString();
+    }
+
+    @Override
+    public String getParamValue(String param) {
+        if (!(mParams.containsKey(param))) {
+            return null;
+        }
+        return mParams.get(param);
+    }
+
+    @Override
+    public void setParamValue(String param, String value) {
+        mParams.put(param, value);
+    }
+
+}
diff --git a/core/java/com/google/android/mms/pdu/EncodedStringValue.java b/core/java/com/google/android/mms/pdu/EncodedStringValue.java
index 7696c5e..a27962d 100644
--- a/core/java/com/google/android/mms/pdu/EncodedStringValue.java
+++ b/core/java/com/google/android/mms/pdu/EncodedStringValue.java
@@ -269,4 +269,16 @@
 
         return new EncodedStringValue(value.mCharacterSet, value.mData);
     }
+    
+    public static EncodedStringValue[] encodeStrings(String[] array) {
+        int count = array.length;
+        if (count > 0) {
+            EncodedStringValue[] encodedArray = new EncodedStringValue[count];
+            for (int i = 0; i < count; i++) {
+                encodedArray[i] = new EncodedStringValue(array[i]);
+            }
+            return encodedArray;
+        }
+        return null;
+    }
 }
diff --git a/core/java/com/google/android/mms/pdu/PduPersister.java b/core/java/com/google/android/mms/pdu/PduPersister.java
index d2a41f1..74af7650 100644
--- a/core/java/com/google/android/mms/pdu/PduPersister.java
+++ b/core/java/com/google/android/mms/pdu/PduPersister.java
@@ -31,6 +31,7 @@
 import android.database.Cursor;
 import android.database.DatabaseUtils;
 import android.net.Uri;
+import android.provider.Telephony;
 import android.provider.Telephony.Mms;
 import android.provider.Telephony.MmsSms;
 import android.provider.Telephony.Threads;
@@ -54,6 +55,8 @@
 import java.util.Set;
 import java.util.Map.Entry;
 
+import com.google.android.mms.pdu.EncodedStringValue;
+
 /**
  * This class is the high-level manager of PDU storage.
  */
@@ -159,6 +162,7 @@
         Part.CONTENT_TYPE,
         Part.FILENAME,
         Part.NAME,
+        Part.TEXT
     };
 
     private static final int PART_COLUMN_ID                  = 0;
@@ -169,6 +173,7 @@
     private static final int PART_COLUMN_CONTENT_TYPE        = 5;
     private static final int PART_COLUMN_FILENAME            = 6;
     private static final int PART_COLUMN_NAME                = 7;
+    private static final int PART_COLUMN_TEXT                = 8;
 
     private static final HashMap<Uri, Integer> MESSAGE_BOX_MAP;
     // These map are used for convenience in persist() and load().
@@ -414,26 +419,36 @@
                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
                     InputStream is = null;
 
-                    try {
-                        is = mContentResolver.openInputStream(partURI);
+                    // Store simple string values directly in the database instead of an
+                    // external file.  This makes the text searchable and retrieval slightly
+                    // faster.
+                    if ("text/plain".equals(type) || "application/smil".equals(type)) {
+                        String text = c.getString(PART_COLUMN_TEXT);
+                        byte [] blob = new EncodedStringValue(text).getTextString();
+                        baos.write(blob, 0, blob.length);
+                    } else {
 
-                        byte[] buffer = new byte[256];
-                        int len = is.read(buffer);
-                        while (len >= 0) {
-                            baos.write(buffer, 0, len);
-                            len = is.read(buffer);
-                        }
-                    } catch (IOException e) {
-                        Log.e(TAG, "Failed to load part data", e);
-                        c.close();
-                        throw new MmsException(e);
-                    } finally {
-                        if (is != null) {
-                            try {
-                                is.close();
-                            } catch (IOException e) {
-                                Log.e(TAG, "Failed to close stream", e);
-                            } // Ignore
+                        try {
+                            is = mContentResolver.openInputStream(partURI);
+
+                            byte[] buffer = new byte[256];
+                            int len = is.read(buffer);
+                            while (len >= 0) {
+                                baos.write(buffer, 0, len);
+                                len = is.read(buffer);
+                            }
+                        } catch (IOException e) {
+                            Log.e(TAG, "Failed to load part data", e);
+                            c.close();
+                            throw new MmsException(e);
+                        } finally {
+                            if (is != null) {
+                                try {
+                                    is.close();
+                                } catch (IOException e) {
+                                    Log.e(TAG, "Failed to close stream", e);
+                                } // Ignore
+                            }
                         }
                     }
                     part.setData(baos.toByteArray());
@@ -719,29 +734,37 @@
         InputStream is = null;
 
         try {
-            os = mContentResolver.openOutputStream(uri);
             byte[] data = part.getData();
-            if (data == null) {
-                Uri dataUri = part.getDataUri();
-                if ((dataUri == null) || (dataUri == uri)) {
-                    Log.w(TAG, "Can't find data for this part.");
-                    return;
-                }
-                is = mContentResolver.openInputStream(dataUri);
-                
-                if (LOCAL_LOGV) {
-                    Log.v(TAG, "Saving data to: " + uri);
-                }
-
-                byte[] buffer = new byte[256];
-                for (int len = 0; (len = is.read(buffer)) != -1; ) {
-                    os.write(buffer, 0, len);
+            if ("text/plain".equals(contentType) || "application/smil".equals(contentType)) {
+                ContentValues cv = new ContentValues();
+                cv.put(Telephony.Mms.Part.TEXT, new EncodedStringValue(data).getString());
+                if (mContentResolver.update(uri, cv, null, null) != 1) {
+                    throw new MmsException("unable to update " + uri.toString());
                 }
             } else {
-                if (LOCAL_LOGV) {
-                    Log.v(TAG, "Saving data to: " + uri);
+                os = mContentResolver.openOutputStream(uri);
+                if (data == null) {
+                    Uri dataUri = part.getDataUri();
+                    if ((dataUri == null) || (dataUri == uri)) {
+                        Log.w(TAG, "Can't find data for this part.");
+                        return;
+                    }
+                    is = mContentResolver.openInputStream(dataUri);
+
+                    if (LOCAL_LOGV) {
+                        Log.v(TAG, "Saving data to: " + uri);
+                    }
+
+                    byte[] buffer = new byte[256];
+                    for (int len = 0; (len = is.read(buffer)) != -1; ) {
+                        os.write(buffer, 0, len);
+                    }
+                } else {
+                    if (LOCAL_LOGV) {
+                        Log.v(TAG, "Saving data to: " + uri);
+                    }
+                    os.write(data);
                 }
-                os.write(data);
             }
         } catch (FileNotFoundException e) {
             Log.e(TAG, "Failed to open Input/Output stream.", e);
diff --git a/core/java/com/google/android/net/GoogleHttpClient.java b/core/java/com/google/android/net/GoogleHttpClient.java
index 922f5be..8a1298f 100644
--- a/core/java/com/google/android/net/GoogleHttpClient.java
+++ b/core/java/com/google/android/net/GoogleHttpClient.java
@@ -58,8 +58,8 @@
  * and otherwise tweak HTTP requests.
  */
 public class GoogleHttpClient implements HttpClient {
-
     private static final String TAG = "GoogleHttpClient";
+    private static final boolean LOCAL_LOGV = Config.LOGV || false;
 
     /** Exception thrown when a request is blocked by the URL rules. */
     public static class BlockedRequestException extends IOException {
@@ -289,9 +289,7 @@
         wrapper.setURI(uri);
         request = wrapper;
 
-        if (Config.LOGV) {
-            Log.v(TAG, "Rule " + rule.mName + ": " + original + " -> " + rewritten);
-        }
+        if (LOCAL_LOGV) Log.v(TAG, "Rule " + rule.mName + ": " + original + " -> " + rewritten);
         return executeWithoutRewriting(request, context);
     }
 
diff --git a/core/java/com/google/android/net/UrlRules.java b/core/java/com/google/android/net/UrlRules.java
index c269d1b..54d139d 100644
--- a/core/java/com/google/android/net/UrlRules.java
+++ b/core/java/com/google/android/net/UrlRules.java
@@ -20,6 +20,7 @@
 import android.database.Cursor;
 import android.provider.Checkin;
 import android.provider.Settings;
+import android.util.Config;
 import android.util.Log;
 
 import java.util.ArrayList;
@@ -53,6 +54,9 @@
  * </pre>
  */
 public class UrlRules {
+    public static final String TAG = "UrlRules";
+    public static final boolean LOCAL_LOGV = Config.LOGV || false;
+
     /** Thrown when the rewrite rules can't be parsed. */
     public static class RuleFormatException extends Exception {
         public RuleFormatException(String msg) { super(msg); }
@@ -192,10 +196,11 @@
                 Settings.Gservices.PROVISIONING_DIGEST);
         if (sCachedDigest != null && sCachedDigest.equals(digest)) {
             // The digest is the same, so the rules are the same.
+            if (LOCAL_LOGV) Log.v(TAG, "Using cached rules for digest: " + digest);
             return sCachedRules;
         }
 
-        // Get all the Gservices settings with names starting with "url:".
+        if (LOCAL_LOGV) Log.v(TAG, "Scanning for Gservices \"url:*\" rules");
         Cursor cursor = resolver.query(Settings.Gservices.CONTENT_URI,
                 new String[] {
                     Settings.Gservices.NAME,
@@ -210,16 +215,18 @@
                     String name = cursor.getString(0).substring(4);  // "url:X"
                     String value = cursor.getString(1);
                     if (value == null || value.length() == 0) continue;
+                    if (LOCAL_LOGV) Log.v(TAG, "  Rule " + name + ": " + value);
                     rules.add(new Rule(name, value));
                 } catch (RuleFormatException e) {
                     // Oops, Gservices has an invalid rule!  Skip it.
-                    Log.e("UrlRules", "Invalid rule from Gservices", e);
+                    Log.e(TAG, "Invalid rule from Gservices", e);
                     Checkin.logEvent(resolver,
                         Checkin.Events.Tag.GSERVICES_ERROR, e.toString());
                 }
             }
             sCachedRules = new UrlRules(rules.toArray(new Rule[rules.size()]));
             sCachedDigest = digest;
+            if (LOCAL_LOGV) Log.v(TAG, "New rules stored for digest: " + digest);
         } finally {
             cursor.close();
         }
diff --git a/core/jni/.android_server_BluetoothEventLoop.cpp.swp b/core/jni/.android_server_BluetoothEventLoop.cpp.swp
new file mode 100644
index 0000000..d36e403
--- /dev/null
+++ b/core/jni/.android_server_BluetoothEventLoop.cpp.swp
Binary files differ
diff --git a/core/jni/ActivityManager.cpp b/core/jni/ActivityManager.cpp
index 9017827..8950dfb 100644
--- a/core/jni/ActivityManager.cpp
+++ b/core/jni/ActivityManager.cpp
@@ -16,9 +16,9 @@
 
 #include <unistd.h>
 #include <android_runtime/ActivityManager.h>
-#include <utils/IBinder.h>
-#include <utils/IServiceManager.h>
-#include <utils/Parcel.h>
+#include <binder/IBinder.h>
+#include <binder/IServiceManager.h>
+#include <binder/Parcel.h>
 #include <utils/String8.h>
 
 namespace android {
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index 888cb11..36d2684 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -11,10 +11,16 @@
 	LOCAL_CFLAGS += -DPACKED=""
 endif
 
+ifeq ($(WITH_JIT),true)
+	LOCAL_CFLAGS += -DWITH_JIT
+endif
+
 ifneq ($(USE_CUSTOM_RUNTIME_HEAP_MAX),)
   LOCAL_CFLAGS += -DCUSTOM_RUNTIME_HEAP_MAX=$(USE_CUSTOM_RUNTIME_HEAP_MAX)
 endif
 
+LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+
 LOCAL_SRC_FILES:= \
 	ActivityManager.cpp \
 	AndroidRuntime.cpp \
@@ -39,7 +45,6 @@
 	android_text_AndroidCharacter.cpp \
 	android_text_KeyCharacterMap.cpp \
 	android_os_Debug.cpp \
-	android_os_Exec.cpp \
 	android_os_FileUtils.cpp \
 	android_os_MemoryFile.cpp \
 	android_os_ParcelFileDescriptor.cpp \
@@ -104,11 +109,10 @@
 	android_util_FileObserver.cpp \
 	android/opengl/poly_clip.cpp.arm \
 	android/opengl/util.cpp.arm \
-	android_bluetooth_Database.cpp \
 	android_bluetooth_HeadsetBase.cpp \
 	android_bluetooth_common.cpp \
 	android_bluetooth_BluetoothAudioGateway.cpp \
-	android_bluetooth_RfcommSocket.cpp \
+	android_bluetooth_BluetoothSocket.cpp \
 	android_bluetooth_ScoSocket.cpp \
 	android_server_BluetoothDeviceService.cpp \
 	android_server_BluetoothEventLoop.cpp \
@@ -150,11 +154,11 @@
 	libnativehelper \
 	libcutils \
 	libutils \
+	libbinder \
 	libnetutils \
 	libui \
 	libskiagl \
-	libsgl \
-	libcorecg \
+	libskia \
 	libsqlite \
 	libdvm \
 	libEGL \
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index c815301..63dc9e8 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -19,12 +19,12 @@
 //#define LOG_NDEBUG 0
 
 #include <android_runtime/AndroidRuntime.h>
-#include <utils/IBinder.h>
-#include <utils/IServiceManager.h>
+#include <binder/IBinder.h>
+#include <binder/IServiceManager.h>
 #include <utils/Log.h>
 #include <utils/misc.h>
-#include <utils/Parcel.h>
-#include <utils/string_array.h>
+#include <binder/Parcel.h>
+#include <utils/StringArray.h>
 #include <utils/threads.h>
 #include <cutils/properties.h>
 
@@ -130,7 +130,6 @@
 extern int register_android_os_StatFs(JNIEnv *env);
 extern int register_android_os_SystemProperties(JNIEnv *env);
 extern int register_android_os_Hardware(JNIEnv* env);
-extern int register_android_os_Exec(JNIEnv *env);
 extern int register_android_os_SystemClock(JNIEnv* env);
 extern int register_android_os_FileObserver(JNIEnv *env);
 extern int register_android_os_FileUtils(JNIEnv *env);
@@ -143,10 +142,9 @@
 extern int register_android_text_AndroidCharacter(JNIEnv *env);
 extern int register_android_text_KeyCharacterMap(JNIEnv *env);
 extern int register_android_opengl_classes(JNIEnv *env);
-extern int register_android_bluetooth_Database(JNIEnv* env);
 extern int register_android_bluetooth_HeadsetBase(JNIEnv* env);
 extern int register_android_bluetooth_BluetoothAudioGateway(JNIEnv* env);
-extern int register_android_bluetooth_RfcommSocket(JNIEnv *env);
+extern int register_android_bluetooth_BluetoothSocket(JNIEnv *env);
 extern int register_android_bluetooth_ScoSocket(JNIEnv *env);
 extern int register_android_server_BluetoothDeviceService(JNIEnv* env);
 extern int register_android_server_BluetoothEventLoop(JNIEnv *env);
@@ -509,11 +507,17 @@
     //LOGD("language=%s region=%s\n", language, region);
 }
 
-void AndroidRuntime::start(const char* className, const bool startSystemServer)
+/*
+ * Start the Dalvik Virtual Machine.
+ *
+ * Various arguments, most determined by system properties, are passed in.
+ * The "mOptions" vector is updated.
+ *
+ * Returns 0 on success.
+ */
+int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv)
 {
-    LOGD("\n>>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<\n");
-
-    JNIEnv* env;
+    int result = -1;
     JavaVMInitArgs initArgs;
     JavaVMOption opt;
     char propBuf[PROPERTY_VALUE_MAX];
@@ -522,24 +526,18 @@
     char enableAssertBuf[sizeof("-ea:")-1 + PROPERTY_VALUE_MAX];
     char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX];
     char* stackTraceFile = NULL;
-    char* slashClassName = NULL;
-    char* cp;
     bool checkJni = false;
+    bool checkDexSum = false;
     bool logStdio = false;
-    enum { kEMDefault, kEMIntPortable, kEMIntFast } executionMode = kEMDefault;
+    enum {
+      kEMDefault,
+      kEMIntPortable,
+      kEMIntFast,
+#if defined(WITH_JIT)
+      kEMJitCompiler,
+#endif
+    } executionMode = kEMDefault;
 
-    blockSigpipe();
-
-    /* 
-     * 'startSystemServer == true' means runtime is obslete and not run from 
-     * init.rc anymore, so we print out the boot start event here.
-     */
-    if (startSystemServer) {
-        /* track our progress through the boot sequence */
-        const int LOG_BOOT_PROGRESS_START = 3000;
-        LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START, 
-                       ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
-    }
 
     property_get("dalvik.vm.checkjni", propBuf, "");
     if (strcmp(propBuf, "true") == 0) {
@@ -557,10 +555,19 @@
         executionMode = kEMIntPortable;
     } else if (strcmp(propBuf, "int:fast") == 0) {
         executionMode = kEMIntFast;
+#if defined(WITH_JIT)
+    } else if (strcmp(propBuf, "int:jit") == 0) {
+        executionMode = kEMJitCompiler;
+#endif
     }
 
     property_get("dalvik.vm.stack-trace-file", stackTraceFileBuf, "");
 
+    property_get("dalvik.vm.check-dex-sum", propBuf, "");
+    if (strcmp(propBuf, "true") == 0) {
+        checkDexSum = true;
+    }
+
     property_get("log.redirect-stdio", propBuf, "");
     if (strcmp(propBuf, "true") == 0) {
         logStdio = true;
@@ -572,19 +579,6 @@
     strcpy(jniOptsBuf, "-Xjniopts:");
     property_get("dalvik.vm.jniopts", jniOptsBuf+10, "");
 
-    const char* rootDir = getenv("ANDROID_ROOT");
-    if (rootDir == NULL) {
-        rootDir = "/system";
-        if (!hasDir("/system")) {
-            LOG_FATAL("No root directory specified, and /android does not exist.");
-            return;
-        }
-        setenv("ANDROID_ROOT", rootDir, 1);
-    }
-
-    const char* kernelHack = getenv("LD_ASSUME_KERNEL");
-    //LOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
-
     /* route exit() to our handler */
     opt.extraInfo = (void*) runtime_exit;
     opt.optionString = "exit";
@@ -658,6 +652,10 @@
         if (opc != NULL) {
             opt.optionString = "-Xgenregmap";
             mOptions.add(opt);
+
+            /* turn on precise GC while we're at it */
+            opt.optionString = "-Xgc:precise";
+            mOptions.add(opt);
         }
     }
 
@@ -697,13 +695,87 @@
         //opt.optionString = "-verbose:jni";
         //mOptions.add(opt);
     }
+
+#if defined(WITH_JIT)
+    /* Minimal profile threshold to trigger JIT compilation */
+    char jitThresholdBuf[sizeof("-Xthreshold:") + PROPERTY_VALUE_MAX];
+    property_get("dalvik.vm.jit.threshold", propBuf, "");
+    if (strlen(propBuf) > 0) {
+        strcpy(jitThresholdBuf, "-Xthreshold:");
+        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, "");
+    if (strlen(propBuf) > 0) {
+        strcpy(jitOpBuf, "-Xjitop:");
+        strcat(jitOpBuf, propBuf);
+        opt.optionString = jitOpBuf;
+        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, "");
+    if (strlen(propBuf) > 0) {
+        strcpy(jitMethodBuf, "-Xjitmethod:");
+        strcat(jitMethodBuf, propBuf);
+        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);
+    }
+#endif
+
     if (executionMode == kEMIntPortable) {
         opt.optionString = "-Xint:portable";
         mOptions.add(opt);
     } else if (executionMode == kEMIntFast) {
         opt.optionString = "-Xint:fast";
         mOptions.add(opt);
+#if defined(WITH_JIT)
+    } else if (executionMode == kEMJitCompiler) {
+        opt.optionString = "-Xint:jit";
+        mOptions.add(opt);
+#endif
     }
+
+    if (checkDexSum) {
+        /* perform additional DEX checksum tests */
+        opt.optionString = "-Xcheckdexsum";
+        mOptions.add(opt);
+    }
+
     if (logStdio) {
         /* convert stdout/stderr to log messages */
         opt.optionString = "-Xlog-stdio";
@@ -771,11 +843,61 @@
      * If this call succeeds, the VM is ready, and we can start issuing
      * JNI calls.
      */
-    if (JNI_CreateJavaVM(&mJavaVM, &env, &initArgs) < 0) {
+    if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
         LOGE("JNI_CreateJavaVM failed\n");
         goto bail;
     }
 
+    result = 0;
+
+bail:
+    free(stackTraceFile);
+    return result;
+}
+
+/*
+ * Start the Android runtime.  This involves starting the virtual machine
+ * and calling the "static void main(String[] args)" method in the class
+ * named by "className".
+ */
+void AndroidRuntime::start(const char* className, const bool startSystemServer)
+{
+    LOGD("\n>>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<\n");
+
+    char* slashClassName = NULL;
+    char* cp;
+    JNIEnv* env;
+
+    blockSigpipe();
+
+    /* 
+     * 'startSystemServer == true' means runtime is obslete and not run from 
+     * init.rc anymore, so we print out the boot start event here.
+     */
+    if (startSystemServer) {
+        /* track our progress through the boot sequence */
+        const int LOG_BOOT_PROGRESS_START = 3000;
+        LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START, 
+                       ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
+    }
+
+    const char* rootDir = getenv("ANDROID_ROOT");
+    if (rootDir == NULL) {
+        rootDir = "/system";
+        if (!hasDir("/system")) {
+            LOG_FATAL("No root directory specified, and /android does not exist.");
+            goto bail;
+        }
+        setenv("ANDROID_ROOT", rootDir, 1);
+    }
+
+    //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
+    //LOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
+
+    /* start the virtual machine */
+    if (startVm(&mJavaVM, &env) != 0)
+        goto bail;
+
     /*
      * Register android functions.
      */
@@ -845,7 +967,6 @@
 
 bail:
     free(slashClassName);
-    free(stackTraceFile);
 }
 
 void AndroidRuntime::start()
@@ -1095,7 +1216,6 @@
     REG_JNI(register_android_database_SQLiteQuery),
     REG_JNI(register_android_database_SQLiteStatement),
     REG_JNI(register_android_os_Debug),
-    REG_JNI(register_android_os_Exec),
     REG_JNI(register_android_os_FileObserver),
     REG_JNI(register_android_os_FileUtils),
     REG_JNI(register_android_os_ParcelFileDescriptor),
@@ -1117,10 +1237,9 @@
     REG_JNI(register_android_media_ToneGenerator),
 
     REG_JNI(register_android_opengl_classes),
-    REG_JNI(register_android_bluetooth_Database),
     REG_JNI(register_android_bluetooth_HeadsetBase),
     REG_JNI(register_android_bluetooth_BluetoothAudioGateway),
-    REG_JNI(register_android_bluetooth_RfcommSocket),
+    REG_JNI(register_android_bluetooth_BluetoothSocket),
     REG_JNI(register_android_bluetooth_ScoSocket),
     REG_JNI(register_android_server_BluetoothDeviceService),
     REG_JNI(register_android_server_BluetoothEventLoop),
diff --git a/core/jni/CursorWindow.cpp b/core/jni/CursorWindow.cpp
index fb891c9..7864189 100644
--- a/core/jni/CursorWindow.cpp
+++ b/core/jni/CursorWindow.cpp
@@ -18,7 +18,7 @@
 #define LOG_TAG "CursorWindow"
 
 #include <utils/Log.h>
-#include <utils/MemoryDealer.h>
+#include <binder/MemoryDealer.h>
 
 #include <assert.h>
 #include <string.h>
diff --git a/core/jni/CursorWindow.h b/core/jni/CursorWindow.h
index 0fb074f..e98b009 100644
--- a/core/jni/CursorWindow.h
+++ b/core/jni/CursorWindow.h
@@ -21,7 +21,7 @@
 #include <stddef.h>
 #include <stdint.h>
 
-#include <utils/MemoryDealer.h>
+#include <binder/MemoryDealer.h>
 #include <utils/RefBase.h>
 
 #include <jni.h>
diff --git a/core/jni/android/graphics/Bitmap.cpp b/core/jni/android/graphics/Bitmap.cpp
index 3fb07a7..002d3db 100644
--- a/core/jni/android/graphics/Bitmap.cpp
+++ b/core/jni/android/graphics/Bitmap.cpp
@@ -5,7 +5,7 @@
 #include "SkDither.h"

 #include "SkUnPreMultiply.h"

 

-#include "Parcel.h"

+#include <binder/Parcel.h>

 #include "android_util_Binder.h"

 #include "android_nio_utils.h"

 #include "CreateJavaOutputStreamAdaptor.h"

diff --git a/core/jni/android/graphics/Canvas.cpp b/core/jni/android/graphics/Canvas.cpp
index 52acf04..c16a75e 100644
--- a/core/jni/android/graphics/Canvas.cpp
+++ b/core/jni/android/graphics/Canvas.cpp
@@ -23,6 +23,7 @@
 #include "SkGLCanvas.h"
 #include "SkGraphics.h"
 #include "SkImageRef_GlobalPool.h"
+#include "SkPorterDuff.h"
 #include "SkShader.h"
 #include "SkTemplates.h"
 
@@ -324,7 +325,7 @@
  
     static void drawColor__II(JNIEnv* env, jobject, SkCanvas* canvas,
                               jint color, SkPorterDuff::Mode mode) {
-        canvas->drawColor(color, mode);
+        canvas->drawColor(color, SkPorterDuff::ToXfermodeMode(mode));
     }
  
     static void drawPaint(JNIEnv* env, jobject, SkCanvas* canvas,
diff --git a/core/jni/android/graphics/ColorFilter.cpp b/core/jni/android/graphics/ColorFilter.cpp
index b6ec4a2..ebfb209 100644
--- a/core/jni/android/graphics/ColorFilter.cpp
+++ b/core/jni/android/graphics/ColorFilter.cpp
@@ -21,6 +21,7 @@
 
 #include "SkColorFilter.h"
 #include "SkColorMatrixFilter.h"
+#include "SkPorterDuff.h"
 
 namespace android {
 
@@ -32,8 +33,9 @@
     }
 
     static SkColorFilter* CreatePorterDuffFilter(JNIEnv* env, jobject,
-                            jint srcColor, SkPorterDuff::Mode porterDuffMode) {
-        return SkColorFilter::CreatePorterDuffFilter(srcColor, porterDuffMode);
+                            jint srcColor, SkPorterDuff::Mode mode) {
+        return SkColorFilter::CreateModeFilter(srcColor,
+                                           SkPorterDuff::ToXfermodeMode(mode));
     }
  
     static SkColorFilter* CreateLightingFilter(JNIEnv* env, jobject,
diff --git a/core/jni/android/graphics/Path.cpp b/core/jni/android/graphics/Path.cpp
index effb1c8..11c608c 100644
--- a/core/jni/android/graphics/Path.cpp
+++ b/core/jni/android/graphics/Path.cpp
@@ -75,9 +75,8 @@
         return result;
     }
  
-    static void computeBounds(JNIEnv* env, jobject clazz, SkPath* obj, jobject bounds, SkPath::BoundsType btype) {
-        SkRect bounds_;
-        obj->computeBounds(&bounds_, btype);
+    static void computeBounds(JNIEnv* env, jobject clazz, SkPath* obj, jobject bounds, int boundstype) {
+        const SkRect& bounds_ = obj->getBounds();
         GraphicsJNI::rect_to_jrectf(bounds_, env, bounds);
     }
  
diff --git a/core/jni/android/graphics/Region.cpp b/core/jni/android/graphics/Region.cpp
index 1dc0314..723cd37 100644
--- a/core/jni/android/graphics/Region.cpp
+++ b/core/jni/android/graphics/Region.cpp
@@ -134,7 +134,7 @@
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
-#include "Parcel.h"
+#include <binder/Parcel.h>
 #include "android_util_Binder.h"
 
 static SkRegion* Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel)
diff --git a/core/jni/android_bluetooth_BluetoothSocket.cpp b/core/jni/android_bluetooth_BluetoothSocket.cpp
new file mode 100644
index 0000000..9c4f7c7
--- /dev/null
+++ b/core/jni/android_bluetooth_BluetoothSocket.cpp
@@ -0,0 +1,517 @@
+/*
+ * Copyright 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 "BluetoothSocket.cpp"
+
+#include "android_bluetooth_common.h"
+#include "android_runtime/AndroidRuntime.h"
+#include "JNIHelp.h"
+#include "utils/Log.h"
+#include "cutils/abort_socket.h"
+
+#include <stdlib.h>
+#include <errno.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+
+#ifdef HAVE_BLUETOOTH
+#include <bluetooth/bluetooth.h>
+#include <bluetooth/rfcomm.h>
+#include <bluetooth/l2cap.h>
+#include <bluetooth/sco.h>
+#endif
+
+#define TYPE_AS_STR(t) \
+    ((t) == TYPE_RFCOMM ? "RFCOMM" : ((t) == TYPE_SCO ? "SCO" : "L2CAP"))
+
+namespace android {
+
+static jfieldID  field_mAuth;     /* read-only */
+static jfieldID  field_mEncrypt;  /* read-only */
+static jfieldID  field_mType;     /* read-only */
+static jfieldID  field_mAddress;  /* read-only */
+static jfieldID  field_mPort;     /* read-only */
+static jfieldID  field_mSocketData;
+static jmethodID method_BluetoothSocket_ctor;
+static jclass    class_BluetoothSocket;
+
+/* Keep TYPE_RFCOMM etc in sync with BluetoothSocket.java */
+static const int TYPE_RFCOMM = 1;
+static const int TYPE_SCO = 2;
+static const int TYPE_L2CAP = 3;  // TODO: Test l2cap code paths
+
+static struct asocket *get_socketData(JNIEnv *env, jobject obj) {
+    struct asocket *s =
+            (struct asocket *) env->GetIntField(obj, field_mSocketData);
+    if (!s)
+        jniThrowException(env, "java/io/IOException", "null socketData");
+    return s;
+}
+
+static void initSocketFromFdNative(JNIEnv *env, jobject obj, jint fd) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+
+    struct asocket *s = asocket_init(fd);
+
+    if (!s) {
+        LOGV("asocket_init() failed, throwing");
+        jniThrowIOException(env, errno);
+        return;
+    }
+
+    env->SetIntField(obj, field_mSocketData, (jint)s);
+
+    return;
+#endif
+    jniThrowIOException(env, ENOSYS);
+}
+
+static void initSocketNative(JNIEnv *env, jobject obj) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+
+    int fd;
+    int lm = 0;
+    jboolean auth;
+    jboolean encrypt;
+    jint type;
+
+    type = env->GetIntField(obj, field_mType);
+
+    switch (type) {
+    case TYPE_RFCOMM:
+        fd = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
+        break;
+    case TYPE_SCO:
+        fd = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO);
+        break;
+    case TYPE_L2CAP:
+        fd = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);
+        break;
+    default:
+        jniThrowIOException(env, ENOSYS);
+        return;
+    }
+
+    if (fd < 0) {
+        LOGV("socket() failed, throwing");
+        jniThrowIOException(env, errno);
+        return;
+    }
+
+    auth = env->GetBooleanField(obj, field_mAuth);
+    encrypt = env->GetBooleanField(obj, field_mEncrypt);
+
+    /* kernel does not yet support LM for SCO */
+    switch (type) {
+    case TYPE_RFCOMM:
+        lm |= auth ? RFCOMM_LM_AUTH : 0;
+        lm |= encrypt? RFCOMM_LM_ENCRYPT : 0;
+        break;
+    case TYPE_L2CAP:
+        lm |= auth ? L2CAP_LM_AUTH : 0;
+        lm |= encrypt? L2CAP_LM_ENCRYPT : 0;
+        break;
+    }
+
+    if (lm) {
+        if (setsockopt(fd, SOL_RFCOMM, RFCOMM_LM, &lm, sizeof(lm))) {
+            LOGV("setsockopt() failed, throwing");
+            jniThrowIOException(env, errno);
+            return;
+        }
+    }
+
+    LOGV("...fd %d created (%s, lm = %x)", fd, TYPE_AS_STR(type), lm);
+
+    initSocketFromFdNative(env, obj, fd);
+    return;
+#endif
+    jniThrowIOException(env, ENOSYS);
+}
+
+static void connectNative(JNIEnv *env, jobject obj) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+
+    int ret;
+    jint type;
+    const char *c_address;
+    jstring address;
+    bdaddr_t bdaddress;
+    socklen_t addr_sz;
+    struct sockaddr *addr;
+    struct asocket *s = get_socketData(env, obj);
+
+    if (!s)
+        return;
+
+    type = env->GetIntField(obj, field_mType);
+
+    /* parse address into bdaddress */
+    address = (jstring) env->GetObjectField(obj, field_mAddress);
+    c_address = env->GetStringUTFChars(address, NULL);
+    if (get_bdaddr(c_address, &bdaddress)) {
+        env->ReleaseStringUTFChars(address, c_address);
+        jniThrowIOException(env, EINVAL);
+        return;
+    }
+    env->ReleaseStringUTFChars(address, c_address);
+
+    switch (type) {
+    case TYPE_RFCOMM:
+        struct sockaddr_rc addr_rc;
+        addr = (struct sockaddr *)&addr_rc;
+        addr_sz = sizeof(addr_rc);
+
+        memset(addr, 0, addr_sz);
+        addr_rc.rc_family = AF_BLUETOOTH;
+        addr_rc.rc_channel = env->GetIntField(obj, field_mPort);
+        memcpy(&addr_rc.rc_bdaddr, &bdaddress, sizeof(bdaddr_t));
+
+        break;
+    case TYPE_SCO:
+        struct sockaddr_sco addr_sco;
+        addr = (struct sockaddr *)&addr_sco;
+        addr_sz = sizeof(addr_sco);
+
+        memset(addr, 0, addr_sz);
+        addr_sco.sco_family = AF_BLUETOOTH;
+        memcpy(&addr_sco.sco_bdaddr, &bdaddress, sizeof(bdaddr_t));
+
+        break;
+    case TYPE_L2CAP:
+        struct sockaddr_l2 addr_l2;
+        addr = (struct sockaddr *)&addr_l2;
+        addr_sz = sizeof(addr_l2);
+
+        memset(addr, 0, addr_sz);
+        addr_l2.l2_family = AF_BLUETOOTH;
+        addr_l2.l2_psm = env->GetIntField(obj, field_mPort);
+        memcpy(&addr_l2.l2_bdaddr, &bdaddress, sizeof(bdaddr_t));
+
+        break;
+    default:
+        jniThrowIOException(env, ENOSYS);
+        return;
+    }
+
+    ret = asocket_connect(s, addr, addr_sz, -1);
+    LOGV("...connect(%d, %s) = %d (errno %d)",
+            s->fd, TYPE_AS_STR(type), ret, errno);
+
+    if (ret)
+        jniThrowIOException(env, errno);
+
+    return;
+#endif
+    jniThrowIOException(env, ENOSYS);
+}
+
+static void bindListenNative(JNIEnv *env, jobject obj) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+
+    jint type;
+    socklen_t addr_sz;
+    struct sockaddr *addr;
+    bdaddr_t bdaddr = *BDADDR_ANY;
+    struct asocket *s = get_socketData(env, obj);
+
+    if (!s)
+        return;
+
+    type = env->GetIntField(obj, field_mType);
+
+    switch (type) {
+    case TYPE_RFCOMM:
+        struct sockaddr_rc addr_rc;
+        addr = (struct sockaddr *)&addr_rc;
+        addr_sz = sizeof(addr_rc);
+
+        memset(addr, 0, addr_sz);
+        addr_rc.rc_family = AF_BLUETOOTH;
+        addr_rc.rc_channel = env->GetIntField(obj, field_mPort);
+        memcpy(&addr_rc.rc_bdaddr, &bdaddr, sizeof(bdaddr_t));
+        break;
+    case TYPE_SCO:
+        struct sockaddr_sco addr_sco;
+        addr = (struct sockaddr *)&addr_sco;
+        addr_sz = sizeof(addr_sco);
+
+        memset(addr, 0, addr_sz);
+        addr_sco.sco_family = AF_BLUETOOTH;
+        memcpy(&addr_sco.sco_bdaddr, &bdaddr, sizeof(bdaddr_t));
+        break;
+    case TYPE_L2CAP:
+        struct sockaddr_l2 addr_l2;
+        addr = (struct sockaddr *)&addr_l2;
+        addr_sz = sizeof(addr_l2);
+
+        memset(addr, 0, addr_sz);
+        addr_l2.l2_family = AF_BLUETOOTH;
+        addr_l2.l2_psm = env->GetIntField(obj, field_mPort);
+        memcpy(&addr_l2.l2_bdaddr, &bdaddr, sizeof(bdaddr_t));
+        break;
+    default:
+        jniThrowIOException(env, ENOSYS);
+        return;
+    }
+
+    if (bind(s->fd, addr, addr_sz)) {
+        jniThrowIOException(env, errno);
+        return;
+    }
+
+    if (listen(s->fd, 1)) {
+        jniThrowIOException(env, errno);
+        return;
+    }
+
+    return;
+#endif
+    jniThrowIOException(env, ENOSYS);
+}
+
+static jobject acceptNative(JNIEnv *env, jobject obj, int timeout) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+
+    int fd;
+    jint type;
+    struct sockaddr *addr;
+    socklen_t addr_sz;
+    jstring addr_jstr;
+    char addr_cstr[BTADDR_SIZE];
+    bdaddr_t *bdaddr;
+    jboolean auth;
+    jboolean encrypt;
+
+    struct asocket *s = get_socketData(env, obj);
+
+    if (!s)
+        return NULL;
+
+    type = env->GetIntField(obj, field_mType);
+
+    switch (type) {
+    case TYPE_RFCOMM:
+        struct sockaddr_rc addr_rc;
+        addr = (struct sockaddr *)&addr_rc;
+        addr_sz = sizeof(addr_rc);
+        bdaddr = &addr_rc.rc_bdaddr;
+        memset(addr, 0, addr_sz);
+        break;
+    case TYPE_SCO:
+        struct sockaddr_sco addr_sco;
+        addr = (struct sockaddr *)&addr_sco;
+        addr_sz = sizeof(addr_sco);
+        bdaddr = &addr_sco.sco_bdaddr;
+        memset(addr, 0, addr_sz);
+        break;
+    case TYPE_L2CAP:
+        struct sockaddr_l2 addr_l2;
+        addr = (struct sockaddr *)&addr_l2;
+        addr_sz = sizeof(addr_l2);
+        bdaddr = &addr_l2.l2_bdaddr;
+        memset(addr, 0, addr_sz);
+        break;
+    default:
+        jniThrowIOException(env, ENOSYS);
+        return NULL;
+    }
+
+    fd = asocket_accept(s, addr, &addr_sz, timeout);
+
+    LOGV("...accept(%d, %s) = %d (errno %d)",
+            s->fd, TYPE_AS_STR(type), fd, errno);
+
+    if (fd < 0) {
+        jniThrowIOException(env, errno);
+        return NULL;
+    }
+
+    /* Connected - return new BluetoothSocket */
+    auth = env->GetBooleanField(obj, field_mAuth);
+    encrypt = env->GetBooleanField(obj, field_mEncrypt);
+
+    get_bdaddr_as_string(bdaddr, addr_cstr);
+
+    addr_jstr = env->NewStringUTF(addr_cstr);
+    return env->NewObject(class_BluetoothSocket, method_BluetoothSocket_ctor,
+            type, fd, auth, encrypt, addr_jstr, -1);
+
+#endif
+    jniThrowIOException(env, ENOSYS);
+    return NULL;
+}
+
+static jint availableNative(JNIEnv *env, jobject obj) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+
+    int available;
+    struct asocket *s = get_socketData(env, obj);
+
+    if (!s)
+        return -1;
+
+    if (ioctl(s->fd, FIONREAD, &available) < 0) {
+        jniThrowIOException(env, errno);
+        return -1;
+    }
+
+    return available;
+
+#endif
+    jniThrowIOException(env, ENOSYS);
+    return -1;
+}
+
+/** jb must not be null. offset and offset+length must be within array */
+static jint readNative(JNIEnv *env, jobject obj, jbyteArray jb, jint offset,
+        jint length) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+
+    int ret;
+    jbyte *b;
+    struct asocket *s = get_socketData(env, obj);
+
+    if (!s)
+        return -1;
+
+    b = env->GetByteArrayElements(jb, NULL);
+    if (b == NULL) {
+        jniThrowIOException(env, EINVAL);
+        return -1;
+    }
+
+    ret = asocket_read(s, &b[offset], length, -1);
+    if (ret < 0) {
+        jniThrowIOException(env, errno);
+        env->ReleaseByteArrayElements(jb, b, JNI_ABORT);
+        return -1;
+    }
+
+    env->ReleaseByteArrayElements(jb, b, 0);
+    return (jint)ret;
+
+#endif
+    jniThrowIOException(env, ENOSYS);
+    return -1;
+}
+
+/** jb must not be null. offset and offset+length must be within array */
+static jint writeNative(JNIEnv *env, jobject obj, jbyteArray jb, jint offset,
+        jint length) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+
+    int ret;
+    jbyte *b;
+    struct asocket *s = get_socketData(env, obj);
+
+    if (!s)
+        return -1;
+
+    b = env->GetByteArrayElements(jb, NULL);
+    if (b == NULL) {
+        jniThrowIOException(env, EINVAL);
+        return -1;
+    }
+
+    ret = asocket_write(s, &b[offset], length, -1);
+    if (ret < 0) {
+        jniThrowIOException(env, errno);
+        env->ReleaseByteArrayElements(jb, b, JNI_ABORT);
+        return -1;
+    }
+
+    env->ReleaseByteArrayElements(jb, b, JNI_ABORT);  // no need to commit
+    return (jint)ret;
+
+#endif
+    jniThrowIOException(env, ENOSYS);
+    return -1;
+}
+
+static void closeNative(JNIEnv *env, jobject obj) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+    struct asocket *s = get_socketData(env, obj);
+
+    if (!s)
+        return;
+
+    asocket_abort(s);
+
+    LOGV("...asocket_abort(%d) complete", s->fd);
+    return;
+#endif
+    jniThrowIOException(env, ENOSYS);
+}
+
+static void destroyNative(JNIEnv *env, jobject obj) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+    struct asocket *s = get_socketData(env, obj);
+    int fd = s->fd;
+
+    if (!s)
+        return;
+
+    asocket_destroy(s);
+
+    LOGV("...asocket_destroy(%d) complete", fd);
+    return;
+#endif
+    jniThrowIOException(env, ENOSYS);
+}
+
+static JNINativeMethod sMethods[] = {
+    {"initSocketNative", "()V",  (void*) initSocketNative},
+    {"initSocketFromFdNative", "(I)V",  (void*) initSocketFromFdNative},
+    {"connectNative", "()V", (void *) connectNative},
+    {"bindListenNative", "()V", (void *) bindListenNative},
+    {"acceptNative", "(I)Landroid/bluetooth/BluetoothSocket;", (void *) acceptNative},
+    {"availableNative", "()I",    (void *) availableNative},
+    {"readNative", "([BII)I",    (void *) readNative},
+    {"writeNative", "([BII)I",    (void *) writeNative},
+    {"closeNative", "()V",    (void *) closeNative},
+    {"destroyNative", "()V",    (void *) destroyNative},
+};
+
+int register_android_bluetooth_BluetoothSocket(JNIEnv *env) {
+    jclass clazz = env->FindClass("android/bluetooth/BluetoothSocket");
+    if (clazz == NULL)
+        return -1;
+    class_BluetoothSocket = (jclass) env->NewGlobalRef(clazz);
+    field_mType = env->GetFieldID(clazz, "mType", "I");
+    field_mAddress = env->GetFieldID(clazz, "mAddress", "Ljava/lang/String;");
+    field_mPort = env->GetFieldID(clazz, "mPort", "I");
+    field_mAuth = env->GetFieldID(clazz, "mAuth", "Z");
+    field_mEncrypt = env->GetFieldID(clazz, "mEncrypt", "Z");
+    field_mSocketData = env->GetFieldID(clazz, "mSocketData", "I");
+    method_BluetoothSocket_ctor = env->GetMethodID(clazz, "<init>", "(IIZZLjava/lang/String;I)V");
+    return AndroidRuntime::registerNativeMethods(env,
+        "android/bluetooth/BluetoothSocket", sMethods, NELEM(sMethods));
+}
+
+} /* namespace android */
+
diff --git a/core/jni/android_bluetooth_Database.cpp b/core/jni/android_bluetooth_Database.cpp
deleted file mode 100644
index 73b8efd..0000000
--- a/core/jni/android_bluetooth_Database.cpp
+++ /dev/null
@@ -1,184 +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.
- */
-
-#define DBUS_CLASS_NAME BLUEZ_DBUS_BASE_IFC ".Database"
-#define LOG_TAG "bluetooth_Database.cpp"
-
-#include "android_bluetooth_common.h"
-#include "android_runtime/AndroidRuntime.h"
-#include "JNIHelp.h"
-#include "jni.h"
-#include "utils/Log.h"
-
-#ifdef HAVE_BLUETOOTH
-#include <dbus/dbus.h>
-#endif
-
-namespace android {
-
-#ifdef HAVE_BLUETOOTH
-static DBusConnection* conn = NULL;   // Singleton thread-safe connection
-#endif
-
-static void classInitNative(JNIEnv* env, jclass clazz) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    conn = NULL;
-#endif
-}
-
-static void initializeNativeDataNative(JNIEnv* env, jobject object) {
-    LOGV(__FUNCTION__);
-
-#ifdef HAVE_BLUETOOTH
-    if (conn == NULL) {
-        DBusError err;
-        dbus_error_init(&err);
-        dbus_threads_init_default();
-        conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
-        if (dbus_error_is_set(&err)) {
-            LOGE("Could not get onto the system bus!");
-            dbus_error_free(&err);
-        }
-        dbus_connection_set_exit_on_disconnect(conn, FALSE);
-    }
-#endif
-}
-
-static void cleanupNativeDataNative(JNIEnv* env, jobject object) {
-    LOGV(__FUNCTION__);
-}
-
-static jint addServiceRecordNative(JNIEnv *env, jobject object,
-                                   jbyteArray record) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    if (conn != NULL) {
-        jbyte* c_record = env->GetByteArrayElements(record, NULL);
-        DBusMessage *reply = dbus_func_args(env,
-                                            conn,
-                                            BLUEZ_DBUS_BASE_PATH,
-                                            DBUS_CLASS_NAME,
-                                            "AddServiceRecord",
-                                            DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE,
-                                            &c_record,
-                                            env->GetArrayLength(record),
-                                            DBUS_TYPE_INVALID);
-        env->ReleaseByteArrayElements(record, c_record, JNI_ABORT);
-        return reply ? dbus_returns_uint32(env, reply) : -1;
-    }
-#endif
-    return -1;
-}
-
-static jint addServiceRecordFromXmlNative(JNIEnv *env, jobject object,
-                                          jstring record) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    if (conn != NULL) {
-        const char *c_record = env->GetStringUTFChars(record, NULL);
-        DBusMessage *reply = dbus_func_args(env,
-                                            conn,
-                                            BLUEZ_DBUS_BASE_PATH,
-                                            DBUS_CLASS_NAME,
-                                            "AddServiceRecordFromXML",
-                                            DBUS_TYPE_STRING, &c_record,
-                                            DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(record, c_record);
-        return reply ? dbus_returns_uint32(env, reply) : -1;
-    }
-#endif
-    return -1;
-}
-
-static void updateServiceRecordNative(JNIEnv *env, jobject object,
-                                      jint handle,
-                                      jbyteArray record) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    if (conn != NULL) {
-        jbyte* c_record = env->GetByteArrayElements(record, NULL);
-        DBusMessage *reply = dbus_func_args(env,
-                                            conn,
-                                            BLUEZ_DBUS_BASE_PATH,
-                                            DBUS_CLASS_NAME,
-                                            "UpdateServiceRecord",
-                                            DBUS_TYPE_UINT32, &handle,
-                                            DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE,
-                                            &c_record,
-                                            env->GetArrayLength(record),
-                                            DBUS_TYPE_INVALID);
-        env->ReleaseByteArrayElements(record, c_record, JNI_ABORT);
-    }
-#endif
-}
-
-static void updateServiceRecordFromXmlNative(JNIEnv *env, jobject object,
-                                             jint handle,
-                                             jstring record) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    if (conn != NULL) {
-        const char *c_record = env->GetStringUTFChars(record, NULL);
-        DBusMessage *reply = dbus_func_args(env,
-                                            conn,
-                                            BLUEZ_DBUS_BASE_PATH,
-                                            DBUS_CLASS_NAME,
-                                            "UpdateServiceRecordFromXML",
-                                            DBUS_TYPE_UINT32, &handle,
-                                            DBUS_TYPE_STRING, &c_record,
-                                            DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(record, c_record);
-    }
-#endif
-}
-
-/* private static native void removeServiceRecordNative(int handle); */
-static void removeServiceRecordNative(JNIEnv *env, jobject object,
-                                      jint handle) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    if (conn != NULL) {
-        DBusMessage *reply = dbus_func_args(env,
-                                            conn,
-                                            BLUEZ_DBUS_BASE_PATH,
-                                            DBUS_CLASS_NAME,
-                                            "RemoveServiceRecord",
-                                            DBUS_TYPE_UINT32, &handle,
-                                            DBUS_TYPE_INVALID);
-    }
-#endif
-}
-
-
-static JNINativeMethod sMethods[] = {
-     /* name, signature, funcPtr */
-    {"classInitNative", "()V", (void*)classInitNative},
-    {"initializeNativeDataNative", "()V", (void *)initializeNativeDataNative},
-    {"cleanupNativeDataNative", "()V", (void *)cleanupNativeDataNative},
-    {"addServiceRecordNative", "([B)I", (void*)addServiceRecordNative},
-    {"addServiceRecordFromXmlNative", "(Ljava/lang/String;)I", (void*)addServiceRecordFromXmlNative},
-    {"updateServiceRecordNative", "(I[B)V", (void*)updateServiceRecordNative},
-    {"updateServiceRecordFromXmlNative", "(ILjava/lang/String;)V", (void*)updateServiceRecordFromXmlNative},
-    {"removeServiceRecordNative", "(I)V", (void*)removeServiceRecordNative},
-};
-
-int register_android_bluetooth_Database(JNIEnv *env) {
-    return AndroidRuntime::registerNativeMethods(env,
-            "android/bluetooth/Database", sMethods, NELEM(sMethods));
-}
-
-} /* namespace android */
diff --git a/core/jni/android_bluetooth_RfcommSocket.cpp b/core/jni/android_bluetooth_RfcommSocket.cpp
deleted file mode 100644
index 3ed35d9..0000000
--- a/core/jni/android_bluetooth_RfcommSocket.cpp
+++ /dev/null
@@ -1,621 +0,0 @@
-/*
-** Copyright 2006, 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 "bluetooth_RfcommSocket.cpp"
-
-#include "android_bluetooth_common.h"
-#include "android_runtime/AndroidRuntime.h"
-#include "JNIHelp.h"
-#include "jni.h"
-#include "utils/Log.h"
-#include "utils/misc.h"
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/socket.h>
-#include <sys/uio.h>
-#include <sys/poll.h>
-
-#ifdef HAVE_BLUETOOTH
-#include <bluetooth/bluetooth.h>
-#include <bluetooth/rfcomm.h>
-#include <bluetooth/sco.h>
-#endif
-
-namespace android {
-
-#ifdef HAVE_BLUETOOTH
-static jfieldID field_mNativeData;
-static jfieldID field_mTimeoutRemainingMs;
-static jfieldID field_mAcceptTimeoutRemainingMs;
-static jfieldID field_mAddress;
-static jfieldID field_mPort;
-
-typedef struct {
-    jstring address;
-    const char *c_address;
-    int rfcomm_channel;
-    int last_read_err;
-    int rfcomm_sock;
-    // < 0 -- in progress, 
-    //   0 -- not connected
-    // > 0 connected
-    //     1 input is open
-    //     2 output is open
-    //     3 both input and output are open
-    int rfcomm_connected; 
-    int rfcomm_sock_flags;
-} native_data_t;
-
-static inline native_data_t * get_native_data(JNIEnv *env, jobject object) {
-    return (native_data_t *)(env->GetIntField(object, field_mNativeData));
-}
-
-static inline void init_socket_info(
-    JNIEnv *env, jobject object,
-    native_data_t *nat,
-    jstring address,
-    jint rfcomm_channel) {
-    nat->address = (jstring)env->NewGlobalRef(address);
-    nat->c_address = env->GetStringUTFChars(nat->address, NULL);
-    nat->rfcomm_channel = (int)rfcomm_channel;
-}
-
-static inline void cleanup_socket_info(JNIEnv *env, native_data_t *nat) {
-    if (nat->c_address != NULL) {
-        env->ReleaseStringUTFChars(nat->address, nat->c_address);
-        env->DeleteGlobalRef(nat->address);
-        nat->c_address = NULL;
-    }
-}
-#endif
-
-static void classInitNative(JNIEnv* env, jclass clazz) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    field_mNativeData = get_field(env, clazz, "mNativeData", "I");
-    field_mTimeoutRemainingMs = get_field(env, clazz, "mTimeoutRemainingMs", "I");
-    field_mAcceptTimeoutRemainingMs = get_field(env, clazz, "mAcceptTimeoutRemainingMs", "I");
-    field_mAddress = get_field(env, clazz, "mAddress", "Ljava/lang/String;");
-    field_mPort = get_field(env, clazz, "mPort", "I");
-#endif
-}
-
-static void initializeNativeDataNative(JNIEnv* env, jobject object) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-
-    native_data_t *nat = (native_data_t *)calloc(1, sizeof(native_data_t));
-    if (nat == NULL) {
-        LOGE("%s: out of memory!", __FUNCTION__);
-        return;
-    }
-
-    env->SetIntField(object, field_mNativeData, (jint)nat);
-    nat->rfcomm_sock = -1;
-    nat->rfcomm_connected = 0;
-#endif
-}
-
-static void cleanupNativeDataNative(JNIEnv* env, jobject object) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        free(nat);
-    }
-#endif
-}
-
-static jobject createNative(JNIEnv *env, jobject obj) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    int lm;
-    native_data_t *nat = get_native_data(env, obj);
-    nat->rfcomm_sock = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
-
-    if (nat->rfcomm_sock < 0) {
-        LOGE("%s: Could not create RFCOMM socket: %s\n", __FUNCTION__,
-             strerror(errno));
-        return NULL;
-    }
-        
-    lm = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT;
-
-    if (lm && setsockopt(nat->rfcomm_sock, SOL_RFCOMM, RFCOMM_LM, &lm,
-                sizeof(lm)) < 0) {
-        LOGE("%s: Can't set RFCOMM link mode", __FUNCTION__);
-        close(nat->rfcomm_sock);
-        return NULL;
-    }
-
-    return jniCreateFileDescriptor(env, nat->rfcomm_sock);
-#else
-    return NULL;
-#endif
-}
-
-static void destroyNative(JNIEnv *env, jobject obj) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    native_data_t *nat = get_native_data(env, obj);
-    cleanup_socket_info(env, nat);
-    if (nat->rfcomm_sock >= 0) {
-        close(nat->rfcomm_sock);
-        nat->rfcomm_sock = -1;
-    }
-#endif
-}
-
-
-static jboolean connectNative(JNIEnv *env, jobject obj,
-                              jstring address, jint port) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    native_data_t *nat = get_native_data(env, obj);
-
-    if (nat->rfcomm_sock >= 0) {
-        if (nat->rfcomm_connected) {
-            LOGI("RFCOMM socket: %s.",
-                 (nat->rfcomm_connected > 0) ? "already connected" : "connection is in progress");
-            return JNI_TRUE;
-        }
-
-        init_socket_info(env, obj, nat, address, port);
-
-        struct sockaddr_rc addr;
-        memset(&addr, 0, sizeof(struct sockaddr_rc));
-        get_bdaddr(nat->c_address, &addr.rc_bdaddr);
-        addr.rc_channel = nat->rfcomm_channel;
-        addr.rc_family = AF_BLUETOOTH;
-        nat->rfcomm_connected = 0;
-
-        while (nat->rfcomm_connected == 0) {
-            if (connect(nat->rfcomm_sock, (struct sockaddr *)&addr,
-                    sizeof(addr)) < 0) {
-                if (errno == EINTR) continue;
-                LOGE("connect error: %s (%d)\n", strerror(errno), errno);
-                break;
-            } else {
-                nat->rfcomm_connected = 3; // input and output
-            }
-        }
-    } else {
-        LOGE("%s: socket(RFCOMM) error: socket not created", __FUNCTION__);
-    }
-
-    if (nat->rfcomm_connected > 0) {
-        env->SetIntField(obj, field_mPort, port);
-        return JNI_TRUE;
-    }
-#endif
-    return JNI_FALSE;
-}
-
-static jboolean connectAsyncNative(JNIEnv *env, jobject obj,
-                                   jstring address, jint port) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    native_data_t *nat = get_native_data(env, obj);
-
-    if (nat->rfcomm_sock < 0) {
-        LOGE("%s: socket(RFCOMM) error: socket not created", __FUNCTION__);
-        return JNI_FALSE;
-    }
-
-    if (nat->rfcomm_connected) {
-        LOGI("RFCOMM socket: %s.",
-             (nat->rfcomm_connected > 0) ?
-             "already connected" : "connection is in progress");
-        return JNI_TRUE;
-    }
-
-    init_socket_info(env, obj, nat, address, port);
-
-    struct sockaddr_rc addr;
-    memset(&addr, 0, sizeof(struct sockaddr_rc));
-    get_bdaddr(nat->c_address, &addr.rc_bdaddr);
-    addr.rc_channel = nat->rfcomm_channel;
-    addr.rc_family = AF_BLUETOOTH;
-
-    nat->rfcomm_sock_flags = fcntl(nat->rfcomm_sock, F_GETFL, 0);
-    if (fcntl(nat->rfcomm_sock,
-              F_SETFL, nat->rfcomm_sock_flags | O_NONBLOCK) >= 0) {
-        int rc;
-        nat->rfcomm_connected = 0;
-        errno = 0;
-        rc = connect(nat->rfcomm_sock,
-                     (struct sockaddr *)&addr,
-                     sizeof(addr));
-
-        if (rc >= 0) {
-            nat->rfcomm_connected = 3;
-            LOGI("RFCOMM async connect immediately successful");
-            env->SetIntField(obj, field_mPort, port);
-            return JNI_TRUE;
-        }
-        else if (rc < 0) {
-            if (errno == EINPROGRESS || errno == EAGAIN)
-                {
-                    LOGI("RFCOMM async connect is in progress (%s)",
-                         strerror(errno));
-                    nat->rfcomm_connected = -1;
-                    env->SetIntField(obj, field_mPort, port);
-                    return JNI_TRUE;
-                }
-            else
-                {
-                    LOGE("RFCOMM async connect error (%d): %s (%d)",
-                         nat->rfcomm_sock, strerror(errno), errno);
-                    return JNI_FALSE;
-                }
-        }
-    } // fcntl(nat->rfcomm_sock ...)
-#endif
-    return JNI_FALSE;
-}
-
-static jboolean interruptAsyncConnectNative(JNIEnv *env, jobject obj) {
-    //WRITEME
-    return JNI_TRUE;
-}
-
-static jint waitForAsyncConnectNative(JNIEnv *env, jobject obj,
-                                      jint timeout_ms) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    struct sockaddr_rc addr;
-    native_data_t *nat = get_native_data(env, obj);
-
-    env->SetIntField(obj, field_mTimeoutRemainingMs, timeout_ms);
-
-    if (nat->rfcomm_sock < 0) {
-        LOGE("%s: socket(RFCOMM) error: socket not created", __FUNCTION__);
-        return -1;
-    }
-
-    if (nat->rfcomm_connected > 0) {
-        LOGI("%s: RFCOMM is already connected!", __FUNCTION__);
-        return 1;
-    }
-
-    /* Do an asynchronous select() */
-    int n;
-    fd_set rset, wset;
-    struct timeval to;
-
-    FD_ZERO(&rset);
-    FD_ZERO(&wset);
-    FD_SET(nat->rfcomm_sock, &rset);
-    FD_SET(nat->rfcomm_sock, &wset);
-    if (timeout_ms >= 0) {
-        to.tv_sec = timeout_ms / 1000;
-        to.tv_usec = 1000 * (timeout_ms % 1000);
-    }
-    n = select(nat->rfcomm_sock + 1,
-               &rset,
-               &wset,
-               NULL,
-               (timeout_ms < 0 ? NULL : &to));
-
-    if (timeout_ms > 0) {
-        jint remaining = to.tv_sec*1000 + to.tv_usec/1000;
-        LOGI("Remaining time %ldms", (long)remaining);
-        env->SetIntField(obj, field_mTimeoutRemainingMs,
-                         remaining);
-    }
-
-    if (n <= 0) {
-        if (n < 0)  {
-            LOGE("select() on RFCOMM socket: %s (%d)",
-                 strerror(errno),
-                 errno);
-            return -1;
-        }
-        return 0;
-    }
-    /* n must be equal to 1 and either rset or wset must have the
-       file descriptor set. */
-    LOGI("select() returned %d.", n);
-    if (FD_ISSET(nat->rfcomm_sock, &rset) ||
-        FD_ISSET(nat->rfcomm_sock, &wset)) {
-        /* A trial async read() will tell us if everything is OK. */
-        char ch;
-        errno = 0;
-        int nr = read(nat->rfcomm_sock, &ch, 1);
-        /* It should be that nr != 1 because we just opened a socket
-           and we haven't sent anything over it for the other side to
-           respond... but one can't be paranoid enough.
-        */
-        if (nr >= 0 || errno != EAGAIN) {
-            LOGE("RFCOMM async connect() error: %s (%d), nr = %d\n",
-                 strerror(errno),
-                 errno,
-                 nr);
-            /* Clear the rfcomm_connected flag to cause this function
-               to re-create the socket and re-attempt the connect()
-               the next time it is called.
-            */
-            nat->rfcomm_connected = 0;
-            /* Restore the blocking properties of the socket. */
-            fcntl(nat->rfcomm_sock, F_SETFL, nat->rfcomm_sock_flags);
-            return -1;
-        }
-        /* Restore the blocking properties of the socket. */
-        fcntl(nat->rfcomm_sock, F_SETFL, nat->rfcomm_sock_flags);
-        LOGI("Successful RFCOMM socket connect.");
-        nat->rfcomm_connected = 3; // input and output
-        return 1;
-    }
-#endif
-    return -1;
-}
-
-static jboolean shutdownNative(JNIEnv *env, jobject obj,
-                jboolean shutdownInput) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    /* NOTE: If you change the bcode to modify nat, make sure you 
-       add synchronize(this) to the method calling this native
-       method. 
-    */
-    native_data_t *nat = get_native_data(env, obj);
-    if (nat->rfcomm_sock < 0) {
-        LOGE("socket(RFCOMM) error: socket not created");
-        return JNI_FALSE;
-    }
-    int rc = shutdown(nat->rfcomm_sock, 
-            shutdownInput ? SHUT_RD : SHUT_WR);
-    if (!rc) {
-        nat->rfcomm_connected &= 
-            shutdownInput ? ~1 : ~2;
-        return JNI_TRUE;
-    }
-#endif
-    return JNI_FALSE;
-}
-
-static jint isConnectedNative(JNIEnv *env, jobject obj) {
-    LOGI(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    const native_data_t *nat = get_native_data(env, obj);
-    return nat->rfcomm_connected;
-#endif
-    return 0;
-}
-
-//@@@@@@@@@ bind to device???
-static jboolean bindNative(JNIEnv *env, jobject obj, jstring device,
-                           jint port) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-
-    /* NOTE: If you change the code to modify nat, make sure you
-       add synchronize(this) to the method calling this native
-       method.
-    */
-    const native_data_t *nat = get_native_data(env, obj);
-    if (nat->rfcomm_sock < 0) {
-        LOGE("socket(RFCOMM) error: socket not created");
-        return JNI_FALSE;
-    }
-
-    struct sockaddr_rc laddr;
-    int lm;
-
-    lm = 0;
-/*
-    lm |= RFCOMM_LM_MASTER;
-    lm |= RFCOMM_LM_AUTH;
-    lm |= RFCOMM_LM_ENCRYPT;
-    lm |= RFCOMM_LM_SECURE;
-*/
-
-    if (lm && setsockopt(nat->rfcomm_sock, SOL_RFCOMM, RFCOMM_LM, &lm, sizeof(lm)) < 0) {
-        LOGE("Can't set RFCOMM link mode");
-        return JNI_FALSE;
-    }
-
-    laddr.rc_family = AF_BLUETOOTH;
-    bacpy(&laddr.rc_bdaddr, BDADDR_ANY);
-    laddr.rc_channel = port;
-
-    if (bind(nat->rfcomm_sock, (struct sockaddr *)&laddr, sizeof(laddr)) < 0) {
-        LOGE("Can't bind RFCOMM socket");
-        return JNI_FALSE;
-    }
-
-    env->SetIntField(obj, field_mPort, port);
-
-    return JNI_TRUE;
-#endif
-    return JNI_FALSE;
-}
-
-static jboolean listenNative(JNIEnv *env, jobject obj, jint backlog) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    /* NOTE: If you change the code to modify nat, make sure you
-       add synchronize(this) to the method calling this native
-       method.
-    */
-    const native_data_t *nat = get_native_data(env, obj);
-    if (nat->rfcomm_sock < 0) {
-        LOGE("socket(RFCOMM) error: socket not created");
-        return JNI_FALSE;
-    }
-    return listen(nat->rfcomm_sock, backlog) < 0 ? JNI_FALSE : JNI_TRUE;
-#else
-    return JNI_FALSE;
-#endif
-}
-
-static int set_nb(int sk, bool nb) {
-    int flags = fcntl(sk, F_GETFL);
-    if (flags < 0) {
-        LOGE("Can't get socket flags with fcntl(): %s (%d)",
-             strerror(errno), errno);
-        close(sk);
-        return -1;
-    }
-    flags &= ~O_NONBLOCK;
-    if (nb) flags |= O_NONBLOCK;
-    int status = fcntl(sk, F_SETFL, flags);
-    if (status < 0) {
-        LOGE("Can't set socket to nonblocking mode with fcntl(): %s (%d)",
-             strerror(errno), errno);
-        close(sk);
-        return -1;
-    }
-    return 0;
-}
-
-// Note: the code should check at a higher level to see whether
-// listen() has been called.
-#ifdef HAVE_BLUETOOTH
-static int do_accept(JNIEnv* env, jobject object, int sock,
-                     jobject newsock,
-                     jfieldID out_address,
-                     bool must_succeed) {
-
-    if (must_succeed && set_nb(sock, true) < 0)
-        return -1;
-
-    struct sockaddr_rc raddr;
-    int alen = sizeof(raddr);
-    int nsk = accept(sock, (struct sockaddr *) &raddr, &alen);
-    if (nsk < 0) {
-        LOGE("Error on accept from socket fd %d: %s (%d).",
-             sock,
-             strerror(errno),
-             errno);
-        if (must_succeed) set_nb(sock, false);
-        return -1;
-    }
-
-    char addr[BTADDR_SIZE];
-    get_bdaddr_as_string(&raddr.rc_bdaddr, addr);
-    env->SetObjectField(newsock, out_address, env->NewStringUTF(addr));
-
-    LOGI("Successful accept() on AG socket %d: new socket %d, address %s, RFCOMM channel %d",
-         sock,
-         nsk,
-         addr,
-         raddr.rc_channel);
-    if (must_succeed) set_nb(sock, false);
-    return nsk;
-}
-#endif /*HAVE_BLUETOOTH*/
-
-static jobject acceptNative(JNIEnv *env, jobject obj,
-                            jobject newsock, jint timeoutMs) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    native_data_t *nat = get_native_data(env, obj);
-    if (nat->rfcomm_sock < 0) {
-        LOGE("socket(RFCOMM) error: socket not created");
-        return JNI_FALSE;
-    }
-
-    if (newsock == NULL) {
-        LOGE("%s: newsock = NULL\n", __FUNCTION__);
-        return JNI_FALSE;
-    }
-
-    int nsk = -1;
-    if (timeoutMs < 0) {
-        /* block until accept() succeeds */
-        nsk = do_accept(env, obj, nat->rfcomm_sock,
-                        newsock, field_mAddress, false);
-        if (nsk < 0) {
-            return NULL;
-        }
-    }
-    else {
-        /* wait with a timeout */
-
-        struct pollfd fds;
-        fds.fd = nat->rfcomm_sock;
-        fds.events = POLLIN | POLLPRI | POLLOUT | POLLERR;
-
-        env->SetIntField(obj, field_mAcceptTimeoutRemainingMs, 0);
-        int n = poll(&fds, 1, timeoutMs);
-        if (n <= 0) {
-            if (n < 0)  {
-                LOGE("listening poll() on RFCOMM socket: %s (%d)",
-                     strerror(errno),
-                     errno);
-                env->SetIntField(obj, field_mAcceptTimeoutRemainingMs, timeoutMs);
-            }
-            else {
-                LOGI("listening poll() on RFCOMM socket timed out");
-            }
-            return NULL;
-        }
-
-        LOGI("listening poll() on RFCOMM socket returned %d", n);
-        if (fds.fd == nat->rfcomm_sock) {
-            if (fds.revents & (POLLIN | POLLPRI | POLLOUT)) {
-                LOGI("Accepting connection.\n");
-                nsk = do_accept(env, obj, nat->rfcomm_sock,
-                                newsock, field_mAddress, true);
-                if (nsk < 0) {
-                    return NULL;
-                }
-            }
-        }
-    }
-
-    LOGI("Connection accepted, new socket fd = %d.", nsk);
-    native_data_t *newnat = get_native_data(env, newsock);
-    newnat->rfcomm_sock = nsk;
-    newnat->rfcomm_connected = 3;
-    return jniCreateFileDescriptor(env, nsk);
-#else
-    return NULL;
-#endif
-}
-
-static JNINativeMethod sMethods[] = {
-     /* name, signature, funcPtr */
-    {"classInitNative", "()V", (void*)classInitNative},
-    {"initializeNativeDataNative", "()V", (void *)initializeNativeDataNative},
-    {"cleanupNativeDataNative", "()V", (void *)cleanupNativeDataNative},
-
-    {"createNative", "()Ljava/io/FileDescriptor;", (void *)createNative},
-    {"destroyNative", "()V", (void *)destroyNative},
-    {"connectNative", "(Ljava/lang/String;I)Z", (void *)connectNative},
-    {"connectAsyncNative", "(Ljava/lang/String;I)Z", (void *)connectAsyncNative},
-    {"interruptAsyncConnectNative", "()Z", (void *)interruptAsyncConnectNative},
-    {"waitForAsyncConnectNative", "(I)I", (void *)waitForAsyncConnectNative},
-    {"shutdownNative", "(Z)Z", (void *)shutdownNative},
-    {"isConnectedNative", "()I", (void *)isConnectedNative},
-
-    {"bindNative", "(Ljava/lang/String;I)Z", (void*)bindNative},
-    {"listenNative", "(I)Z", (void*)listenNative},
-    {"acceptNative", "(Landroid/bluetooth/RfcommSocket;I)Ljava/io/FileDescriptor;", (void*)acceptNative},
-};
-
-int register_android_bluetooth_RfcommSocket(JNIEnv *env) {
-    return AndroidRuntime::registerNativeMethods(env,
-        "android/bluetooth/RfcommSocket", sMethods, NELEM(sMethods));
-}
-
-} /* namespace android */
diff --git a/core/jni/android_bluetooth_common.cpp b/core/jni/android_bluetooth_common.cpp
index 0b8a604..343fa53 100644
--- a/core/jni/android_bluetooth_common.cpp
+++ b/core/jni/android_bluetooth_common.cpp
@@ -36,6 +36,43 @@
 namespace android {
 
 #ifdef HAVE_BLUETOOTH
+
+static Properties remote_device_properties[] = {
+    {"Address",  DBUS_TYPE_STRING},
+    {"Name", DBUS_TYPE_STRING},
+    {"Icon", DBUS_TYPE_STRING},
+    {"Class", DBUS_TYPE_UINT32},
+    {"UUIDs", DBUS_TYPE_ARRAY},
+    {"Paired", DBUS_TYPE_BOOLEAN},
+    {"Connected", DBUS_TYPE_BOOLEAN},
+    {"Trusted", DBUS_TYPE_BOOLEAN},
+    {"Alias", DBUS_TYPE_STRING},
+    {"Nodes", DBUS_TYPE_ARRAY},
+    {"Adapter", DBUS_TYPE_OBJECT_PATH},
+    {"LegacyPairing", DBUS_TYPE_BOOLEAN},
+    {"RSSI", DBUS_TYPE_INT16},
+    {"TX", DBUS_TYPE_UINT32}
+};
+
+static Properties adapter_properties[] = {
+    {"Address", DBUS_TYPE_STRING},
+    {"Name", DBUS_TYPE_STRING},
+    {"Class", DBUS_TYPE_UINT32},
+    {"Powered", DBUS_TYPE_BOOLEAN},
+    {"Discoverable", DBUS_TYPE_BOOLEAN},
+    {"DiscoverableTimeout", DBUS_TYPE_UINT32},
+    {"Pairable", DBUS_TYPE_BOOLEAN},
+    {"PairableTimeout", DBUS_TYPE_UINT32},
+    {"Discovering", DBUS_TYPE_BOOLEAN},
+    {"Devices", DBUS_TYPE_ARRAY},
+};
+
+typedef union {
+    char *str_val;
+    int int_val;
+    char **array_val;
+} property_value;
+
 jfieldID get_field(JNIEnv *env, jclass clazz, const char *member,
                    const char *mtype) {
     jfieldID field = env->GetFieldID(clazz, member, mtype);
@@ -332,6 +369,44 @@
     return ret;
 }
 
+static void set_object_array_element(JNIEnv *env, jobjectArray strArray,
+                                     const char *value, int index) {
+    jstring obj;
+    obj = env->NewStringUTF(value);
+    env->SetObjectArrayElement(strArray, index, obj);
+    env->DeleteLocalRef(obj);
+}
+
+jobjectArray dbus_returns_array_of_object_path(JNIEnv *env,
+                                               DBusMessage *reply) {
+
+    DBusError err;
+    char **list;
+    int i, len;
+    jobjectArray strArray = NULL;
+
+    dbus_error_init(&err);
+    if (dbus_message_get_args (reply,
+                               &err,
+                               DBUS_TYPE_ARRAY, DBUS_TYPE_OBJECT_PATH,
+                               &list, &len,
+                               DBUS_TYPE_INVALID)) {
+        jclass stringClass;
+        jstring classNameStr;
+
+        stringClass = env->FindClass("java/lang/String");
+        strArray = env->NewObjectArray(len, stringClass, NULL);
+
+        for (i = 0; i < len; i++)
+            set_object_array_element(env, strArray, list[i], i);
+    } else {
+        LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
+    }
+
+    dbus_message_unref(reply);
+    return strArray;
+}
+
 jobjectArray dbus_returns_array_of_strings(JNIEnv *env, DBusMessage *reply) {
 
     DBusError err;
@@ -353,11 +428,8 @@
         stringClass = env->FindClass("java/lang/String");
         strArray = env->NewObjectArray(len, stringClass, NULL);
 
-        for (i = 0; i < len; i++) {
-            //LOGV("%s:    array[%d] = [%s]", __FUNCTION__, i, list[i]);
-            env->SetObjectArrayElement(strArray, i,
-                                       env->NewStringUTF(list[i]));
-        }
+        for (i = 0; i < len; i++)
+            set_object_array_element(env, strArray, list[i], i);
     } else {
         LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
     }
@@ -390,17 +462,263 @@
     return byteArray;
 }
 
-void get_bdaddr(const char *str, bdaddr_t *ba) {
+void append_variant(DBusMessageIter *iter, int type, void *val)
+{
+    DBusMessageIter value_iter;
+    char var_type[2] = { type, '\0'};
+    dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, var_type, &value_iter);
+    dbus_message_iter_append_basic(&value_iter, type, val);
+    dbus_message_iter_close_container(iter, &value_iter);
+}
+
+int get_property(DBusMessageIter iter, Properties *properties,
+                  int max_num_properties, int *prop_index, property_value *value, int *len) {
+    DBusMessageIter prop_val, array_val_iter;
+    char *property = NULL;
+    uint32_t array_type;
+    char *str_val;
+    int i, j, type, int_val;
+
+    if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+        return -1;
+    dbus_message_iter_get_basic(&iter, &property);
+    if (!dbus_message_iter_next(&iter))
+        return -1;
+    if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
+        return -1;
+    for (i = 0; i <  max_num_properties; i++) {
+        if (!strncmp(property, properties[i].name, strlen(property)))
+            break;
+    }
+    *prop_index = i;
+    if (i == max_num_properties)
+        return -1;
+
+    dbus_message_iter_recurse(&iter, &prop_val);
+    type = properties[*prop_index].type;
+    if (dbus_message_iter_get_arg_type(&prop_val) != type) {
+        LOGE("Property type mismatch in get_property: %d, expected:%d, index:%d",
+             dbus_message_iter_get_arg_type(&prop_val), type, *prop_index);
+        return -1;
+    }
+
+    switch(type) {
+    case DBUS_TYPE_STRING:
+    case DBUS_TYPE_OBJECT_PATH:
+        dbus_message_iter_get_basic(&prop_val, &value->str_val);
+        *len = 1;
+        break;
+    case DBUS_TYPE_UINT32:
+    case DBUS_TYPE_INT16:
+    case DBUS_TYPE_BOOLEAN:
+        dbus_message_iter_get_basic(&prop_val, &int_val);
+        value->int_val = int_val;
+        *len = 1;
+        break;
+    case DBUS_TYPE_ARRAY:
+        dbus_message_iter_recurse(&prop_val, &array_val_iter);
+        array_type = dbus_message_iter_get_arg_type(&array_val_iter);
+        *len = 0;
+        value->array_val = NULL;
+        if (array_type == DBUS_TYPE_OBJECT_PATH ||
+            array_type == DBUS_TYPE_STRING){
+            j = 0;
+            do {
+               j ++;
+            } while(dbus_message_iter_next(&array_val_iter));
+            dbus_message_iter_recurse(&prop_val, &array_val_iter);
+            // Allocate  an array of char *
+            *len = j;
+            char **tmp = (char **)malloc(sizeof(char *) * *len);
+            if (!tmp)
+                return -1;
+            j = 0;
+            do {
+               dbus_message_iter_get_basic(&array_val_iter, &tmp[j]);
+               j ++;
+            } while(dbus_message_iter_next(&array_val_iter));
+            value->array_val = tmp;
+        }
+        break;
+    default:
+        return -1;
+    }
+    return 0;
+}
+
+void create_prop_array(JNIEnv *env, jobjectArray strArray, Properties *property,
+                       property_value *value, int len, int *array_index ) {
+    char **prop_val = NULL;
+    char buf[32] = {'\0'}, buf1[32] = {'\0'};
+    int i;
+
+    char *name = property->name;
+    int prop_type = property->type;
+
+    set_object_array_element(env, strArray, name, *array_index);
+    *array_index += 1;
+
+    if (prop_type == DBUS_TYPE_UINT32 || prop_type == DBUS_TYPE_INT16) {
+        sprintf(buf, "%d", value->int_val);
+        set_object_array_element(env, strArray, buf, *array_index);
+        *array_index += 1;
+    } else if (prop_type == DBUS_TYPE_BOOLEAN) {
+        sprintf(buf, "%s", value->int_val ? "true" : "false");
+
+        set_object_array_element(env, strArray, buf, *array_index);
+        *array_index += 1;
+    } else if (prop_type == DBUS_TYPE_ARRAY) {
+        // Write the length first
+        sprintf(buf1, "%d", len);
+        set_object_array_element(env, strArray, buf1, *array_index);
+        *array_index += 1;
+
+        prop_val = value->array_val;
+        for (i = 0; i < len; i++) {
+            set_object_array_element(env, strArray, prop_val[i], *array_index);
+            *array_index += 1;
+        }
+    } else {
+        set_object_array_element(env, strArray, (const char *) value->str_val, *array_index);
+        *array_index += 1;
+    }
+}
+
+jobjectArray parse_properties(JNIEnv *env, DBusMessageIter *iter, Properties *properties,
+                              const int max_num_properties) {
+    DBusMessageIter dict_entry, dict;
+    jobjectArray strArray = NULL;
+    property_value value;
+    int i, size = 0,array_index = 0;
+    int len = 0, prop_type = DBUS_TYPE_INVALID, prop_index = -1, type;
+    struct {
+        property_value value;
+        int len;
+        bool used;
+    } values[max_num_properties];
+    int t, j;
+
+    jclass stringClass = env->FindClass("java/lang/String");
+    DBusError err;
+    dbus_error_init(&err);
+
+    for (i = 0; i < max_num_properties; i++) {
+        values[i].used = false;
+    }
+
+    if(dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY)
+        goto failure;
+    dbus_message_iter_recurse(iter, &dict);
+    do {
+        len = 0;
+        if (dbus_message_iter_get_arg_type(&dict) != DBUS_TYPE_DICT_ENTRY)
+            goto failure;
+        dbus_message_iter_recurse(&dict, &dict_entry);
+
+        if (!get_property(dict_entry, properties, max_num_properties, &prop_index,
+                          &value, &len)) {
+            size += 2;
+            if (properties[prop_index].type == DBUS_TYPE_ARRAY)
+                size += len;
+            values[prop_index].value = value;
+            values[prop_index].len = len;
+            values[prop_index].used = true;
+        } else {
+            goto failure;
+        }
+    } while(dbus_message_iter_next(&dict));
+
+    strArray = env->NewObjectArray(size, stringClass, NULL);
+
+    for (i = 0; i < max_num_properties; i++) {
+        if (values[i].used) {
+            create_prop_array(env, strArray, &properties[i], &values[i].value, values[i].len,
+                              &array_index);
+
+            if (properties[i].type == DBUS_TYPE_ARRAY && values[i].used
+                   && values[i].value.array_val != NULL)
+                free(values[i].value.array_val);
+        }
+
+    }
+    return strArray;
+
+failure:
+    if (dbus_error_is_set(&err))
+        LOG_AND_FREE_DBUS_ERROR(&err);
+    for (i = 0; i < max_num_properties; i++)
+        if (properties[i].type == DBUS_TYPE_ARRAY && values[i].used == true
+                                        && values[i].value.array_val != NULL)
+            free(values[i].value.array_val);
+    return NULL;
+}
+
+jobjectArray parse_property_change(JNIEnv *env, DBusMessage *msg,
+                           Properties *properties, int max_num_properties) {
+    DBusMessageIter iter;
+    DBusError err;
+    jobjectArray strArray = NULL;
+    jclass stringClass= env->FindClass("java/lang/String");
+    int len = 0, prop_index = -1;
+    int array_index = 0, size = 0;
+    property_value value;
+
+    dbus_error_init(&err);
+    if (!dbus_message_iter_init(msg, &iter))
+        goto failure;
+
+    if (!get_property(iter, properties, max_num_properties,
+                      &prop_index, &value, &len)) {
+        size += 2;
+        if (properties[prop_index].type == DBUS_TYPE_ARRAY)
+            size += len;
+        strArray = env->NewObjectArray(size, stringClass, NULL);
+
+        create_prop_array(env, strArray, &properties[prop_index],
+                          &value, len, &array_index);
+
+        if (properties[prop_index].type == DBUS_TYPE_ARRAY && value.array_val != NULL)
+             free(value.array_val);
+
+        return strArray;
+    }
+failure:
+    LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
+    return NULL;
+}
+
+jobjectArray parse_adapter_property_change(JNIEnv *env, DBusMessage *msg) {
+    return parse_property_change(env, msg, (Properties *) &adapter_properties,
+                    sizeof(adapter_properties) / sizeof(Properties));
+}
+
+jobjectArray parse_remote_device_property_change(JNIEnv *env, DBusMessage *msg) {
+    return parse_property_change(env, msg, (Properties *) &remote_device_properties,
+                    sizeof(remote_device_properties) / sizeof(Properties));
+}
+
+jobjectArray parse_adapter_properties(JNIEnv *env, DBusMessageIter *iter) {
+    return parse_properties(env, iter, (Properties *) &adapter_properties,
+                            sizeof(adapter_properties) / sizeof(Properties));
+}
+
+jobjectArray parse_remote_device_properties(JNIEnv *env, DBusMessageIter *iter) {
+    return parse_properties(env, iter, (Properties *) &remote_device_properties,
+                          sizeof(remote_device_properties) / sizeof(Properties));
+}
+
+int get_bdaddr(const char *str, bdaddr_t *ba) {
     char *d = ((char *)ba) + 5, *endp;
     int i;
     for(i = 0; i < 6; i++) {
         *d-- = strtol(str, &endp, 16);
         if (*endp != ':' && i != 5) {
             memset(ba, 0, sizeof(bdaddr_t));
-            return;
+            return -1;
         }
         str = endp + 1;
     }
+    return 0;
 }
 
 void get_bdaddr_as_string(const bdaddr_t *ba, char *str) {
diff --git a/core/jni/android_bluetooth_common.h b/core/jni/android_bluetooth_common.h
index 69092dd..ef9b66b 100644
--- a/core/jni/android_bluetooth_common.h
+++ b/core/jni/android_bluetooth_common.h
@@ -68,6 +68,7 @@
 
 struct event_loop_native_data_t {
     DBusConnection *conn;
+    const char *adapter;
 
     /* protects the thread */
     pthread_mutex_t thread_mutex;
@@ -89,6 +90,12 @@
     jobject me;
 };
 
+struct _Properties {
+    char name[32];
+    int type;
+};
+typedef struct _Properties Properties;
+
 dbus_bool_t dbus_func_args_async(JNIEnv *env,
                                  DBusConnection *conn,
                                  int timeout_ms,
@@ -142,9 +149,19 @@
 jstring dbus_returns_string(JNIEnv *env, DBusMessage *reply);
 jboolean dbus_returns_boolean(JNIEnv *env, DBusMessage *reply);
 jobjectArray dbus_returns_array_of_strings(JNIEnv *env, DBusMessage *reply);
+jobjectArray dbus_returns_array_of_object_path(JNIEnv *env, DBusMessage *reply);
 jbyteArray dbus_returns_array_of_bytes(JNIEnv *env, DBusMessage *reply);
 
-void get_bdaddr(const char *str, bdaddr_t *ba);
+jobjectArray parse_properties(JNIEnv *env, DBusMessageIter *iter, Properties *properties,
+                              const int max_num_properties);
+jobjectArray parse_property_change(JNIEnv *env, DBusMessage *msg,
+                                   Properties *properties, int max_num_properties);
+jobjectArray parse_adapter_properties(JNIEnv *env, DBusMessageIter *iter);
+jobjectArray parse_remote_device_properties(JNIEnv *env, DBusMessageIter *iter);
+jobjectArray parse_remote_device_property_change(JNIEnv *env, DBusMessage *msg);
+jobjectArray parse_adapter_property_change(JNIEnv *env, DBusMessage *msg);
+void append_variant(DBusMessageIter *iter, int type, void *val);
+int get_bdaddr(const char *str, bdaddr_t *ba);
 void get_bdaddr_as_string(const bdaddr_t *ba, char *str);
 
 bool debug_no_encrypt();
diff --git a/core/jni/android_database_CursorWindow.cpp b/core/jni/android_database_CursorWindow.cpp
index f19fbbf..91449bc 100644
--- a/core/jni/android_database_CursorWindow.cpp
+++ b/core/jni/android_database_CursorWindow.cpp
@@ -229,7 +229,7 @@
 {
     int32_t err;
     CursorWindow * window = GET_WINDOW(env, object);
-LOG_WINDOW("Checking if column is a blob for %d,%d from %p", row, column, window);
+LOG_WINDOW("Checking if column is a blob or null for %d,%d from %p", row, column, window);
 
     field_slot_t field;
     err = window->read_field_slot(row, column, &field);
@@ -241,6 +241,54 @@
     return field.type == FIELD_TYPE_BLOB || field.type == FIELD_TYPE_NULL;
 }
 
+static jboolean isString_native(JNIEnv* env, jobject object, jint row, jint column)
+{
+    int32_t err;
+    CursorWindow * window = GET_WINDOW(env, object);
+LOG_WINDOW("Checking if column is a string or null for %d,%d from %p", row, column, window);
+
+    field_slot_t field;
+    err = window->read_field_slot(row, column, &field);
+    if (err != 0) {
+        throwExceptionWithRowCol(env, row, column);
+        return NULL;
+    }
+
+    return field.type == FIELD_TYPE_STRING || field.type == FIELD_TYPE_NULL;
+}
+
+static jboolean isInteger_native(JNIEnv* env, jobject object, jint row, jint column)
+{
+    int32_t err;
+    CursorWindow * window = GET_WINDOW(env, object);
+LOG_WINDOW("Checking if column is an integer for %d,%d from %p", row, column, window);
+
+    field_slot_t field;
+    err = window->read_field_slot(row, column, &field);
+    if (err != 0) {
+        throwExceptionWithRowCol(env, row, column);
+        return NULL;
+    }
+
+    return field.type == FIELD_TYPE_INTEGER;
+}
+
+static jboolean isFloat_native(JNIEnv* env, jobject object, jint row, jint column)
+{
+    int32_t err;
+    CursorWindow * window = GET_WINDOW(env, object);
+LOG_WINDOW("Checking if column is a float for %d,%d from %p", row, column, window);
+
+    field_slot_t field;
+    err = window->read_field_slot(row, column, &field);
+    if (err != 0) {
+        throwExceptionWithRowCol(env, row, column);
+        return NULL;
+    }
+
+    return field.type == FIELD_TYPE_FLOAT;
+}
+
 static jstring getString_native(JNIEnv* env, jobject object, jint row, jint column)
 {
     int32_t err;
@@ -326,11 +374,11 @@
         jniThrowException(env, "java/lang/IllegalStateException", "Unable to get field slot");
         return NULL;
     }
-    
+
     jcharArray buffer = (jcharArray)env->GetObjectField(buf, gBufferField);
     if (buffer == NULL) {
         jniThrowException(env, "java/lang/IllegalStateException", "buf should not be null");
-        return NULL;        
+        return NULL;
     }
     jchar* dst = env->GetCharArrayElements(buffer, NULL);
     uint8_t type = field.type;
@@ -338,7 +386,7 @@
     jcharArray newArray = NULL;
     if (type == FIELD_TYPE_STRING) {
         uint32_t size = field.data.buffer.size;
-        if (size > 0) {            
+        if (size > 0) {
 #if WINDOW_STORAGE_UTF8
             // Pass size - 1 since the UTF8 is null terminated and we don't want a null terminator on the UTF16 string
             String16 utf16((char const *)window->offsetToPtr(field.data.buffer.offset), size - 1);
@@ -346,7 +394,7 @@
             if (strSize > bufferSize || dst == NULL) {
                 newArray = env->NewCharArray(strSize);
                 env->SetCharArrayRegion(newArray, 0, strSize, (jchar const *)utf16.string());
-            } else {                
+            } else {
                 memcpy(dst, (jchar const *)utf16.string(), strSize * 2);
             }
             sizeCopied = strSize;
@@ -359,7 +407,7 @@
                 memcpy(dst, (jchar const *)window->offsetToPtr(field.data.buffer.offset), size);
             }
 #endif
-        } 
+        }
     } else if (type == FIELD_TYPE_INTEGER) {
         int64_t value;
         if (window->getLong(row, column, &value)) {
@@ -628,6 +676,9 @@
     {"putDouble_native", "(DII)Z", (void *)putDouble_native},
     {"freeLastRow_native", "()V", (void *)freeLastRow},
     {"putNull_native", "(II)Z", (void *)putNull_native},
+    {"isString_native", "(II)Z", (void *)isString_native},
+    {"isFloat_native", "(II)Z", (void *)isFloat_native},
+    {"isInteger_native", "(II)Z", (void *)isInteger_native},
 };
 
 int register_android_database_CursorWindow(JNIEnv * env)
@@ -646,7 +697,7 @@
         LOGE("Error locating fields");
         return -1;
     }
-    
+
     clazz =  env->FindClass("android/database/CharArrayBuffer");
     if (clazz == NULL) {
         LOGE("Can't find android/database/CharArrayBuffer");
diff --git a/core/jni/android_database_SQLiteDatabase.cpp b/core/jni/android_database_SQLiteDatabase.cpp
index 66858f9..020aff4a 100644
--- a/core/jni/android_database_SQLiteDatabase.cpp
+++ b/core/jni/android_database_SQLiteDatabase.cpp
@@ -28,7 +28,10 @@
 #include <sqlite3.h>
 #include <sqlite3_android.h>
 #include <string.h>
-#include <utils.h>
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 #include <ctype.h>
 
 #include <stdio.h>
diff --git a/core/jni/android_hardware_Camera.cpp b/core/jni/android_hardware_Camera.cpp
index 9053468..8a312d9 100644
--- a/core/jni/android_hardware_Camera.cpp
+++ b/core/jni/android_hardware_Camera.cpp
@@ -25,7 +25,7 @@
 
 #include <ui/Surface.h>
 #include <ui/Camera.h>
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 
 using namespace android;
 
diff --git a/core/jni/android_media_AudioRecord.cpp b/core/jni/android_media_AudioRecord.cpp
index 44a9e8c..0be996d 100644
--- a/core/jni/android_media_AudioRecord.cpp
+++ b/core/jni/android_media_AudioRecord.cpp
@@ -28,8 +28,8 @@
 #include "android_runtime/AndroidRuntime.h"
 
 #include "utils/Log.h"
-#include "media/AudioSystem.h"
 #include "media/AudioRecord.h"
+#include "media/mediarecorder.h"
 
 
 // ----------------------------------------------------------------------------
@@ -62,7 +62,7 @@
 #define AUDIORECORD_ERROR_BAD_VALUE                 -2
 #define AUDIORECORD_ERROR_INVALID_OPERATION         -3
 #define AUDIORECORD_ERROR_SETUP_ZEROFRAMECOUNT      -16
-#define AUDIORECORD_ERROR_SETUP_INVALIDCHANNELCOUNT -17
+#define AUDIORECORD_ERROR_SETUP_INVALIDCHANNELMASK -17
 #define AUDIORECORD_ERROR_SETUP_INVALIDFORMAT       -18
 #define AUDIORECORD_ERROR_SETUP_INVALIDSOURCE       -19
 #define AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED    -20
@@ -122,17 +122,18 @@
 // ----------------------------------------------------------------------------
 static int
 android_media_AudioRecord_setup(JNIEnv *env, jobject thiz, jobject weak_this,
-        jint source, jint sampleRateInHertz, jint nbChannels, 
+        jint source, jint sampleRateInHertz, jint channels,
         jint audioFormat, jint buffSizeInBytes)
 {
     //LOGV(">> Entering android_media_AudioRecord_setup");
-    //LOGV("sampleRate=%d, audioFormat=%d, nbChannels=%d, buffSizeInBytes=%d",
-    //     sampleRateInHertz, audioFormat, nbChannels,     buffSizeInBytes);
+    //LOGV("sampleRate=%d, audioFormat=%d, channels=%x, buffSizeInBytes=%d",
+    //     sampleRateInHertz, audioFormat, channels,     buffSizeInBytes);
 
-    if ((nbChannels == 0) || (nbChannels > 2)) {
+    if (!AudioSystem::isInputChannel(channels)) {
         LOGE("Error creating AudioRecord: channel count is not 1 or 2.");
-        return AUDIORECORD_ERROR_SETUP_INVALIDCHANNELCOUNT;
+        return AUDIORECORD_ERROR_SETUP_INVALIDCHANNELMASK;
     }
+    uint32_t nbChannels = AudioSystem::popCount(channels);
 
     // compare the format against the Java constants
     if ((audioFormat != javaAudioRecordFields.PCM16) 
@@ -152,12 +153,7 @@
     int frameSize = nbChannels * bytesPerSample;
     size_t frameCount = buffSizeInBytes / frameSize;
     
-    // convert and check input source value
-    // input_source values defined in AudioRecord.h are equal to
-    // JAVA MediaRecord.AudioSource values minus 1.
-    AudioRecord::input_source arSource = (AudioRecord::input_source)(source - 1);
-    if (arSource < AudioRecord::DEFAULT_INPUT ||
-        arSource >= AudioRecord::NUM_INPUT_SOURCES) {
+    if (source >= AUDIO_SOURCE_LIST_END) {
         LOGE("Error creating AudioRecord: unknown source.");
         return AUDIORECORD_ERROR_SETUP_INVALIDSOURCE;
     }
@@ -184,10 +180,10 @@
     // we use a weak reference so the AudioRecord object can be garbage collected.
     lpCallbackData->audioRecord_ref = env->NewGlobalRef(weak_this);
     
-    lpRecorder->set(arSource,
+    lpRecorder->set(source,
         sampleRateInHertz,
         format,        // word length, PCM
-        nbChannels,
+        channels,
         frameCount,
         0,             // flags
         recorderCallback,// callback_t
diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp
index 692610e..3d8d296 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -50,25 +50,6 @@
 }
 
 static int
-android_media_AudioSystem_setVolume(JNIEnv *env, jobject clazz, jint type, jint volume)
-{
-    LOGV("setVolume(%d)", int(volume));
-    
-    return check_AudioSystem_Command(AudioSystem::setStreamVolume(type, AudioSystem::linearToLog(volume)));
-}
-
-static int
-android_media_AudioSystem_getVolume(JNIEnv *env, jobject clazz, jint type)
-{
-    float v;
-    int v_int = -1;
-    if (AudioSystem::getStreamVolume(int(type), &v) == NO_ERROR) {
-        v_int = AudioSystem::logToLinear(v);
-    }
-    return v_int;
-}
-
-static int
 android_media_AudioSystem_muteMicrophone(JNIEnv *env, jobject thiz, jboolean on)
 {
     return check_AudioSystem_Command(AudioSystem::muteMicrophone(on));
@@ -82,34 +63,6 @@
     return state;
 }
 
-static int
-android_media_AudioSystem_setRouting(JNIEnv *env, jobject clazz, jint mode, jint routes, jint mask)
-{
-    return check_AudioSystem_Command(AudioSystem::setRouting(mode, uint32_t(routes), uint32_t(mask)));
-}
-
-static jint
-android_media_AudioSystem_getRouting(JNIEnv *env, jobject clazz, jint mode)
-{
-    uint32_t routes = -1;
-    AudioSystem::getRouting(mode, &routes);
-    return jint(routes);
-}
-
-static int
-android_media_AudioSystem_setMode(JNIEnv *env, jobject clazz, jint mode)
-{
-    return check_AudioSystem_Command(AudioSystem::setMode(mode));
-}
-
-static jint
-android_media_AudioSystem_getMode(JNIEnv *env, jobject clazz)
-{
-    int mode = AudioSystem::MODE_INVALID;
-    AudioSystem::getMode(&mode);
-    return jint(mode);
-}
-
 static jboolean
 android_media_AudioSystem_isMusicActive(JNIEnv *env, jobject thiz)
 {
@@ -118,16 +71,29 @@
     return state;
 }
 
-// Temporary interface, do not use
-// TODO: Replace with a more generic key:value get/set mechanism
-static void
-android_media_AudioSystem_setParameter(JNIEnv *env, jobject thiz, jstring key, jstring value)
+static int
+android_media_AudioSystem_setParameters(JNIEnv *env, jobject thiz, jstring keyValuePairs)
 {
-    const char *c_key = env->GetStringUTFChars(key, NULL);
-    const char *c_value = env->GetStringUTFChars(value, NULL);
-    AudioSystem::setParameter(c_key, c_value);
-    env->ReleaseStringUTFChars(key, c_key);
-    env->ReleaseStringUTFChars(value, c_value);
+    const jchar* c_keyValuePairs = env->GetStringCritical(keyValuePairs, 0);
+    String8 c_keyValuePairs8;
+    if (keyValuePairs) {
+        c_keyValuePairs8 = String8(c_keyValuePairs, env->GetStringLength(keyValuePairs));
+        env->ReleaseStringCritical(keyValuePairs, c_keyValuePairs);
+    }
+    int status = check_AudioSystem_Command(AudioSystem::setParameters(0, c_keyValuePairs8));
+    return status;
+}
+
+static jstring
+android_media_AudioSystem_getParameters(JNIEnv *env, jobject thiz, jstring keys)
+{
+    const jchar* c_keys = env->GetStringCritical(keys, 0);
+    String8 c_keys8;
+    if (keys) {
+        c_keys8 = String8(c_keys, env->GetStringLength(keys));
+        env->ReleaseStringCritical(keys, c_keys);
+    }
+    return env->NewStringUTF(AudioSystem::getParameters(0, c_keys8).string());
 }
 
 void android_media_AudioSystem_error_callback(status_t err)
@@ -152,19 +118,93 @@
     env->CallStaticVoidMethod(clazz, env->GetStaticMethodID(clazz, "errorCallbackFromNative","(I)V"), error);
 }
 
+static int
+android_media_AudioSystem_setDeviceConnectionState(JNIEnv *env, jobject thiz, jint device, jint state, jstring device_address)
+{
+    const char *c_address = env->GetStringUTFChars(device_address, NULL);
+    int status = check_AudioSystem_Command(AudioSystem::setDeviceConnectionState(static_cast <AudioSystem::audio_devices>(device),
+                                          static_cast <AudioSystem::device_connection_state>(state),
+                                          c_address));
+    env->ReleaseStringUTFChars(device_address, c_address);
+    return status;
+}
+
+static int
+android_media_AudioSystem_getDeviceConnectionState(JNIEnv *env, jobject thiz, jint device, jstring device_address)
+{
+    const char *c_address = env->GetStringUTFChars(device_address, NULL);
+    int state = static_cast <int>(AudioSystem::getDeviceConnectionState(static_cast <AudioSystem::audio_devices>(device),
+                                          c_address));
+    env->ReleaseStringUTFChars(device_address, c_address);
+    return state;
+}
+
+static int
+android_media_AudioSystem_setPhoneState(JNIEnv *env, jobject thiz, jint state)
+{
+    return check_AudioSystem_Command(AudioSystem::setPhoneState(state));
+}
+
+static int
+android_media_AudioSystem_setRingerMode(JNIEnv *env, jobject thiz, jint mode, jint mask)
+{
+    return check_AudioSystem_Command(AudioSystem::setRingerMode(mode, mask));
+}
+
+static int
+android_media_AudioSystem_setForceUse(JNIEnv *env, jobject thiz, jint usage, jint config)
+{
+    return check_AudioSystem_Command(AudioSystem::setForceUse(static_cast <AudioSystem::force_use>(usage),
+                                                           static_cast <AudioSystem::forced_config>(config)));
+}
+
+static int
+android_media_AudioSystem_getForceUse(JNIEnv *env, jobject thiz, jint usage)
+{
+    return static_cast <int>(AudioSystem::getForceUse(static_cast <AudioSystem::force_use>(usage)));
+}
+
+static int
+android_media_AudioSystem_initStreamVolume(JNIEnv *env, jobject thiz, jint stream, jint indexMin, jint indexMax)
+{
+    return check_AudioSystem_Command(AudioSystem::initStreamVolume(static_cast <AudioSystem::stream_type>(stream),
+                                                                   indexMin,
+                                                                   indexMax));
+}
+
+static int
+android_media_AudioSystem_setStreamVolumeIndex(JNIEnv *env, jobject thiz, jint stream, jint index)
+{
+    return check_AudioSystem_Command(AudioSystem::setStreamVolumeIndex(static_cast <AudioSystem::stream_type>(stream), index));
+}
+
+static int
+android_media_AudioSystem_getStreamVolumeIndex(JNIEnv *env, jobject thiz, jint stream)
+{
+    int index;
+    if (AudioSystem::getStreamVolumeIndex(static_cast <AudioSystem::stream_type>(stream), &index) != NO_ERROR) {
+        index = -1;
+    }
+    return index;
+}
+
 // ----------------------------------------------------------------------------
 
 static JNINativeMethod gMethods[] = {
-    {"setVolume",           "(II)I",    (void *)android_media_AudioSystem_setVolume},
-    {"getVolume",           "(I)I",     (void *)android_media_AudioSystem_getVolume},
-    {"setParameter",        "(Ljava/lang/String;Ljava/lang/String;)V", (void *)android_media_AudioSystem_setParameter},
+    {"setParameters",        "(Ljava/lang/String;)I", (void *)android_media_AudioSystem_setParameters},
+    {"getParameters",        "(Ljava/lang/String;)Ljava/lang/String;", (void *)android_media_AudioSystem_getParameters},
     {"muteMicrophone",      "(Z)I",     (void *)android_media_AudioSystem_muteMicrophone},
     {"isMicrophoneMuted",   "()Z",      (void *)android_media_AudioSystem_isMicrophoneMuted},
-    {"setRouting",          "(III)I",   (void *)android_media_AudioSystem_setRouting},
-    {"getRouting",          "(I)I",     (void *)android_media_AudioSystem_getRouting},
-    {"setMode",             "(I)I",     (void *)android_media_AudioSystem_setMode},
-    {"getMode",             "()I",      (void *)android_media_AudioSystem_getMode},
     {"isMusicActive",       "()Z",      (void *)android_media_AudioSystem_isMusicActive},
+    {"setDeviceConnectionState", "(IILjava/lang/String;)I", (void *)android_media_AudioSystem_setDeviceConnectionState},
+    {"getDeviceConnectionState", "(ILjava/lang/String;)I",  (void *)android_media_AudioSystem_getDeviceConnectionState},
+    {"setPhoneState",       "(I)I",     (void *)android_media_AudioSystem_setPhoneState},
+    {"setRingerMode",       "(II)I",    (void *)android_media_AudioSystem_setRingerMode},
+    {"setForceUse",         "(II)I",    (void *)android_media_AudioSystem_setForceUse},
+    {"getForceUse",         "(I)I",     (void *)android_media_AudioSystem_getForceUse},
+    {"initStreamVolume",    "(III)I",   (void *)android_media_AudioSystem_initStreamVolume},
+    {"setStreamVolumeIndex","(II)I",    (void *)android_media_AudioSystem_setStreamVolumeIndex},
+    {"getStreamVolumeIndex","(I)I",     (void *)android_media_AudioSystem_getStreamVolumeIndex}
 };
 
 const char* const kClassPathName = "android/media/AudioSystem";
diff --git a/core/jni/android_media_AudioTrack.cpp b/core/jni/android_media_AudioTrack.cpp
index fd92fbe..6449147 100644
--- a/core/jni/android_media_AudioTrack.cpp
+++ b/core/jni/android_media_AudioTrack.cpp
@@ -30,8 +30,8 @@
 #include "media/AudioSystem.h"
 #include "media/AudioTrack.h"
 
-#include <utils/MemoryHeapBase.h>
-#include <utils/MemoryBase.h>
+#include <binder/MemoryHeapBase.h>
+#include <binder/MemoryBase.h>
 
 
 // ----------------------------------------------------------------------------
@@ -103,7 +103,7 @@
 #define AUDIOTRACK_ERROR_BAD_VALUE                 -2
 #define AUDIOTRACK_ERROR_INVALID_OPERATION         -3
 #define AUDIOTRACK_ERROR_SETUP_AUDIOSYSTEM         -16
-#define AUDIOTRACK_ERROR_SETUP_INVALIDCHANNELCOUNT -17
+#define AUDIOTRACK_ERROR_SETUP_INVALIDCHANNELMASK -17
 #define AUDIOTRACK_ERROR_SETUP_INVALIDFORMAT       -18
 #define AUDIOTRACK_ERROR_SETUP_INVALIDSTREAMTYPE   -19
 #define AUDIOTRACK_ERROR_SETUP_NATIVEINITFAILED    -20
@@ -164,11 +164,11 @@
 // ----------------------------------------------------------------------------
 static int
 android_media_AudioTrack_native_setup(JNIEnv *env, jobject thiz, jobject weak_this,
-        jint streamType, jint sampleRateInHertz, jint nbChannels, 
+        jint streamType, jint sampleRateInHertz, jint channels,
         jint audioFormat, jint buffSizeInBytes, jint memoryMode)
 {
-    LOGV("sampleRate=%d, audioFormat(from Java)=%d, nbChannels=%d, buffSize=%d", 
-        sampleRateInHertz, audioFormat, nbChannels, buffSizeInBytes);
+    LOGV("sampleRate=%d, audioFormat(from Java)=%d, channels=%x, buffSize=%d",
+        sampleRateInHertz, audioFormat, channels, buffSizeInBytes);
     int afSampleRate;
     int afFrameCount;
 
@@ -181,10 +181,11 @@
         return AUDIOTRACK_ERROR_SETUP_AUDIOSYSTEM;
     }
 
-    if ((nbChannels == 0) || (nbChannels > 2)) {
-        LOGE("Error creating AudioTrack: channel count is not 1 or 2.");
-        return AUDIOTRACK_ERROR_SETUP_INVALIDCHANNELCOUNT;
+    if (!AudioSystem::isOutputChannel(channels)) {
+        LOGE("Error creating AudioTrack: invalid channel mask.");
+        return AUDIOTRACK_ERROR_SETUP_INVALIDCHANNELMASK;
     }
+    int nbChannels = AudioSystem::popCount(channels);
     
     // check the stream type
     AudioSystem::stream_type atStreamType;
@@ -231,15 +232,7 @@
     int bytesPerSample = audioFormat == javaAudioTrackFields.PCM16 ? 2 : 1;
     int format = audioFormat == javaAudioTrackFields.PCM16 ? 
             AudioSystem::PCM_16_BIT : AudioSystem::PCM_8_BIT;
-    int frameCount;
-    if (buffSizeInBytes == -1) {
-        // compute the frame count based on the system's output frame count 
-        // and the native sample rate
-        frameCount = (sampleRateInHertz*afFrameCount)/afSampleRate;
-    } else {
-        // compute the frame count based on the specified buffer size
-        frameCount = buffSizeInBytes / (nbChannels * bytesPerSample);
-    }
+    int frameCount = buffSizeInBytes / (nbChannels * bytesPerSample);
     
     AudioTrackJniStorage* lpJniStorage = new AudioTrackJniStorage();
     
@@ -271,7 +264,7 @@
             atStreamType,// stream type
             sampleRateInHertz,
             format,// word length, PCM
-            nbChannels,
+            channels,
             frameCount,
             0,// flags
             audioCallback, &(lpJniStorage->mCallbackData),//callback, callback data (user)
@@ -291,7 +284,7 @@
             atStreamType,// stream type
             sampleRateInHertz,
             format,// word length, PCM
-            nbChannels,
+            channels,
             frameCount,
             0,// flags
             audioCallback, &(lpJniStorage->mCallbackData),//callback, callback data (user));
diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp
index 8383deb..feb0dad 100644
--- a/core/jni/android_net_NetUtils.cpp
+++ b/core/jni/android_net_NetUtils.cpp
@@ -23,6 +23,7 @@
 #include <arpa/inet.h>
 
 extern "C" {
+int ifc_enable(const char *ifname);
 int ifc_disable(const char *ifname);
 int ifc_add_host_route(const char *ifname, uint32_t addr);
 int ifc_remove_host_routes(const char *ifname);
@@ -66,6 +67,16 @@
     jfieldID leaseDuration;
 } dhcpInfoFieldIds;
 
+static jint android_net_utils_enableInterface(JNIEnv* env, jobject clazz, jstring ifname)
+{
+    int result;
+
+    const char *nameStr = env->GetStringUTFChars(ifname, NULL);
+    result = ::ifc_enable(nameStr);
+    env->ReleaseStringUTFChars(ifname, nameStr);
+    return (jint)result;
+}
+
 static jint android_net_utils_disableInterface(JNIEnv* env, jobject clazz, jstring ifname)
 {
     int result;
@@ -209,6 +220,7 @@
 static JNINativeMethod gNetworkUtilMethods[] = {
     /* name, signature, funcPtr */
 
+    { "enableInterface", "(Ljava/lang/String;)I",  (void *)android_net_utils_enableInterface },
     { "disableInterface", "(Ljava/lang/String;)I",  (void *)android_net_utils_disableInterface },
     { "addHostRoute", "(Ljava/lang/String;I)I",  (void *)android_net_utils_addHostRoute },
     { "removeHostRoutes", "(Ljava/lang/String;)I",  (void *)android_net_utils_removeHostRoutes },
diff --git a/core/jni/android_net_wifi_Wifi.cpp b/core/jni/android_net_wifi_Wifi.cpp
index ae744a8..70b7da1 100644
--- a/core/jni/android_net_wifi_Wifi.cpp
+++ b/core/jni/android_net_wifi_Wifi.cpp
@@ -311,14 +311,15 @@
     return result;
 }
 
-static jint android_net_wifi_getRssiCommand(JNIEnv* env, jobject clazz)
+static jint android_net_wifi_getRssiHelper(const char *cmd)
 {
     char reply[256];
     int rssi = -200;
 
-    if (doCommand("DRIVER RSSI", reply, sizeof(reply)) != 0) {
+    if (doCommand(cmd, reply, sizeof(reply)) != 0) {
         return (jint)-1;
     }
+
     // reply comes back in the form "<SSID> rssi XX" where XX is the
     // number we're interested in.  if we're associating, it returns "OK".
     // beware - <SSID> can contain spaces.
@@ -332,6 +333,16 @@
     return (jint)rssi;
 }
 
+static jint android_net_wifi_getRssiCommand(JNIEnv* env, jobject clazz)
+{
+    return android_net_wifi_getRssiHelper("DRIVER RSSI");
+}
+
+static jint android_net_wifi_getRssiApproxCommand(JNIEnv* env, jobject clazz)
+{
+    return android_net_wifi_getRssiHelper("DRIVER RSSI-APPROX");
+}
+
 static jint android_net_wifi_getLinkSpeedCommand(JNIEnv* env, jobject clazz)
 {
     char reply[256];
@@ -527,6 +538,8 @@
     { "setBluetoothCoexistenceScanModeCommand", "(Z)Z",
     		(void*) android_net_wifi_setBluetoothCoexistenceScanModeCommand },
     { "getRssiCommand", "()I", (void*) android_net_wifi_getRssiCommand },
+    { "getRssiApproxCommand", "()I",
+            (void*) android_net_wifi_getRssiApproxCommand},
     { "getLinkSpeedCommand", "()I", (void*) android_net_wifi_getLinkSpeedCommand },
     { "getMacAddressCommand", "()Ljava/lang/String;", (void*) android_net_wifi_getMacAddressCommand },
     { "saveConfigCommand", "()Z", (void*) android_net_wifi_saveConfigCommand },
diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp
index a6b63d8..b4c60f1 100644
--- a/core/jni/android_os_Debug.cpp
+++ b/core/jni/android_os_Debug.cpp
@@ -129,6 +129,8 @@
             isDalvikHeap = 1;
         } else if (strstr(line, "/dalvik-heap-bitmap/")) {
             isDalvikHeap = 1;    
+        } else if (strstr(line, "/data/dalvik-cache/")) {
+            isDalvikHeap = 1;
         } else if (strstr(line, "/tmp/sqlite-heap")) {
             isSqliteHeap = 1;
         }
@@ -158,9 +160,9 @@
                 private_dirty = temp;
             } else if (sscanf(line, "Referenced: %d kB", &temp) == 1) {
                 referenced = temp;
-            } else if (strlen(line) > 40 && line[8] == '-' && line[17] == ' ') {
+            } else if (strlen(line) > 30 && line[8] == '-' && line[17] == ' ') {
                 // looks like a new mapping
-                // example: "0000a000-00232000 rwxp 0000a000 00:00 0          [heap]"
+                // example: "10000000-10001000 ---p 10000000 00:00 0"
                 break;
             }
         }
@@ -178,8 +180,8 @@
                 // ignore
             } else {
                 stats->otherPss += pss;
-                stats->otherPrivateDirty += shared_dirty;
-                stats->otherSharedDirty += private_dirty;
+                stats->otherPrivateDirty += private_dirty;
+                stats->otherSharedDirty += shared_dirty;
             }
         }
     }
diff --git a/core/jni/android_os_Exec.cpp b/core/jni/android_os_Exec.cpp
deleted file mode 100644
index ca5e695..0000000
--- a/core/jni/android_os_Exec.cpp
+++ /dev/null
@@ -1,215 +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.
- */
-
-#define LOG_TAG "Exec"
-
-#include "JNIHelp.h"
-#include "jni.h"
-#include "utils/Log.h"
-#include "utils/misc.h"
-#include "android_runtime/AndroidRuntime.h"
-
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/wait.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <termios.h>
-
-namespace android
-{
-
-static jclass class_fileDescriptor;
-static jfieldID field_fileDescriptor_descriptor;
-static jmethodID method_fileDescriptor_init;
- 
-
-static int create_subprocess(const char *cmd, const char *arg0, const char *arg1,
-    int* pProcessId)
-{
-    char *devname;
-    int ptm;
-    pid_t pid;
-
-    ptm = open("/dev/ptmx", O_RDWR); // | O_NOCTTY);
-    if(ptm < 0){
-        LOGE("[ cannot open /dev/ptmx - %s ]\n",strerror(errno));
-        return -1;
-    }
-    fcntl(ptm, F_SETFD, FD_CLOEXEC);
-
-    if(grantpt(ptm) || unlockpt(ptm) ||
-       ((devname = (char*) ptsname(ptm)) == 0)){
-        LOGE("[ trouble with /dev/ptmx - %s ]\n", strerror(errno));
-        return -1;
-    }
-    
-    pid = fork();
-    if(pid < 0) {
-        LOGE("- fork failed: %s -\n", strerror(errno));
-        return -1;
-    }
-
-    if(pid == 0){
-        int pts;
-
-        setsid();
-        
-        pts = open(devname, O_RDWR);
-        if(pts < 0) exit(-1);
-
-        dup2(pts, 0);
-        dup2(pts, 1);
-        dup2(pts, 2);
-
-        close(ptm);
-
-        execl(cmd, cmd, arg0, arg1, NULL);
-        exit(-1);
-    } else {
-        *pProcessId = (int) pid;
-        return ptm;
-    }
-}
-
-
-static jobject android_os_Exec_createSubProcess(JNIEnv *env, jobject clazz,
-    jstring cmd, jstring arg0, jstring arg1, jintArray processIdArray)
-{
-    const jchar* str = cmd ? env->GetStringCritical(cmd, 0) : 0;
-    String8 cmd_8;
-    if (str) {
-        cmd_8 = String8(str, env->GetStringLength(cmd));
-        env->ReleaseStringCritical(cmd, str);
-    }
-
-    str = arg0 ? env->GetStringCritical(arg0, 0) : 0;
-    const char* arg0Str = 0;
-    String8 arg0_8;
-    if (str) {
-        arg0_8 = String8(str, env->GetStringLength(arg0));
-        env->ReleaseStringCritical(arg0, str);
-        arg0Str = arg0_8.string();
-    }
-
-    str = arg1 ? env->GetStringCritical(arg1, 0) : 0;
-    const char* arg1Str = 0;
-    String8 arg1_8;
-    if (str) {
-        arg1_8 = String8(str, env->GetStringLength(arg1));
-        env->ReleaseStringCritical(arg1, str);
-        arg1Str = arg1_8.string();
-    }
-
-    int procId;
-    int ptm = create_subprocess(cmd_8.string(), arg0Str, arg1Str, &procId);
-    
-    if (processIdArray) {
-        int procIdLen = env->GetArrayLength(processIdArray);
-        if (procIdLen > 0) {
-            jboolean isCopy;
-    
-            int* pProcId = (int*) env->GetPrimitiveArrayCritical(processIdArray, &isCopy);
-            if (pProcId) {
-                *pProcId = procId;
-                env->ReleasePrimitiveArrayCritical(processIdArray, pProcId, 0);
-            }
-        }
-    }
-    
-    jobject result = env->NewObject(class_fileDescriptor, method_fileDescriptor_init);
-    
-    if (!result) {
-        LOGE("Couldn't create a FileDescriptor.");
-    }
-    else {
-        env->SetIntField(result, field_fileDescriptor_descriptor, ptm);
-    }
-    
-    return result;
-}
-
-
-static void android_os_Exec_setPtyWindowSize(JNIEnv *env, jobject clazz,
-    jobject fileDescriptor, jint row, jint col, jint xpixel, jint ypixel)
-{
-    int fd;
-    struct winsize sz;
-
-    fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
-
-    if (env->ExceptionOccurred() != NULL) {
-        return;
-    }
-    
-    sz.ws_row = row;
-    sz.ws_col = col;
-    sz.ws_xpixel = xpixel;
-    sz.ws_ypixel = ypixel;
-    
-    ioctl(fd, TIOCSWINSZ, &sz);
-}
-
-static int android_os_Exec_waitFor(JNIEnv *env, jobject clazz,
-    jint procId) {
-    int status;
-    waitpid(procId, &status, 0);
-    int result = 0;
-    if (WIFEXITED(status)) {
-        result = WEXITSTATUS(status);
-    }
-    return result;
-}
-
-static JNINativeMethod method_table[] = {
-    { "createSubprocess", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[I)Ljava/io/FileDescriptor;",
-        (void*) android_os_Exec_createSubProcess },
-    { "setPtyWindowSize", "(Ljava/io/FileDescriptor;IIII)V",
-        (void*) android_os_Exec_setPtyWindowSize},
-    { "waitFor", "(I)I",
-        (void*) android_os_Exec_waitFor}
-};
-
-int register_android_os_Exec(JNIEnv *env)
-{
-    class_fileDescriptor = env->FindClass("java/io/FileDescriptor");
-
-    if (class_fileDescriptor == NULL) {
-        LOGE("Can't find java/io/FileDescriptor");
-        return -1;
-    }
-
-    field_fileDescriptor_descriptor = env->GetFieldID(class_fileDescriptor, "descriptor", "I");
-
-    if (field_fileDescriptor_descriptor == NULL) {
-        LOGE("Can't find FileDescriptor.descriptor");
-        return -1;
-    }
-
-    method_fileDescriptor_init = env->GetMethodID(class_fileDescriptor, "<init>", "()V");
-    if (method_fileDescriptor_init == NULL) {
-        LOGE("Can't find FileDescriptor.init");
-        return -1;
-     }
-
-    return AndroidRuntime::registerNativeMethods(
-        env, "android/os/Exec",
-        method_table, NELEM(method_table));
-}
-
-};
diff --git a/core/jni/android_os_MemoryFile.cpp b/core/jni/android_os_MemoryFile.cpp
index 8643393..1ae3ec7 100644
--- a/core/jni/android_os_MemoryFile.cpp
+++ b/core/jni/android_os_MemoryFile.cpp
@@ -118,7 +118,7 @@
     }
 }
 
-static jboolean android_os_MemoryFile_is_ashmem_region(JNIEnv* env, jobject clazz,
+static jint android_os_MemoryFile_get_mapped_size(JNIEnv* env, jobject clazz,
         jobject fileDescriptor) {
     int fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
     // Use ASHMEM_GET_SIZE to find out if the fd refers to an ashmem region.
@@ -129,13 +129,13 @@
         if (errno == ENOTTY) {
             // ENOTTY means that the ioctl does not apply to this object,
             // i.e., it is not an ashmem region.
-            return JNI_FALSE;
+            return (jint) -1;
         }
         // Some other error, throw exception
         jniThrowIOException(env, errno);
-        return JNI_FALSE;
+        return (jint) -1;
     }
-    return JNI_TRUE;
+    return (jint) result;
 }
 
 static const JNINativeMethod methods[] = {
@@ -146,8 +146,8 @@
     {"native_read",  "(Ljava/io/FileDescriptor;I[BIIIZ)I", (void*)android_os_MemoryFile_read},
     {"native_write", "(Ljava/io/FileDescriptor;I[BIIIZ)V", (void*)android_os_MemoryFile_write},
     {"native_pin",   "(Ljava/io/FileDescriptor;Z)V", (void*)android_os_MemoryFile_pin},
-    {"native_is_ashmem_region", "(Ljava/io/FileDescriptor;)Z",
-            (void*)android_os_MemoryFile_is_ashmem_region}
+    {"native_get_mapped_size", "(Ljava/io/FileDescriptor;)I",
+            (void*)android_os_MemoryFile_get_mapped_size}
 };
 
 static const char* const kClassPathName = "android/os/MemoryFile";
diff --git a/core/jni/android_server_BluetoothA2dpService.cpp b/core/jni/android_server_BluetoothA2dpService.cpp
index 91a8e8e..14da1fd 100644
--- a/core/jni/android_server_BluetoothA2dpService.cpp
+++ b/core/jni/android_server_BluetoothA2dpService.cpp
@@ -37,12 +37,7 @@
 namespace android {
 
 #ifdef HAVE_BLUETOOTH
-static jmethodID method_onHeadsetCreated;
-static jmethodID method_onHeadsetRemoved;
-static jmethodID method_onSinkConnected;
-static jmethodID method_onSinkDisconnected;
-static jmethodID method_onSinkPlaying;
-static jmethodID method_onSinkStopped;
+static jmethodID method_onSinkPropertyChanged;
 
 typedef struct {
     JavaVM *vm;
@@ -53,11 +48,11 @@
 
 static native_data_t *nat = NULL;  // global native data
 
-#endif
-
-#ifdef HAVE_BLUETOOTH
-static void onConnectSinkResult(DBusMessage *msg, void *user, void *nat);
-static void onDisconnectSinkResult(DBusMessage *msg, void *user, void *nat);
+static Properties sink_properties[] = {
+        {"State", DBUS_TYPE_STRING},
+        {"Connected", DBUS_TYPE_BOOLEAN},
+        {"Playing", DBUS_TYPE_BOOLEAN},
+      };
 #endif
 
 /* Returns true on success (even if adapter is present but disabled).
@@ -100,91 +95,58 @@
     }
 #endif
 }
-static jobjectArray listHeadsetsNative(JNIEnv *env, jobject object) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    if (nat) {
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, "/org/bluez/audio",
-                           "org.bluez.audio.Manager", "ListHeadsets",
-                           DBUS_TYPE_INVALID);
-        return reply ? dbus_returns_array_of_strings(env, reply) : NULL;
-    }
-#endif
-    return NULL;
-}
 
-static jstring createHeadsetNative(JNIEnv *env, jobject object,
-                                     jstring address) {
+static jobjectArray getSinkPropertiesNative(JNIEnv *env, jobject object,
+                                            jstring path) {
 #ifdef HAVE_BLUETOOTH
     LOGV(__FUNCTION__);
     if (nat) {
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-        LOGV("... address = %s\n", c_address);
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, "/org/bluez/audio",
-                           "org.bluez.audio.Manager", "CreateHeadset",
-                           DBUS_TYPE_STRING, &c_address,
-                           DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(address, c_address);
-        return reply ? dbus_returns_string(env, reply) : NULL;
-    }
-#endif
-    return NULL;
-}
+        DBusMessage *msg, *reply;
+        DBusError err;
+        dbus_error_init(&err);
 
-static jstring removeHeadsetNative(JNIEnv *env, jobject object, jstring path) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    if (nat) {
         const char *c_path = env->GetStringUTFChars(path, NULL);
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, "/org/bluez/audio",
-                           "org.bluez.audio.Manager", "RemoveHeadset",
-                           DBUS_TYPE_STRING, &c_path,
-                           DBUS_TYPE_INVALID);
+        reply = dbus_func_args_timeout(env,
+                                   nat->conn, -1, c_path,
+                                   "org.bluez.AudioSink", "GetProperties",
+                                   DBUS_TYPE_INVALID);
         env->ReleaseStringUTFChars(path, c_path);
-        return reply ? dbus_returns_string(env, reply) : NULL;
+        if (!reply && dbus_error_is_set(&err)) {
+            LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
+            return NULL;
+        } else if (!reply) {
+            LOGE("DBus reply is NULL in function %s", __FUNCTION__);
+            return NULL;
+        }
+        DBusMessageIter iter;
+        if (dbus_message_iter_init(reply, &iter))
+            return parse_properties(env, &iter, (Properties *)&sink_properties,
+                                 sizeof(sink_properties) / sizeof(Properties));
     }
 #endif
     return NULL;
 }
 
-static jstring getAddressNative(JNIEnv *env, jobject object, jstring path) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    if (nat) {
-        const char *c_path = env->GetStringUTFChars(path, NULL);
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, c_path,
-                           "org.bluez.audio.Device", "GetAddress",
-                           DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(path, c_path);
-        return reply ? dbus_returns_string(env, reply) : NULL;
-    }
-#endif
-    return NULL;
-}
 
 static jboolean connectSinkNative(JNIEnv *env, jobject object, jstring path) {
 #ifdef HAVE_BLUETOOTH
     LOGV(__FUNCTION__);
     if (nat) {
         const char *c_path = env->GetStringUTFChars(path, NULL);
-        size_t path_sz = env->GetStringUTFLength(path) + 1;
-        char *c_path_copy = (char *)malloc(path_sz);  // callback data
-        strncpy(c_path_copy, c_path, path_sz);
+        DBusError err;
+        dbus_error_init(&err);
 
-        bool ret =
-            dbus_func_args_async(env, nat->conn, -1,
-                           onConnectSinkResult, (void *)c_path_copy, nat,
-                           c_path,
-                           "org.bluez.audio.Sink", "Connect",
-                           DBUS_TYPE_INVALID);
-
+        DBusMessage *reply =
+                dbus_func_args_timeout(env, nat->conn, -1, c_path,
+                               "org.bluez.AudioSink", "Connect",
+                                DBUS_TYPE_INVALID);
         env->ReleaseStringUTFChars(path, c_path);
-        if (!ret) {
-            free(c_path_copy);
+
+        if (!reply && dbus_error_is_set(&err)) {
+            LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
+            return JNI_FALSE;
+        } else if (!reply) {
+            LOGE("DBus reply is NULL in function %s", __FUNCTION__);
             return JNI_FALSE;
         }
         return JNI_TRUE;
@@ -199,19 +161,20 @@
     LOGV(__FUNCTION__);
     if (nat) {
         const char *c_path = env->GetStringUTFChars(path, NULL);
-        size_t path_sz = env->GetStringUTFLength(path) + 1;
-        char *c_path_copy = (char *)malloc(path_sz);  // callback data
-        strncpy(c_path_copy, c_path, path_sz);
+        DBusError err;
+        dbus_error_init(&err);
 
-        bool ret =
-            dbus_func_args_async(env, nat->conn, -1,
-                           onDisconnectSinkResult, (void *)c_path_copy, nat,
-                           c_path,
-                           "org.bluez.audio.Sink", "Disconnect",
-                           DBUS_TYPE_INVALID);
+        DBusMessage *reply =
+              dbus_func_args_timeout(env, nat->conn, -1, c_path,
+                                     "org.bluez.AudioSink", "Disconnect",
+                                     DBUS_TYPE_INVALID);
         env->ReleaseStringUTFChars(path, c_path);
-        if (!ret) {
-            free(c_path_copy);
+
+        if (!reply && dbus_error_is_set(&err)) {
+            LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
+            return JNI_FALSE;
+        } else if (!reply) {
+            LOGE("DBus reply is NULL in function %s", __FUNCTION__);
             return JNI_FALSE;
         }
         return JNI_TRUE;
@@ -220,93 +183,7 @@
     return JNI_FALSE;
 }
 
-static jboolean isSinkConnectedNative(JNIEnv *env, jobject object, jstring path) {
 #ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    if (nat) {
-        const char *c_path = env->GetStringUTFChars(path, NULL);
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, c_path,
-                           "org.bluez.audio.Sink", "IsConnected",
-                           DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(path, c_path);
-        return reply ? dbus_returns_boolean(env, reply) : JNI_FALSE;
-    }
-#endif
-    return JNI_FALSE;
-}
-
-#ifdef HAVE_BLUETOOTH
-static void onConnectSinkResult(DBusMessage *msg, void *user, void *natData) {
-    LOGV(__FUNCTION__);
-
-    char *c_path = (char *)user;
-    DBusError err;
-    JNIEnv *env;
-
-    if (nat->vm->GetEnv((void**)&env, nat->envVer) < 0) {
-        LOGE("%s: error finding Env for our VM\n", __FUNCTION__);
-        return;
-    }
-
-    dbus_error_init(&err);
-
-    LOGV("... path = %s", c_path);
-    if (dbus_set_error_from_message(&err, msg)) {
-        /* if (!strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.AuthenticationFailed")) */
-        LOGE("%s: D-Bus error: %s (%s)\n", __FUNCTION__, err.name, err.message);
-        dbus_error_free(&err);
-        env->CallVoidMethod(nat->me,
-                            method_onSinkDisconnected,
-                            env->NewStringUTF(c_path));
-        if (env->ExceptionCheck()) {
-            LOGE("VM Exception occurred in native function %s (%s:%d)",
-                 __FUNCTION__, __FILE__, __LINE__);
-        }
-    } // else Java callback is triggered by signal in a2dp_event_filter
-
-    free(c_path);
-}
-
-static void onDisconnectSinkResult(DBusMessage *msg, void *user, void *natData) {
-    LOGV(__FUNCTION__);
-
-    char *c_path = (char *)user;
-    DBusError err;
-    JNIEnv *env;
-
-    if (nat->vm->GetEnv((void**)&env, nat->envVer) < 0) {
-        LOGE("%s: error finding Env for our VM\n", __FUNCTION__);
-        return;
-    }
-
-    dbus_error_init(&err);
-
-    LOGV("... path = %s", c_path);
-    if (dbus_set_error_from_message(&err, msg)) {
-        /* if (!strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.AuthenticationFailed")) */
-        LOGE("%s: D-Bus error: %s (%s)\n", __FUNCTION__, err.name, err.message);
-        if (strcmp(err.name, "org.bluez.Error.NotConnected") == 0) {
-            // we were already disconnected, so report disconnect
-            env->CallVoidMethod(nat->me,
-                                method_onSinkDisconnected,
-                                env->NewStringUTF(c_path));
-        } else {
-            // Assume it is still connected
-            env->CallVoidMethod(nat->me,
-                                method_onSinkConnected,
-                                env->NewStringUTF(c_path));
-        }
-        dbus_error_free(&err);
-        if (env->ExceptionCheck()) {
-            LOGE("VM Exception occurred in native function %s (%s:%d)",
-                 __FUNCTION__, __FILE__, __LINE__);
-        }
-    } // else Java callback is triggered by signal in a2dp_event_filter
-
-    free(c_path);
-}
-
 DBusHandlerResult a2dp_event_filter(DBusMessage *msg, JNIEnv *env) {
     DBusError err;
 
@@ -324,71 +201,23 @@
 
     DBusHandlerResult result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
 
-    if (dbus_message_is_signal(msg,
-                               "org.bluez.audio.Manager",
-                               "HeadsetCreated")) {
-        char *c_path;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_path,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... path = %s", c_path);
-            env->CallVoidMethod(nat->me,
-                                method_onHeadsetCreated,
-                                env->NewStringUTF(c_path));
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        result = DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.audio.Manager",
-                                      "HeadsetRemoved")) {
-        char *c_path;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_path,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... path = %s", c_path);
-            env->CallVoidMethod(nat->me,
-                                method_onHeadsetRemoved,
-                                env->NewStringUTF(c_path));
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        result = DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.audio.Sink",
-                                      "Connected")) {
+    if (dbus_message_is_signal(msg, "org.bluez.AudioSink",
+                                      "PropertyChanged")) {
+        jobjectArray str_array =
+                    parse_property_change(env, msg, (Properties *)&sink_properties,
+                                sizeof(sink_properties) / sizeof(Properties));
         const char *c_path = dbus_message_get_path(msg);
-        LOGV("... path = %s", c_path);
         env->CallVoidMethod(nat->me,
-                            method_onSinkConnected,
-                            env->NewStringUTF(c_path));
+                            method_onSinkPropertyChanged,
+                            env->NewStringUTF(c_path),
+                            str_array);
+        for (int i = 0; i < env->GetArrayLength(str_array); i++) {
+            env->DeleteLocalRef(env->GetObjectArrayElement(str_array, i));
+        }
+        env->DeleteLocalRef(str_array);
         result = DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.audio.Sink",
-                                      "Disconnected")) {
-        const char *c_path = dbus_message_get_path(msg);
-        LOGV("... path = %s", c_path);
-        env->CallVoidMethod(nat->me,
-                            method_onSinkDisconnected,
-                            env->NewStringUTF(c_path));
-        result = DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.audio.Sink",
-                                      "Playing")) {
-        const char *c_path = dbus_message_get_path(msg);
-        LOGV("... path = %s", c_path);
-        env->CallVoidMethod(nat->me,
-                            method_onSinkPlaying,
-                            env->NewStringUTF(c_path));
-        result = DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.audio.Sink",
-                                      "Stopped")) {
-        const char *c_path = dbus_message_get_path(msg);
-        LOGV("... path = %s", c_path);
-        env->CallVoidMethod(nat->me,
-                            method_onSinkStopped,
-                            env->NewStringUTF(c_path));
-        result = DBUS_HANDLER_RESULT_HANDLED;
-    }
-
-    if (result == DBUS_HANDLER_RESULT_NOT_YET_HANDLED) {
+        return result;
+    } else {
         LOGV("... ignored");
     }
     if (env->ExceptionCheck()) {
@@ -407,14 +236,11 @@
     {"initNative", "()Z", (void *)initNative},
     {"cleanupNative", "()V", (void *)cleanupNative},
 
-    /* Bluez audio 3.36 API */
-    {"listHeadsetsNative", "()[Ljava/lang/String;", (void*)listHeadsetsNative},
-    {"createHeadsetNative", "(Ljava/lang/String;)Ljava/lang/String;", (void*)createHeadsetNative},
-    {"removeHeadsetNative", "(Ljava/lang/String;)Z", (void*)removeHeadsetNative},
-    {"getAddressNative", "(Ljava/lang/String;)Ljava/lang/String;", (void*)getAddressNative},
-    {"connectSinkNative", "(Ljava/lang/String;)Z", (void*)connectSinkNative},
-    {"disconnectSinkNative", "(Ljava/lang/String;)Z", (void*)disconnectSinkNative},
-    {"isSinkConnectedNative", "(Ljava/lang/String;)Z", (void*)isSinkConnectedNative},
+    /* Bluez audio 4.40 API */
+    {"connectSinkNative", "(Ljava/lang/String;)Z", (void *)connectSinkNative},
+    {"disconnectSinkNative", "(Ljava/lang/String;)Z", (void *)disconnectSinkNative},
+    {"getSinkPropertiesNative", "(Ljava/lang/String;)[Ljava/lang/Object;",
+                                    (void *)getSinkPropertiesNative},
 };
 
 int register_android_server_BluetoothA2dpService(JNIEnv *env) {
@@ -425,12 +251,8 @@
     }
 
 #ifdef HAVE_BLUETOOTH
-    method_onHeadsetCreated = env->GetMethodID(clazz, "onHeadsetCreated", "(Ljava/lang/String;)V");
-    method_onHeadsetRemoved = env->GetMethodID(clazz, "onHeadsetRemoved", "(Ljava/lang/String;)V");
-    method_onSinkConnected = env->GetMethodID(clazz, "onSinkConnected", "(Ljava/lang/String;)V");
-    method_onSinkDisconnected = env->GetMethodID(clazz, "onSinkDisconnected", "(Ljava/lang/String;)V");
-    method_onSinkPlaying = env->GetMethodID(clazz, "onSinkPlaying", "(Ljava/lang/String;)V");
-    method_onSinkStopped = env->GetMethodID(clazz, "onSinkStopped", "(Ljava/lang/String;)V");
+    method_onSinkPropertyChanged = env->GetMethodID(clazz, "onSinkPropertyChanged",
+                                          "(Ljava/lang/String;[Ljava/lang/String;)V");
 #endif
 
     return AndroidRuntime::registerNativeMethods(env,
diff --git a/core/jni/android_server_BluetoothDeviceService.cpp b/core/jni/android_server_BluetoothDeviceService.cpp
index 58ae4f6..444e628 100644
--- a/core/jni/android_server_BluetoothDeviceService.cpp
+++ b/core/jni/android_server_BluetoothDeviceService.cpp
@@ -14,7 +14,8 @@
 ** limitations under the License.
 */
 
-#define DBUS_CLASS_NAME BLUEZ_DBUS_BASE_IFC ".Adapter"
+#define DBUS_ADAPTER_IFACE BLUEZ_DBUS_BASE_IFC ".Adapter"
+#define DBUS_DEVICE_IFACE BLUEZ_DBUS_BASE_IFC ".Device"
 #define LOG_TAG "BluetoothDeviceService.cpp"
 
 #include "android_bluetooth_common.h"
@@ -60,8 +61,11 @@
 
 extern event_loop_native_data_t *get_EventLoop_native_data(JNIEnv *,
                                                            jobject);
-void onCreateBondingResult(DBusMessage *msg, void *user, void *nat);
-void onGetRemoteServiceChannelResult(DBusMessage *msg, void *user, void *nat);
+extern DBusHandlerResult agent_event_filter(DBusConnection *conn,
+                                            DBusMessage *msg,
+                                            void *data);
+void onCreatePairedDeviceResult(DBusMessage *msg, void *user, void *nat);
+
 
 /** Get native data stored in the opaque (Java code maintained) pointer mNativeData
  *  Perform quick sanity check, if there are any problems return NULL
@@ -110,12 +114,61 @@
         return false;
     }
     dbus_connection_set_exit_on_disconnect(nat->conn, FALSE);
-
-    nat->adapter = BLUEZ_ADAPTER_OBJECT_NAME;
 #endif  /*HAVE_BLUETOOTH*/
     return true;
 }
 
+static const char *get_adapter_path(JNIEnv* env, jobject object) {
+#ifdef HAVE_BLUETOOTH
+    event_loop_native_data_t *event_nat =
+        get_EventLoop_native_data(env, env->GetObjectField(object,
+                                                           field_mEventLoop));
+    if (event_nat == NULL)
+        return NULL;
+    return event_nat->adapter;
+#else
+    return NULL;
+#endif
+}
+
+// This function is called when the adapter is enabled.
+static jboolean setupNativeDataNative(JNIEnv* env, jobject object) {
+    LOGV(__FUNCTION__);
+#ifdef HAVE_BLUETOOTH
+    native_data_t *nat =
+        (native_data_t *)env->GetIntField(object, field_mNativeData);
+    event_loop_native_data_t *event_nat =
+        get_EventLoop_native_data(env, env->GetObjectField(object,
+                                                           field_mEventLoop));
+    // Register agent for remote devices.
+    const char *device_agent_path = "/android/bluetooth/remote_device_agent";
+    static const DBusObjectPathVTable agent_vtable = {
+                 NULL, agent_event_filter, NULL, NULL, NULL, NULL };
+
+    if (!dbus_connection_register_object_path(nat->conn, device_agent_path,
+                                              &agent_vtable, event_nat)) {
+        LOGE("%s: Can't register object path %s for remote device agent!",
+                               __FUNCTION__, device_agent_path);
+        return JNI_FALSE;
+    }
+#endif /*HAVE_BLUETOOTH*/
+    return JNI_TRUE;
+}
+
+static jboolean tearDownNativeDataNative(JNIEnv *env, jobject object) {
+    LOGV(__FUNCTION__);
+#ifdef HAVE_BLUETOOTH
+    native_data_t *nat =
+               (native_data_t *)env->GetIntField(object, field_mNativeData);
+    if (nat != NULL) {
+        const char *device_agent_path =
+            "/android/bluetooth/remote_device_agent";
+        dbus_connection_unregister_object_path (nat->conn, device_agent_path);
+    }
+#endif /*HAVE_BLUETOOTH*/
+    return JNI_TRUE;
+}
+
 static void cleanupNativeDataNative(JNIEnv* env, jobject object) {
     LOGV(__FUNCTION__);
 #ifdef HAVE_BLUETOOTH
@@ -128,26 +181,12 @@
 #endif
 }
 
-static jstring getNameNative(JNIEnv *env, jobject object){
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        DBusMessage *reply = dbus_func_args(env, nat->conn, nat->adapter,
-                                            DBUS_CLASS_NAME, "GetName",
-                                            DBUS_TYPE_INVALID);
-        return reply ? dbus_returns_string(env, reply) : NULL;
-    }
-#endif
-    return NULL;
-}
-
 static jstring getAdapterPathNative(JNIEnv *env, jobject object) {
     LOGV(__FUNCTION__);
 #ifdef HAVE_BLUETOOTH
     native_data_t *nat = get_native_data(env, object);
     if (nat) {
-        return (env->NewStringUTF(nat->adapter));
+        return (env->NewStringUTF(get_adapter_path(env, object)));
     }
 #endif
     return NULL;
@@ -171,28 +210,23 @@
     dbus_error_init(&err);
 
     /* Compose the command */
-    msg = dbus_message_new_method_call(BLUEZ_DBUS_BASE_IFC, nat->adapter,
-                                       DBUS_CLASS_NAME, "DiscoverDevices");
+    msg = dbus_message_new_method_call(BLUEZ_DBUS_BASE_IFC,
+                                       get_adapter_path(env, object),
+                                       DBUS_ADAPTER_IFACE, "StartDiscovery");
 
     if (msg == NULL) {
-        LOGE("%s: Could not allocate D-Bus message object!", __FUNCTION__);
+        if (dbus_error_is_set(&err)) {
+            LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
+        }
         goto done;
     }
 
     /* Send the command. */
     reply = dbus_connection_send_with_reply_and_block(nat->conn, msg, -1, &err);
     if (dbus_error_is_set(&err)) {
-        /* We treat the in-progress error code as success. */
-        if(strcmp(err.message, BLUEZ_DBUS_BASE_IFC ".Error.InProgress") == 0) {
-            LOGW("%s: D-Bus error: %s, treating as startDiscoveryNative success\n",
-                 __FUNCTION__, err.message);
-            ret = JNI_TRUE;
-            goto done;
-        } else {
-            LOGE("%s: D-Bus error: %s (%s)\n", __FUNCTION__, err.name, err.message);
-            ret = JNI_FALSE;
-            goto done;
-        }
+         LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
+         ret = JNI_FALSE;
+         goto done;
     }
 
     ret = JNI_TRUE;
@@ -205,7 +239,7 @@
 #endif
 }
 
-static void cancelDiscoveryNative(JNIEnv *env, jobject object) {
+static void stopDiscoveryNative(JNIEnv *env, jobject object) {
     LOGV(__FUNCTION__);
 #ifdef HAVE_BLUETOOTH
     DBusMessage *msg = NULL;
@@ -223,18 +257,20 @@
     }
 
     /* Compose the command */
-    msg = dbus_message_new_method_call(BLUEZ_DBUS_BASE_IFC, nat->adapter,
-                                       DBUS_CLASS_NAME, "CancelDiscovery");
-
+    msg = dbus_message_new_method_call(BLUEZ_DBUS_BASE_IFC,
+                                       get_adapter_path(env, object),
+                                       DBUS_ADAPTER_IFACE, "StopDiscovery");
     if (msg == NULL) {
-        LOGE("%s: Could not allocate D-Bus message object!", __FUNCTION__);
+        if (dbus_error_is_set(&err))
+            LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
         goto done;
     }
 
     /* Send the command. */
     reply = dbus_connection_send_with_reply_and_block(nat->conn, msg, -1, &err);
     if (dbus_error_is_set(&err)) {
-        if(strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.NotAuthorized") == 0) {
+        if(strncmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.NotAuthorized",
+                   strlen(BLUEZ_DBUS_BASE_IFC ".Error.NotAuthorized")) == 0) {
             // hcid sends this if there is no active discovery to cancel
             LOGV("%s: There was no active discovery to cancel", __FUNCTION__);
             dbus_error_free(&err);
@@ -249,232 +285,8 @@
 #endif
 }
 
-static jboolean startPeriodicDiscoveryNative(JNIEnv *env, jobject object) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    DBusMessage *msg = NULL;
-    DBusMessage *reply = NULL;
-    DBusError err;
-    jboolean ret = JNI_FALSE;
-
-    native_data_t *nat = get_native_data(env, object);
-    if (nat == NULL) {
-        goto done;
-    }
-
-    dbus_error_init(&err);
-    msg = dbus_message_new_method_call(BLUEZ_DBUS_BASE_IFC, nat->adapter,
-            DBUS_CLASS_NAME, "StartPeriodicDiscovery");
-    if (msg == NULL) {
-        LOGE("%s: Could not allocate DBUS message object\n", __FUNCTION__);
-        goto done;
-    }
-
-    /* Send the command. */
-    reply = dbus_connection_send_with_reply_and_block(nat->conn, msg, -1, &err);
-    if (dbus_error_is_set(&err)) {
-        /* We treat the in-progress error code as success. */
-        if(strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.InProgress") == 0) {
-            LOGW("%s: D-Bus error: %s (%s), treating as "
-                 "startPeriodicDiscoveryNative success\n",
-                 __FUNCTION__, err.name, err.message);
-        } else {
-            LOGE("%s: D-Bus error: %s (%s)\n", __FUNCTION__, err.name, err.message);
-            ret = JNI_FALSE;
-            goto done;
-        }
-    }
-
-    ret = JNI_TRUE;
-done:
-    if (reply) dbus_message_unref(reply);
-    if (msg) dbus_message_unref(msg);
-    return ret;
-#else
-    return JNI_FALSE;
-#endif
-}
-
-static jboolean stopPeriodicDiscoveryNative(JNIEnv *env, jobject object) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    DBusMessage *msg = NULL;
-    DBusMessage *reply = NULL;
-    DBusError err;
-    const char *name;
-    jboolean ret = JNI_FALSE;
-
-    native_data_t *nat = get_native_data(env, object);
-    if (nat == NULL) {
-        goto done;
-    }
-
-    dbus_error_init(&err);
-    msg = dbus_message_new_method_call(BLUEZ_DBUS_BASE_IFC, nat->adapter,
-            DBUS_CLASS_NAME, "StopPeriodicDiscovery");
-    if (msg == NULL) {
-        LOGE("%s: Could not allocate DBUS message object\n", __FUNCTION__);
-        goto done;
-    }
-
-    /* Send the command. */
-    reply = dbus_connection_send_with_reply_and_block(nat->conn, msg, -1, &err);
-    if (dbus_error_is_set(&err)) {
-        /* We treat the in-progress error code as success. */
-        if(strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.InProgress") == 0) {
-            LOGW("%s: D-Bus error: %s (%s), treating as "
-                 "stopPeriodicDiscoveryNative success\n",
-                 __FUNCTION__, err.name, err.message);
-        } else {
-            LOGE("%s: D-Bus error: %s (%s)\n", __FUNCTION__, err.name, err.message);
-            ret = JNI_FALSE;
-            goto done;
-        }
-    }
-
-    ret = JNI_TRUE;
-done:
-    if (reply) dbus_message_unref(reply);
-    if (msg) dbus_message_unref(msg);
-    return ret;
-#else
-    return JNI_FALSE;
-#endif
-}
-
-static jboolean isPeriodicDiscoveryNative(JNIEnv *env, jobject object) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "IsPeriodicDiscovery",
-                           DBUS_TYPE_INVALID);
-        return reply ? dbus_returns_boolean(env, reply) : JNI_FALSE;
-    }
-#endif
-    return JNI_FALSE;
-}
-
-static jboolean setDiscoverableTimeoutNative(JNIEnv *env, jobject object, jint timeout_s) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-
-    if (timeout_s < 0) {
-        return JNI_FALSE;
-    }
-
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "SetDiscoverableTimeout",
-                           DBUS_TYPE_UINT32, &timeout_s,
-                           DBUS_TYPE_INVALID);
-        if (reply != NULL) {
-            dbus_message_unref(reply);
-            return JNI_TRUE;
-        }
-    }
-#endif
-    return JNI_FALSE;
-}
-
-static jint getDiscoverableTimeoutNative(JNIEnv *env, jobject object) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "GetDiscoverableTimeout",
-                           DBUS_TYPE_INVALID);
-        return reply ? dbus_returns_uint32(env, reply) : -1;
-    }
-#endif
-    return -1;
-}
-
-static jboolean isConnectedNative(JNIEnv *env, jobject object, jstring address) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "IsConnected",
-                           DBUS_TYPE_STRING, &c_address,
-                           DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(address, c_address);
-        return reply ? dbus_returns_boolean(env, reply) : JNI_FALSE;
-    }
-#endif
-    return JNI_FALSE;
-}
-
-static void disconnectRemoteDeviceNative(JNIEnv *env, jobject object, jstring address) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-        // Set a timeout of 5 seconds.  Specifying the default timeout is
-        // not long enough, as a remote-device disconnect results in
-        // signal RemoteDisconnectRequested being sent, followed by a
-        // delay of 2 seconds, after which the actual disconnect takes
-        // place.
-        DBusMessage *reply =
-            dbus_func_args_timeout(env, nat->conn, 60000, nat->adapter,
-                                   DBUS_CLASS_NAME, "DisconnectRemoteDevice",
-                                   DBUS_TYPE_STRING, &c_address,
-                                   DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(address, c_address);
-        if (reply) dbus_message_unref(reply);
-    }
-#endif
-}
-
-static jstring getModeNative(JNIEnv *env, jobject object) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "GetMode",
-                           DBUS_TYPE_INVALID);
-        return reply ? dbus_returns_string(env, reply) : NULL;
-    }
-#endif
-    return NULL;
-}
-
-static jboolean setModeNative(JNIEnv *env, jobject object, jstring mode) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        const char *c_mode = env->GetStringUTFChars(mode, NULL);
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "SetMode",
-                           DBUS_TYPE_STRING, &c_mode,
-                           DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(mode, c_mode);
-        if (reply) {
-            dbus_message_unref(reply);
-            return JNI_TRUE;
-        }
-        return JNI_FALSE;
-    }
-#endif
-    return JNI_FALSE;
-}
-
-static jboolean createBondingNative(JNIEnv *env, jobject object,
-                                    jstring address, jint timeout_ms) {
+static jboolean createPairedDeviceNative(JNIEnv *env, jobject object,
+                                         jstring address, jint timeout_ms) {
     LOGV(__FUNCTION__);
 #ifdef HAVE_BLUETOOTH
     native_data_t *nat = get_native_data(env, object);
@@ -486,14 +298,20 @@
         const char *c_address = env->GetStringUTFChars(address, NULL);
         LOGV("... address = %s", c_address);
         char *context_address = (char *)calloc(BTADDR_SIZE, sizeof(char));
+        const char *capabilities = "DisplayYesNo";
+        const char *agent_path = "/android/bluetooth/remote_device_agent";
+
         strlcpy(context_address, c_address, BTADDR_SIZE);  // for callback
         bool ret = dbus_func_args_async(env, nat->conn, (int)timeout_ms,
-                                        onCreateBondingResult, // callback
+                                        onCreatePairedDeviceResult, // callback
                                         context_address,
                                         eventLoopNat,
-                                        nat->adapter,
-                                        DBUS_CLASS_NAME, "CreateBonding",
+                                        get_adapter_path(env, object),
+                                        DBUS_ADAPTER_IFACE,
+                                        "CreatePairedDevice",
                                         DBUS_TYPE_STRING, &c_address,
+                                        DBUS_TYPE_OBJECT_PATH, &agent_path,
+                                        DBUS_TYPE_STRING, &capabilities,
                                         DBUS_TYPE_INVALID);
         env->ReleaseStringUTFChars(address, c_address);
         return ret ? JNI_TRUE : JNI_FALSE;
@@ -503,367 +321,9 @@
     return JNI_FALSE;
 }
 
-static jboolean cancelBondingProcessNative(JNIEnv *env, jobject object,
-                                       jstring address) {
-    LOGV(__FUNCTION__);
-#ifdef HAVE_BLUETOOTH
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-        LOGV("... address = %s", c_address);
-        DBusMessage *reply =
-            dbus_func_args_timeout(env, nat->conn, -1, nat->adapter,
-                                   DBUS_CLASS_NAME, "CancelBondingProcess",
-                                   DBUS_TYPE_STRING, &c_address,
-                                   DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(address, c_address);
-        if (reply) {
-            dbus_message_unref(reply);
-        }
-        return JNI_TRUE;
-    }
-#endif
-    return JNI_FALSE;
-}
-
-static jboolean removeBondingNative(JNIEnv *env, jobject object, jstring address) {
-    LOGV(__FUNCTION__);
-    jboolean result = JNI_FALSE;
-#ifdef HAVE_BLUETOOTH
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-        LOGV("... address = %s", c_address);
-        DBusError err;
-        dbus_error_init(&err);
-        DBusMessage *reply =
-            dbus_func_args_error(env, nat->conn, &err, nat->adapter,
-                                 DBUS_CLASS_NAME, "RemoveBonding",
-                                 DBUS_TYPE_STRING, &c_address,
-                                 DBUS_TYPE_INVALID);
-        if (dbus_error_is_set(&err)) {
-            if (dbus_error_has_name(&err,
-                    BLUEZ_DBUS_BASE_IFC ".Error.DoesNotExist")) {
-                LOGW("%s: Warning: %s (%s)", __FUNCTION__, err.message,
-                     c_address);
-                result = JNI_TRUE;
-            } else {
-                LOGE("%s: D-Bus error %s (%s)", __FUNCTION__, err.name,
-                        err.message);
-            }
-        } else {
-            result = JNI_TRUE;
-        }
-
-        env->ReleaseStringUTFChars(address, c_address);
-        dbus_error_free(&err);
-        if (reply) dbus_message_unref(reply);
-    }
-#endif
-    return result;
-}
-
-static jobjectArray listBondingsNative(JNIEnv *env, jobject object) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "ListBondings",
-                           DBUS_TYPE_INVALID);
-        // return String[]
-        return reply ? dbus_returns_array_of_strings(env, reply) : NULL;
-    }
-#endif
-    return NULL;
-}
-
-static jobjectArray listConnectionsNative(JNIEnv *env, jobject object) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "ListConnections",
-                           DBUS_TYPE_INVALID);
-        // return String[]
-        return reply ? dbus_returns_array_of_strings(env, reply) : NULL;
-    }
-#endif
-    return NULL;
-}
-
-static jobjectArray listRemoteDevicesNative(JNIEnv *env, jobject object) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "ListRemoteDevices",
-                           DBUS_TYPE_INVALID);
-        return reply ? dbus_returns_array_of_strings(env, reply) : NULL;
-    }
-#endif
-    return NULL;
-}
-
-static jstring common_Get(JNIEnv *env, jobject object, const char *func) {
-    LOGV("%s:%s", __FUNCTION__, func);
-#ifdef HAVE_BLUETOOTH
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        DBusError err;
-        dbus_error_init(&err);
-        DBusMessage *reply =
-            dbus_func_args_error(env, nat->conn, &err, nat->adapter,
-                                 DBUS_CLASS_NAME, func,
-                                 DBUS_TYPE_INVALID);
-        if (reply) {
-            return dbus_returns_string(env, reply);
-        } else {
-            LOG_AND_FREE_DBUS_ERROR(&err);
-            return NULL;
-        }
-    }
-#endif
-    return NULL;
-}
-
-static jstring getAddressNative(JNIEnv *env, jobject obj) {
-    return common_Get(env, obj, "GetAddress");
-}
-
-static jstring getVersionNative(JNIEnv *env, jobject obj) {
-    return common_Get(env, obj, "GetVersion");
-}
-
-static jstring getRevisionNative(JNIEnv *env, jobject obj) {
-    return common_Get(env, obj, "GetRevision");
-}
-
-static jstring getManufacturerNative(JNIEnv *env, jobject obj) {
-    return common_Get(env, obj, "GetManufacturer");
-}
-
-static jstring getCompanyNative(JNIEnv *env, jobject obj) {
-    return common_Get(env, obj, "GetCompany");
-}
-
-static jboolean setNameNative(JNIEnv *env, jobject obj, jstring name) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, obj);
-    if (nat) {
-        const char *c_name = env->GetStringUTFChars(name, NULL);
-        DBusMessage *reply = dbus_func_args(env, nat->conn, nat->adapter,
-                                            DBUS_CLASS_NAME, "SetName",
-                                            DBUS_TYPE_STRING, &c_name,
-                                            DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(name, c_name);
-        if (reply) {
-            dbus_message_unref(reply);
-            return JNI_TRUE;
-        }
-    }
-#endif
-    return JNI_FALSE;
-}
-
-static jstring common_getRemote(JNIEnv *env, jobject object, const char *func,
-                                jstring address) {
-    LOGV("%s:%s", __FUNCTION__, func);
-#ifdef HAVE_BLUETOOTH
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-        DBusError err;
-        dbus_error_init(&err);
-
-        LOGV("... address = %s", c_address);
-
-        DBusMessage *reply =
-            dbus_func_args_error(env, nat->conn, &err, nat->adapter,
-                                 DBUS_CLASS_NAME, func,
-                                 DBUS_TYPE_STRING, &c_address,
-                                 DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(address, c_address);
-        if (reply) {
-            return dbus_returns_string(env, reply);
-        } else if (!strcmp(func, "GetRemoteName") &&
-                dbus_error_has_name(&err, "org.bluez.Error.RequestDeferred")) {
-            // This error occurs if we request name during device discovery,
-            // its fine
-            LOGV("... %s: %s", func, err.message);
-            dbus_error_free(&err);
-            return NULL;
-        } else {
-            LOG_AND_FREE_DBUS_ERROR(&err);
-            return NULL;
-        }
-    }
-#endif
-    return NULL;
-}
-
-static jstring getRemoteVersionNative(JNIEnv *env, jobject obj, jstring address) {
-    return common_getRemote(env, obj, "GetRemoteVersion", address);
-}
-
-static jstring getRemoteRevisionNative(JNIEnv *env, jobject obj, jstring address) {
-    return common_getRemote(env, obj, "GetRemoteRevision", address);
-}
-
-static jstring getRemoteManufacturerNative(JNIEnv *env, jobject obj, jstring address) {
-    return common_getRemote(env, obj, "GetRemoteManufacturer", address);
-}
-
-static jstring getRemoteCompanyNative(JNIEnv *env, jobject obj, jstring address) {
-    return common_getRemote(env, obj, "GetRemoteCompany", address);
-}
-
-static jstring getRemoteNameNative(JNIEnv *env, jobject obj, jstring address) {
-    return common_getRemote(env, obj, "GetRemoteName", address);
-}
-
-static jstring lastSeenNative(JNIEnv *env, jobject obj, jstring address) {
-    return common_getRemote(env, obj, "LastSeen", address);
-}
-
-static jstring lastUsedNative(JNIEnv *env, jobject obj, jstring address) {
-    return common_getRemote(env, obj, "LastUsed", address);
-}
-
-static jint getRemoteClassNative(JNIEnv *env, jobject object, jstring address) {
-    jint result = BLUETOOTH_CLASS_ERROR;
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-
-        LOGV("... address = %s", c_address);
-
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "GetRemoteClass",
-                           DBUS_TYPE_STRING, &c_address,
-                           DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(address, c_address);
-        if (reply)
-        {
-            DBusError err;
-            dbus_error_init(&err);
-            if (!dbus_message_get_args(reply, &err,
-                                      DBUS_TYPE_UINT32, &result,
-                                      DBUS_TYPE_INVALID)) {
-                LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
-            }
-            dbus_message_unref(reply);
-        }
-    }
-#endif
-    return result;
-}
-
-static jbyteArray getRemoteFeaturesNative(JNIEnv *env, jobject object,
-                                          jstring address) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-
-        LOGV("... address = %s", c_address);
-
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "GetRemoteFeatures",
-                           DBUS_TYPE_STRING, &c_address,
-                           DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(address, c_address);
-        /* array of DBUS_TYPE_BYTE_AS_STRING */
-        return reply ? dbus_returns_array_of_bytes(env, reply) : NULL;
-    }
-#endif
-    return NULL;
-}
-
-static jintArray getRemoteServiceHandlesNative(JNIEnv *env, jobject object,
-                                               jstring address, jstring match) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        jintArray intArray = NULL;
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-        const char *c_match = env->GetStringUTFChars(match, NULL);
-
-        LOGV("... address = %s match = %s", c_address, c_match);
-
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "GetRemoteServiceHandles",
-                           DBUS_TYPE_STRING, &c_address,
-                           DBUS_TYPE_STRING, &c_match,
-                           DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(address, c_address);
-        env->ReleaseStringUTFChars(match, c_match);
-        if (reply)
-        {
-            DBusError err;
-            jint *list;
-            int i, len;
-
-            dbus_error_init(&err);
-            if (dbus_message_get_args (reply, &err,
-                                       DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32,
-                                       &list, &len,
-                                       DBUS_TYPE_INVALID)) {
-                if (len) {
-                    intArray = env->NewIntArray(len);
-                    if (intArray)
-                        env->SetIntArrayRegion(intArray, 0, len, list);
-                }
-            } else {
-                LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
-            }
-
-            dbus_message_unref(reply);
-        }
-        return intArray;
-    }
-#endif
-    return NULL;
-}
-
-static jbyteArray getRemoteServiceRecordNative(JNIEnv *env, jobject object,
-                                                 jstring address, jint handle) {
-#ifdef HAVE_BLUETOOTH
-    LOGV(__FUNCTION__);
-    native_data_t *nat = get_native_data(env, object);
-    if (nat) {
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-
-        LOGV("... address = %s", c_address);
-
-        DBusMessage *reply =
-            dbus_func_args(env, nat->conn, nat->adapter,
-                           DBUS_CLASS_NAME, "GetRemoteServiceRecord",
-                           DBUS_TYPE_STRING, &c_address,
-                           DBUS_TYPE_UINT32, &handle,
-                           DBUS_TYPE_INVALID);
-        env->ReleaseStringUTFChars(address, c_address);
-        return reply ? dbus_returns_array_of_bytes(env, reply) : NULL;
-    }
-#endif
-    return NULL;
-}
-
-static jboolean getRemoteServiceChannelNative(JNIEnv *env, jobject object,
-                                          jstring address, jshort uuid16) {
+static jint getDeviceServiceChannelNative(JNIEnv *env, jobject object,
+                                          jstring path,
+                                          jstring pattern, jint attr_id) {
 #ifdef HAVE_BLUETOOTH
     LOGV(__FUNCTION__);
     native_data_t *nat = get_native_data(env, object);
@@ -871,28 +331,88 @@
     struct event_loop_native_data_t *eventLoopNat =
             get_EventLoop_native_data(env, eventLoop);
     if (nat && eventLoopNat) {
-        const char *c_address = env->GetStringUTFChars(address, NULL);
-        char *context_address = (char *)calloc(BTADDR_SIZE, sizeof(char));
-        strlcpy(context_address, c_address, BTADDR_SIZE);
-
-        LOGV("... address = %s", c_address);
-        LOGV("... uuid16 = %#X", uuid16);
-
-        bool ret = dbus_func_args_async(env, nat->conn, 20000,  // ms
-                           onGetRemoteServiceChannelResult, context_address,
-                           eventLoopNat,
-                           nat->adapter,
-                           DBUS_CLASS_NAME, "GetRemoteServiceChannel",
-                           DBUS_TYPE_STRING, &c_address,
-                           DBUS_TYPE_UINT16, &uuid16,
+        const char *c_pattern = env->GetStringUTFChars(pattern, NULL);
+        const char *c_path = env->GetStringUTFChars(path, NULL);
+        LOGV("... pattern = %s", c_pattern);
+        LOGV("... attr_id = %#X", attr_id);
+        DBusMessage *reply =
+            dbus_func_args(env, nat->conn, c_path,
+                           DBUS_DEVICE_IFACE, "GetServiceAttributeValue",
+                           DBUS_TYPE_STRING, &c_pattern,
+                           DBUS_TYPE_UINT16, &attr_id,
                            DBUS_TYPE_INVALID);
+        env->ReleaseStringUTFChars(pattern, c_pattern);
+        env->ReleaseStringUTFChars(path, c_path);
+        return reply ? dbus_returns_int32(env, reply) : -1;
+    }
+#endif
+    return -1;
+}
+
+static jboolean cancelDeviceCreationNative(JNIEnv *env, jobject object,
+                                           jstring address) {
+    LOGV(__FUNCTION__);
+    jboolean result = JNI_FALSE;
+#ifdef HAVE_BLUETOOTH
+    native_data_t *nat = get_native_data(env, object);
+    if (nat) {
+        const char *c_address = env->GetStringUTFChars(address, NULL);
+        DBusError err;
+        dbus_error_init(&err);
+        LOGV("... address = %s", c_address);
+        DBusMessage *reply =
+            dbus_func_args_timeout(env, nat->conn, -1,
+                                   get_adapter_path(env, object),
+                                   DBUS_ADAPTER_IFACE, "CancelDeviceCreation",
+                                   DBUS_TYPE_STRING, &c_address,
+                                   DBUS_TYPE_INVALID);
         env->ReleaseStringUTFChars(address, c_address);
-        return ret ? JNI_TRUE : JNI_FALSE;
+        if (!reply) {
+            if (dbus_error_is_set(&err)) {
+                LOG_AND_FREE_DBUS_ERROR(&err);
+            } else
+                LOGE("DBus reply is NULL in function %s", __FUNCTION__);
+            return JNI_FALSE;
+        } else {
+            result = JNI_TRUE;
+        }
+        dbus_message_unref(reply);
     }
 #endif
     return JNI_FALSE;
 }
 
+static jboolean removeDeviceNative(JNIEnv *env, jobject object, jstring object_path) {
+    LOGV(__FUNCTION__);
+    jboolean result = JNI_FALSE;
+#ifdef HAVE_BLUETOOTH
+    native_data_t *nat = get_native_data(env, object);
+    if (nat) {
+        const char *c_object_path = env->GetStringUTFChars(object_path, NULL);
+        DBusError err;
+        dbus_error_init(&err);
+        DBusMessage *reply =
+            dbus_func_args_error(env, nat->conn, &err,
+                                 get_adapter_path(env, object),
+                                 DBUS_ADAPTER_IFACE, "RemoveDevice",
+                                 DBUS_TYPE_OBJECT_PATH, &c_object_path,
+                                 DBUS_TYPE_INVALID);
+        if (!reply) {
+            if (dbus_error_is_set(&err)) {
+                LOG_AND_FREE_DBUS_ERROR(&err);
+            } else
+                LOGE("DBus reply is NULL in function %s", __FUNCTION__);
+            result = JNI_FALSE;
+        } else {
+            result = JNI_TRUE;
+        }
+        env->ReleaseStringUTFChars(object_path, c_object_path);
+        if (reply) dbus_message_unref(reply);
+    }
+#endif
+    return result;
+}
+
 static jint enableNative(JNIEnv *env, jobject object) {
 #ifdef HAVE_BLUETOOTH
     LOGV(__FUNCTION__);
@@ -917,6 +437,65 @@
     return -1;
 }
 
+static jboolean setPairingConfirmationNative(JNIEnv *env, jobject object,
+                                             jstring address, bool confirm,
+                                             int nativeData) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+    native_data_t *nat = get_native_data(env, object);
+    if (nat) {
+        DBusMessage *msg = (DBusMessage *)nativeData;
+        DBusMessage *reply;
+        if (confirm) {
+            reply = dbus_message_new_method_return(msg);
+        } else {
+            reply = dbus_message_new_error(msg,
+                "org.bluez.Error.Rejected", "User rejected confirmation");
+        }
+
+        if (!reply) {
+            LOGE("%s: Cannot create message reply to RequestConfirmation to "
+                 "D-Bus\n", __FUNCTION__);
+            dbus_message_unref(msg);
+            return JNI_FALSE;
+        }
+
+        dbus_connection_send(nat->conn, reply, NULL);
+        dbus_message_unref(msg);
+        dbus_message_unref(reply);
+        return JNI_TRUE;
+    }
+#endif
+    return JNI_FALSE;
+}
+
+static jboolean setPasskeyNative(JNIEnv *env, jobject object, jstring address,
+                         int passkey, int nativeData) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+    native_data_t *nat = get_native_data(env, object);
+    if (nat) {
+        DBusMessage *msg = (DBusMessage *)nativeData;
+        DBusMessage *reply = dbus_message_new_method_return(msg);
+        if (!reply) {
+            LOGE("%s: Cannot create message reply to return Passkey code to "
+                 "D-Bus\n", __FUNCTION__);
+            dbus_message_unref(msg);
+            return JNI_FALSE;
+        }
+
+        dbus_message_append_args(reply, DBUS_TYPE_UINT32, (uint32_t *)&passkey,
+                                 DBUS_TYPE_INVALID);
+
+        dbus_connection_send(nat->conn, reply, NULL);
+        dbus_message_unref(msg);
+        dbus_message_unref(reply);
+        return JNI_TRUE;
+    }
+#endif
+    return JNI_FALSE;
+}
+
 static jboolean setPinNative(JNIEnv *env, jobject object, jstring address,
                          jstring pin, int nativeData) {
 #ifdef HAVE_BLUETOOTH
@@ -947,17 +526,17 @@
     return JNI_FALSE;
 }
 
-static jboolean cancelPinNative(JNIEnv *env, jobject object, jstring address,
-                            int nativeData) {
+static jboolean cancelPairingUserInputNative(JNIEnv *env, jobject object,
+                                            jstring address, int nativeData) {
 #ifdef HAVE_BLUETOOTH
     LOGV(__FUNCTION__);
     native_data_t *nat = get_native_data(env, object);
     if (nat) {
         DBusMessage *msg = (DBusMessage *)nativeData;
         DBusMessage *reply = dbus_message_new_error(msg,
-                "org.bluez.Error.Canceled", "PIN Entry was canceled");
+                "org.bluez.Error.Canceled", "Pairing User Input was canceled");
         if (!reply) {
-            LOGE("%s: Cannot create message reply to return PIN cancel to "
+            LOGE("%s: Cannot create message reply to return cancelUserInput to"
                  "D-BUS\n", __FUNCTION__);
             dbus_message_unref(msg);
             return JNI_FALSE;
@@ -972,10 +551,153 @@
     return JNI_FALSE;
 }
 
+static jobjectArray getDevicePropertiesNative(JNIEnv *env, jobject object,
+                                                    jstring path)
+{
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+    native_data_t *nat = get_native_data(env, object);
+    if (nat) {
+        DBusMessage *msg, *reply;
+        DBusError err;
+        dbus_error_init(&err);
+
+        const char *c_path = env->GetStringUTFChars(path, NULL);
+        reply = dbus_func_args_timeout(env,
+                                   nat->conn, -1, c_path,
+                                   DBUS_DEVICE_IFACE, "GetProperties",
+                                   DBUS_TYPE_INVALID);
+        env->ReleaseStringUTFChars(path, c_path);
+
+        if (!reply) {
+            if (dbus_error_is_set(&err)) {
+                LOG_AND_FREE_DBUS_ERROR(&err);
+            } else
+                LOGE("DBus reply is NULL in function %s", __FUNCTION__);
+            return NULL;
+        }
+        DBusMessageIter iter;
+        jobjectArray str_array = NULL;
+        if (dbus_message_iter_init(reply, &iter))
+           str_array =  parse_remote_device_properties(env, &iter);
+        dbus_message_unref(reply);
+        return str_array;
+    }
+#endif
+    return NULL;
+}
+
+static jobjectArray getAdapterPropertiesNative(JNIEnv *env, jobject object) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+    native_data_t *nat = get_native_data(env, object);
+    if (nat) {
+        DBusMessage *msg, *reply;
+        DBusError err;
+        dbus_error_init(&err);
+
+        reply = dbus_func_args_timeout(env,
+                                   nat->conn, -1, get_adapter_path(env, object),
+                                   DBUS_ADAPTER_IFACE, "GetProperties",
+                                   DBUS_TYPE_INVALID);
+        if (!reply) {
+            if (dbus_error_is_set(&err)) {
+                LOG_AND_FREE_DBUS_ERROR(&err);
+            } else
+                LOGE("DBus reply is NULL in function %s", __FUNCTION__);
+            return NULL;
+        }
+        DBusMessageIter iter;
+        jobjectArray str_array = NULL;
+        if (dbus_message_iter_init(reply, &iter))
+            str_array = parse_adapter_properties(env, &iter);
+        dbus_message_unref(reply);
+        return str_array;
+    }
+#endif
+    return NULL;
+}
+
+static jboolean setAdapterPropertyNative(JNIEnv *env, jobject object, jstring key,
+                                         void *value, jint type) {
+#ifdef HAVE_BLUETOOTH
+    LOGV(__FUNCTION__);
+    native_data_t *nat = get_native_data(env, object);
+    if (nat) {
+        DBusMessage *reply, *msg;
+        DBusMessageIter iter;
+        DBusError err;
+        const char *c_key = env->GetStringUTFChars(key, NULL);
+        dbus_error_init(&err);
+
+        msg = dbus_message_new_method_call(BLUEZ_DBUS_BASE_IFC,
+                                           get_adapter_path(env, object),
+                                           DBUS_ADAPTER_IFACE, "SetProperty");
+        if (!msg) {
+            LOGE("%s: Can't allocate new method call for GetProperties!",
+                  __FUNCTION__);
+            return JNI_FALSE;
+        }
+
+        dbus_message_append_args(msg, DBUS_TYPE_STRING, &c_key, DBUS_TYPE_INVALID);
+        dbus_message_iter_init_append(msg, &iter);
+        append_variant(&iter, type, value);
+
+        reply = dbus_connection_send_with_reply_and_block(nat->conn, msg, -1, &err);
+        dbus_message_unref(msg);
+
+        env->ReleaseStringUTFChars(key, c_key);
+
+        if (!reply) {
+            if (dbus_error_is_set(&err)) {
+                LOG_AND_FREE_DBUS_ERROR(&err);
+            } else
+                LOGE("DBus reply is NULL in function %s", __FUNCTION__);
+            return JNI_FALSE;
+        }
+        return JNI_TRUE;
+    }
+#endif
+    return JNI_FALSE;
+}
+
+static jboolean setAdapterPropertyStringNative(JNIEnv *env, jobject object, jstring key,
+                                               jstring value) {
+#ifdef HAVE_BLUETOOTH
+    const char *c_value = env->GetStringUTFChars(value, NULL);
+    jboolean ret =  setAdapterPropertyNative(env, object, key, (void *)&c_value, DBUS_TYPE_STRING);
+    env->ReleaseStringUTFChars(value, (char *)c_value);
+    return ret;
+#else
+    return JNI_FALSE;
+#endif
+}
+
+static jboolean setAdapterPropertyIntegerNative(JNIEnv *env, jobject object, jstring key,
+                                               jint value) {
+#ifdef HAVE_BLUETOOTH
+    return setAdapterPropertyNative(env, object, key, (void *)&value, DBUS_TYPE_UINT32);
+#else
+    return JNI_FALSE;
+#endif
+}
+
+static jboolean setAdapterPropertyBooleanNative(JNIEnv *env, jobject object, jstring key,
+                                               jint value) {
+#ifdef HAVE_BLUETOOTH
+    return setAdapterPropertyNative(env, object, key, (void *)&value, DBUS_TYPE_BOOLEAN);
+#else
+    return JNI_FALSE;
+#endif
+}
+
+
 static JNINativeMethod sMethods[] = {
      /* name, signature, funcPtr */
     {"classInitNative", "()V", (void*)classInitNative},
     {"initializeNativeDataNative", "()V", (void *)initializeNativeDataNative},
+    {"setupNativeDataNative", "()Z", (void *)setupNativeDataNative},
+    {"tearDownNativeDataNative", "()Z", (void *)tearDownNativeDataNative},
     {"cleanupNativeDataNative", "()V", (void *)cleanupNativeDataNative},
     {"getAdapterPathNative", "()Ljava/lang/String;", (void*)getAdapterPathNative},
 
@@ -983,48 +705,31 @@
     {"enableNative", "()I", (void *)enableNative},
     {"disableNative", "()I", (void *)disableNative},
 
-    {"getAddressNative", "()Ljava/lang/String;", (void *)getAddressNative},
-    {"getNameNative", "()Ljava/lang/String;", (void*)getNameNative},
-    {"setNameNative", "(Ljava/lang/String;)Z", (void *)setNameNative},
-    {"getVersionNative", "()Ljava/lang/String;", (void *)getVersionNative},
-    {"getRevisionNative", "()Ljava/lang/String;", (void *)getRevisionNative},
-    {"getManufacturerNative", "()Ljava/lang/String;", (void *)getManufacturerNative},
-    {"getCompanyNative", "()Ljava/lang/String;", (void *)getCompanyNative},
+    {"getAdapterPropertiesNative", "()[Ljava/lang/Object;", (void *)getAdapterPropertiesNative},
+    {"getDevicePropertiesNative", "(Ljava/lang/String;)[Ljava/lang/Object;",
+      (void *)getDevicePropertiesNative},
+    {"setAdapterPropertyStringNative", "(Ljava/lang/String;Ljava/lang/String;)Z",
+      (void *)setAdapterPropertyStringNative},
+    {"setAdapterPropertyBooleanNative", "(Ljava/lang/String;I)Z",
+      (void *)setAdapterPropertyBooleanNative},
+    {"setAdapterPropertyIntegerNative", "(Ljava/lang/String;I)Z",
+      (void *)setAdapterPropertyIntegerNative},
 
-    {"getModeNative", "()Ljava/lang/String;", (void *)getModeNative},
-    {"setModeNative", "(Ljava/lang/String;)Z", (void *)setModeNative},
+    {"startDiscoveryNative", "()Z", (void*)startDiscoveryNative},
+    {"stopDiscoveryNative", "()Z", (void *)stopDiscoveryNative},
 
-    {"getDiscoverableTimeoutNative", "()I", (void *)getDiscoverableTimeoutNative},
-    {"setDiscoverableTimeoutNative", "(I)Z", (void *)setDiscoverableTimeoutNative},
+    {"createPairedDeviceNative", "(Ljava/lang/String;I)Z", (void *)createPairedDeviceNative},
+    {"cancelDeviceCreationNative", "(Ljava/lang/String;)Z", (void *)cancelDeviceCreationNative},
+    {"removeDeviceNative", "(Ljava/lang/String;)Z", (void *)removeDeviceNative},
+    {"getDeviceServiceChannelNative", "(Ljava/lang/String;Ljava/lang/String;I)I",
+      (void *)getDeviceServiceChannelNative},
 
-    {"startDiscoveryNative", "(Z)Z", (void*)startDiscoveryNative},
-    {"cancelDiscoveryNative", "()Z", (void *)cancelDiscoveryNative},
-    {"startPeriodicDiscoveryNative", "()Z", (void *)startPeriodicDiscoveryNative},
-    {"stopPeriodicDiscoveryNative", "()Z", (void *)stopPeriodicDiscoveryNative},
-    {"isPeriodicDiscoveryNative", "()Z", (void *)isPeriodicDiscoveryNative},
-    {"listRemoteDevicesNative", "()[Ljava/lang/String;", (void *)listRemoteDevicesNative},
-
-    {"listConnectionsNative", "()[Ljava/lang/String;", (void *)listConnectionsNative},
-    {"isConnectedNative", "(Ljava/lang/String;)Z", (void *)isConnectedNative},
-    {"disconnectRemoteDeviceNative", "(Ljava/lang/String;)Z", (void *)disconnectRemoteDeviceNative},
-
-    {"createBondingNative", "(Ljava/lang/String;I)Z", (void *)createBondingNative},
-    {"cancelBondingProcessNative", "(Ljava/lang/String;)Z", (void *)cancelBondingProcessNative},
-    {"listBondingsNative", "()[Ljava/lang/String;", (void *)listBondingsNative},
-    {"removeBondingNative", "(Ljava/lang/String;)Z", (void *)removeBondingNative},
-
-    {"getRemoteNameNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteNameNative},
-    {"getRemoteVersionNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteVersionNative},
-    {"getRemoteRevisionNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteRevisionNative},
-    {"getRemoteClassNative", "(Ljava/lang/String;)I", (void *)getRemoteClassNative},
-    {"getRemoteManufacturerNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteManufacturerNative},
-    {"getRemoteCompanyNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteCompanyNative},
-    {"getRemoteServiceChannelNative", "(Ljava/lang/String;S)Z", (void *)getRemoteServiceChannelNative},
-    {"getRemoteFeaturesNative", "(Ljava/lang/String;)[B", (void *)getRemoteFeaturesNative},
-    {"lastSeenNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)lastSeenNative},
-    {"lastUsedNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)lastUsedNative},
+    {"setPairingConfirmationNative", "(Ljava/lang/String;ZI)Z",
+            (void *)setPairingConfirmationNative},
+    {"setPasskeyNative", "(Ljava/lang/String;II)Z", (void *)setPasskeyNative},
     {"setPinNative", "(Ljava/lang/String;Ljava/lang/String;I)Z", (void *)setPinNative},
-    {"cancelPinNative", "(Ljava/lang/String;I)Z", (void *)cancelPinNative},
+    {"cancelPairingUserInputNative", "(Ljava/lang/String;I)Z",
+            (void *)cancelPairingUserInputNative},
 };
 
 int register_android_server_BluetoothDeviceService(JNIEnv *env) {
diff --git a/core/jni/android_server_BluetoothEventLoop.cpp b/core/jni/android_server_BluetoothEventLoop.cpp
index ad24136..4a13e80 100644
--- a/core/jni/android_server_BluetoothEventLoop.cpp
+++ b/core/jni/android_server_BluetoothEventLoop.cpp
@@ -39,30 +39,21 @@
 #ifdef HAVE_BLUETOOTH
 static jfieldID field_mNativeData;
 
-static jmethodID method_onModeChanged;
-static jmethodID method_onNameChanged;
-static jmethodID method_onDiscoveryStarted;
-static jmethodID method_onDiscoveryCompleted;
-static jmethodID method_onRemoteDeviceFound;
-static jmethodID method_onRemoteDeviceDisappeared;
-static jmethodID method_onRemoteClassUpdated;
-static jmethodID method_onRemoteNameUpdated;
-static jmethodID method_onRemoteNameFailed;
-static jmethodID method_onRemoteDeviceConnected;
-static jmethodID method_onRemoteDeviceDisconnectRequested;
-static jmethodID method_onRemoteDeviceDisconnected;
-static jmethodID method_onBondingCreated;
-static jmethodID method_onBondingRemoved;
+static jmethodID method_onPropertyChanged;
+static jmethodID method_onDevicePropertyChanged;
+static jmethodID method_onDeviceFound;
+static jmethodID method_onDeviceDisappeared;
+static jmethodID method_onDeviceCreated;
+static jmethodID method_onDeviceRemoved;
 
-static jmethodID method_onCreateBondingResult;
-static jmethodID method_onGetRemoteServiceChannelResult;
+static jmethodID method_onCreatePairedDeviceResult;
+static jmethodID method_onGetDeviceServiceChannelResult;
 
-static jmethodID method_onPasskeyAgentRequest;
-static jmethodID method_onPasskeyAgentCancel;
-static jmethodID method_onAuthAgentAuthorize;
-static jmethodID method_onAuthAgentCancel;
-
-static jmethodID method_onRestartRequired;
+static jmethodID method_onRequestPinCode;
+static jmethodID method_onRequestPasskey;
+static jmethodID method_onRequestConfirmation;
+static jmethodID method_onAgentAuthorize;
+static jmethodID method_onAgentCancel;
 
 typedef event_loop_native_data_t native_data_t;
 
@@ -80,30 +71,30 @@
     LOGV(__FUNCTION__);
 
 #ifdef HAVE_BLUETOOTH
-    method_onModeChanged = env->GetMethodID(clazz, "onModeChanged", "(Ljava/lang/String;)V");
-    method_onNameChanged = env->GetMethodID(clazz, "onNameChanged", "(Ljava/lang/String;)V");
-    method_onDiscoveryStarted = env->GetMethodID(clazz, "onDiscoveryStarted", "()V");
-    method_onDiscoveryCompleted = env->GetMethodID(clazz, "onDiscoveryCompleted", "()V");
-    method_onRemoteDeviceFound = env->GetMethodID(clazz, "onRemoteDeviceFound", "(Ljava/lang/String;IS)V");
-    method_onRemoteDeviceDisappeared = env->GetMethodID(clazz, "onRemoteDeviceDisappeared", "(Ljava/lang/String;)V");
-    method_onRemoteClassUpdated = env->GetMethodID(clazz, "onRemoteClassUpdated", "(Ljava/lang/String;I)V");
-    method_onRemoteNameUpdated = env->GetMethodID(clazz, "onRemoteNameUpdated", "(Ljava/lang/String;Ljava/lang/String;)V");
-    method_onRemoteNameFailed = env->GetMethodID(clazz, "onRemoteNameFailed", "(Ljava/lang/String;)V");
-    method_onRemoteDeviceConnected = env->GetMethodID(clazz, "onRemoteDeviceConnected", "(Ljava/lang/String;)V");
-    method_onRemoteDeviceDisconnectRequested = env->GetMethodID(clazz, "onRemoteDeviceDisconnectRequested", "(Ljava/lang/String;)V");
-    method_onRemoteDeviceDisconnected = env->GetMethodID(clazz, "onRemoteDeviceDisconnected", "(Ljava/lang/String;)V");
-    method_onBondingCreated = env->GetMethodID(clazz, "onBondingCreated", "(Ljava/lang/String;)V");
-    method_onBondingRemoved = env->GetMethodID(clazz, "onBondingRemoved", "(Ljava/lang/String;)V");
+    method_onPropertyChanged = env->GetMethodID(clazz, "onPropertyChanged",
+                                                "([Ljava/lang/String;)V");
+    method_onDevicePropertyChanged = env->GetMethodID(clazz,
+                                                      "onDevicePropertyChanged",
+                                                      "(Ljava/lang/String;[Ljava/lang/String;)V");
+    method_onDeviceFound = env->GetMethodID(clazz, "onDeviceFound",
+                                            "(Ljava/lang/String;[Ljava/lang/String;)V");
+    method_onDeviceDisappeared = env->GetMethodID(clazz, "onDeviceDisappeared",
+                                                  "(Ljava/lang/String;)V");
+    method_onDeviceCreated = env->GetMethodID(clazz, "onDeviceCreated", "(Ljava/lang/String;)V");
+    method_onDeviceRemoved = env->GetMethodID(clazz, "onDeviceRemoved", "(Ljava/lang/String;)V");
 
-    method_onCreateBondingResult = env->GetMethodID(clazz, "onCreateBondingResult", "(Ljava/lang/String;I)V");
+    method_onCreatePairedDeviceResult = env->GetMethodID(clazz, "onCreatePairedDeviceResult",
+                                                         "(Ljava/lang/String;I)V");
 
-    method_onPasskeyAgentRequest = env->GetMethodID(clazz, "onPasskeyAgentRequest", "(Ljava/lang/String;I)V");
-    method_onPasskeyAgentCancel = env->GetMethodID(clazz, "onPasskeyAgentCancel", "(Ljava/lang/String;)V");
-    method_onAuthAgentAuthorize = env->GetMethodID(clazz, "onAuthAgentAuthorize", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z");
-    method_onAuthAgentCancel = env->GetMethodID(clazz, "onAuthAgentCancel", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
-    method_onGetRemoteServiceChannelResult = env->GetMethodID(clazz, "onGetRemoteServiceChannelResult", "(Ljava/lang/String;I)V");
-
-    method_onRestartRequired = env->GetMethodID(clazz, "onRestartRequired", "()V");
+    method_onAgentAuthorize = env->GetMethodID(clazz, "onAgentAuthorize",
+                                               "(Ljava/lang/String;Ljava/lang/String;)Z");
+    method_onAgentCancel = env->GetMethodID(clazz, "onAgentCancel", "()V");
+    method_onRequestPinCode = env->GetMethodID(clazz, "onRequestPinCode",
+                                               "(Ljava/lang/String;I)V");
+    method_onRequestPasskey = env->GetMethodID(clazz, "onRequestPasskey",
+                                               "(Ljava/lang/String;I)V");
+    method_onRequestConfirmation = env->GetMethodID(clazz, "onRequestConfirmation",
+                                               "(Ljava/lang/String;II)V");
 
     field_mNativeData = env->GetFieldID(clazz, "mNativeData", "I");
 #endif
@@ -154,9 +145,11 @@
 #ifdef HAVE_BLUETOOTH
 static DBusHandlerResult event_filter(DBusConnection *conn, DBusMessage *msg,
                                       void *data);
-static DBusHandlerResult agent_event_filter(DBusConnection *conn,
-                                            DBusMessage *msg,
-                                            void *data);
+DBusHandlerResult agent_event_filter(DBusConnection *conn,
+                                     DBusMessage *msg,
+                                     void *data);
+static int register_agent(native_data_t *nat,
+                          const char *agent_path, const char *capabilities);
 
 static const DBusObjectPathVTable agent_vtable = {
     NULL, agent_event_filter, NULL, NULL, NULL, NULL
@@ -178,11 +171,12 @@
 
 static jboolean setUpEventLoop(native_data_t *nat) {
     LOGV(__FUNCTION__);
-    dbus_threads_init_default();
-    DBusError err;
-    dbus_error_init(&err);
 
     if (nat != NULL && nat->conn != NULL) {
+        dbus_threads_init_default();
+        DBusError err;
+        dbus_error_init(&err);
+
         // Add a filter for all incoming messages
         if (!dbus_connection_add_filter(nat->conn, event_filter, nat, NULL)){
             return JNI_FALSE;
@@ -204,108 +198,143 @@
             return JNI_FALSE;
         }
         dbus_bus_add_match(nat->conn,
-                "type='signal',interface='org.bluez.audio.Manager'",
+                "type='signal',interface='"BLUEZ_DBUS_BASE_IFC".Device'",
                 &err);
         if (dbus_error_is_set(&err)) {
             LOG_AND_FREE_DBUS_ERROR(&err);
             return JNI_FALSE;
         }
         dbus_bus_add_match(nat->conn,
-                "type='signal',interface='org.bluez.audio.Device'",
-                &err);
-        if (dbus_error_is_set(&err)) {
-            LOG_AND_FREE_DBUS_ERROR(&err);
-            return JNI_FALSE;
-        }
-        dbus_bus_add_match(nat->conn,
-                "type='signal',interface='org.bluez.audio.Sink'",
+                "type='signal',interface='org.bluez.AudioSink'",
                 &err);
         if (dbus_error_is_set(&err)) {
             LOG_AND_FREE_DBUS_ERROR(&err);
             return JNI_FALSE;
         }
 
-        // Add an object handler for passkey agent method calls
-        const char *path = "/android/bluetooth/Agent";
-        if (!dbus_connection_register_object_path(nat->conn, path,
-                &agent_vtable, nat)) {
-            LOGE("%s: Can't register object path %s for agent!",
-                 __FUNCTION__, path);
+        const char *agent_path = "/android/bluetooth/agent";
+        const char *capabilities = "DisplayYesNo";
+        if (register_agent(nat, agent_path, capabilities) < 0) {
+            dbus_connection_unregister_object_path (nat->conn, agent_path);
             return JNI_FALSE;
         }
-
-        // RegisterDefaultPasskeyAgent() will fail until hcid is up, so keep
-        // trying for 10 seconds.
-        int attempt;
-        for (attempt = 0; attempt < 1000; attempt++) {
-            DBusMessage *reply = dbus_func_args_error(NULL, nat->conn, &err,
-                    BLUEZ_DBUS_BASE_PATH,
-                    "org.bluez.Security", "RegisterDefaultPasskeyAgent",
-                    DBUS_TYPE_STRING, &path,
-                    DBUS_TYPE_INVALID);
-            if (reply) {
-                // Success
-                dbus_message_unref(reply);
-                LOGV("Registered agent on attempt %d of 1000\n", attempt);
-                break;
-            } else if (dbus_error_has_name(&err,
-                    "org.freedesktop.DBus.Error.ServiceUnknown")) {
-                // hcid is still down, retry
-                dbus_error_free(&err);
-                usleep(10000);  // 10 ms
-            } else {
-                // Some other error we weren't expecting
-                LOG_AND_FREE_DBUS_ERROR(&err);
-                return JNI_FALSE;
-            }
-        }
-        if (attempt == 1000) {
-            LOGE("Time-out trying to call RegisterDefaultPasskeyAgent(), "
-                 "is hcid running?");
-            return JNI_FALSE;
-        }
-
-        // Now register the Auth agent
-        DBusMessage *reply = dbus_func_args_error(NULL, nat->conn, &err,
-                BLUEZ_DBUS_BASE_PATH,
-                "org.bluez.Security", "RegisterDefaultAuthorizationAgent",
-                DBUS_TYPE_STRING, &path,
-                DBUS_TYPE_INVALID);
-        if (!reply) {
-            LOG_AND_FREE_DBUS_ERROR(&err);
-            return JNI_FALSE;
-        }
-
-        dbus_message_unref(reply);
         return JNI_TRUE;
     }
-
     return JNI_FALSE;
 }
 
+
+const char * get_adapter_path(DBusConnection *conn) {
+    DBusMessage *msg, *reply;
+    DBusError err;
+    const char *device_path = NULL;
+    msg = dbus_message_new_method_call("org.bluez", "/",
+          "org.bluez.Manager", "DefaultAdapter");
+    if (!msg) {
+        LOGE("%s: Can't allocate new method call for GetProperties!",
+              __FUNCTION__);
+        return NULL;
+    }
+    dbus_message_append_args(msg, DBUS_TYPE_INVALID);
+
+    dbus_error_init(&err);
+    reply = dbus_connection_send_with_reply_and_block(conn, msg, -1, &err);
+    dbus_message_unref(msg);
+
+    if (!reply) {
+        if (dbus_error_is_set(&err)) {
+            LOG_AND_FREE_DBUS_ERROR(&err);
+        }
+        return NULL;
+    }
+    if (!dbus_message_get_args(reply, &err, DBUS_TYPE_OBJECT_PATH,
+                               &device_path, DBUS_TYPE_INVALID)
+                               || !device_path){
+        if (dbus_error_is_set(&err)) {
+            LOG_AND_FREE_DBUS_ERROR(&err);
+        }
+        return NULL;
+    }
+    return device_path;
+}
+
+static int register_agent(native_data_t *nat,
+                          const char * agent_path, const char * capabilities)
+{
+    DBusMessage *msg, *reply;
+    DBusError err;
+
+    if (!dbus_connection_register_object_path(nat->conn, agent_path,
+            &agent_vtable, nat)) {
+        LOGE("%s: Can't register object path %s for agent!",
+              __FUNCTION__, agent_path);
+        return -1;
+    }
+
+    nat->adapter = get_adapter_path(nat->conn);
+    msg = dbus_message_new_method_call("org.bluez", nat->adapter,
+          "org.bluez.Adapter", "RegisterAgent");
+    if (!msg) {
+        LOGE("%s: Can't allocate new method call for agent!",
+              __FUNCTION__);
+        return -1;
+    }
+    dbus_message_append_args(msg, DBUS_TYPE_OBJECT_PATH, &agent_path,
+                             DBUS_TYPE_STRING, &capabilities,
+                             DBUS_TYPE_INVALID);
+
+    dbus_error_init(&err);
+    reply = dbus_connection_send_with_reply_and_block(nat->conn, msg, -1, &err);
+    dbus_message_unref(msg);
+
+    if (!reply) {
+        LOGE("%s: Can't register agent!", __FUNCTION__);
+        if (dbus_error_is_set(&err)) {
+            LOG_AND_FREE_DBUS_ERROR(&err);
+        }
+        return -1;
+    }
+
+    dbus_message_unref(reply);
+    dbus_connection_flush(nat->conn);
+
+    return 0;
+}
+
 static void tearDownEventLoop(native_data_t *nat) {
     LOGV(__FUNCTION__);
     if (nat != NULL && nat->conn != NULL) {
 
+        DBusMessage *msg, *reply;
         DBusError err;
         dbus_error_init(&err);
+        const char * agent_path = "/android/bluetooth/agent";
 
-        const char *path = "/android/bluetooth/Agent";
-        DBusMessage *reply =
-            dbus_func_args(NULL, nat->conn, BLUEZ_DBUS_BASE_PATH,
-                    "org.bluez.Security", "UnregisterDefaultPasskeyAgent",
-                    DBUS_TYPE_STRING, &path,
-                    DBUS_TYPE_INVALID);
-        if (reply) dbus_message_unref(reply);
+        msg = dbus_message_new_method_call("org.bluez",
+                                           nat->adapter,
+                                           "org.bluez.Adapter",
+                                           "UnregisterAgent");
+        if (msg != NULL) {
+            dbus_message_append_args(msg, DBUS_TYPE_OBJECT_PATH, &agent_path,
+                                     DBUS_TYPE_INVALID);
+            reply = dbus_connection_send_with_reply_and_block(nat->conn,
+                                                              msg, -1, &err);
 
-        reply =
-            dbus_func_args(NULL, nat->conn, BLUEZ_DBUS_BASE_PATH,
-                    "org.bluez.Security", "UnregisterDefaultAuthorizationAgent",
-                    DBUS_TYPE_STRING, &path,
-                    DBUS_TYPE_INVALID);
-        if (reply) dbus_message_unref(reply);
+            if (!reply) {
+                if (dbus_error_is_set(&err)) {
+                    LOG_AND_FREE_DBUS_ERROR(&err);
+                    dbus_error_free(&err);
+                }
+            } else {
+                dbus_message_unref(reply);
+            }
+            dbus_message_unref(msg);
+        } else {
+             LOGE("%s: Can't create new method call!", __FUNCTION__);
+        }
 
-        dbus_connection_unregister_object_path(nat->conn, path);
+        dbus_connection_flush(nat->conn);
+        dbus_connection_unregister_object_path(nat->conn, agent_path);
 
         dbus_bus_remove_match(nat->conn,
                 "type='signal',interface='org.bluez.audio.Sink'",
@@ -660,267 +689,129 @@
         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
     }
 
-    LOGV("%s: Received signal %s:%s from %s", __FUNCTION__,
-         dbus_message_get_interface(msg), dbus_message_get_member(msg),
-         dbus_message_get_path(msg));
+    // STOPSHIP: Change to LOGV
+    LOGE("%s: Received signal %s:%s from %s", __FUNCTION__,
+        dbus_message_get_interface(msg), dbus_message_get_member(msg),
+        dbus_message_get_path(msg));
 
     if (dbus_message_is_signal(msg,
                                "org.bluez.Adapter",
-                               "RemoteDeviceFound")) {
+                               "DeviceFound")) {
         char *c_address;
-        int n_class;
-        short n_rssi;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_address,
-                                  DBUS_TYPE_UINT32, &n_class,
-                                  DBUS_TYPE_INT16, &n_rssi,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... address = %s class = %#X rssi = %hd", c_address, n_class,
-                 n_rssi);
+        DBusMessageIter iter;
+        jobjectArray str_array = NULL;
+        if (dbus_message_iter_init(msg, &iter)) {
+            dbus_message_iter_get_basic(&iter, &c_address);
+            if (dbus_message_iter_next(&iter))
+                str_array =
+                    parse_remote_device_properties(env, &iter);
+        }
+        if (str_array != NULL) {
             env->CallVoidMethod(nat->me,
-                                method_onRemoteDeviceFound,
+                                method_onDeviceFound,
                                 env->NewStringUTF(c_address),
-                                (jint)n_class,
-                                (jshort)n_rssi);
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
+                                str_array);
+        } else
+            LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
         return DBUS_HANDLER_RESULT_HANDLED;
     } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "DiscoveryStarted")) {
-        LOGI("DiscoveryStarted signal received");
-        env->CallVoidMethod(nat->me, method_onDiscoveryStarted);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                    "org.bluez.Adapter",
-                                    "DiscoveryCompleted")) {
-        LOGI("DiscoveryCompleted signal received");
-        env->CallVoidMethod(nat->me, method_onDiscoveryCompleted);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "RemoteDeviceDisappeared")) {
+                                     "org.bluez.Adapter",
+                                     "DeviceDisappeared")) {
         char *c_address;
         if (dbus_message_get_args(msg, &err,
                                   DBUS_TYPE_STRING, &c_address,
                                   DBUS_TYPE_INVALID)) {
             LOGV("... address = %s", c_address);
-            env->CallVoidMethod(nat->me, method_onRemoteDeviceDisappeared,
+            env->CallVoidMethod(nat->me, method_onDeviceDisappeared,
                                 env->NewStringUTF(c_address));
         } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
         return DBUS_HANDLER_RESULT_HANDLED;
     } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "RemoteClassUpdated")) {
-        char *c_address;
-        int n_class;
+                                     "org.bluez.Adapter",
+                                     "DeviceCreated")) {
+        char *c_object_path;
         if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_address,
-                                  DBUS_TYPE_UINT32, &n_class,
+                                  DBUS_TYPE_OBJECT_PATH, &c_object_path,
                                   DBUS_TYPE_INVALID)) {
-            LOGV("... address = %s", c_address);
-            env->CallVoidMethod(nat->me, method_onRemoteClassUpdated,
-                                env->NewStringUTF(c_address), (jint)n_class);
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "RemoteNameUpdated")) {
-        char *c_address;
-        char *c_name;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_address,
-                                  DBUS_TYPE_STRING, &c_name,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... address = %s, name = %s", c_address, c_name);
+            LOGV("... address = %s", c_object_path);
             env->CallVoidMethod(nat->me,
-                                method_onRemoteNameUpdated,
-                                env->NewStringUTF(c_address),
-                                env->NewStringUTF(c_name));
+                                method_onDeviceCreated,
+                                env->NewStringUTF(c_object_path));
         } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
         return DBUS_HANDLER_RESULT_HANDLED;
     } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "RemoteNameFailed")) {
-        char *c_address;
+                                     "org.bluez.Adapter",
+                                     "DeviceRemoved")) {
+        char *c_object_path;
         if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_address,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... address = %s", c_address);
-            env->CallVoidMethod(nat->me,
-                                method_onRemoteNameFailed,
-                                env->NewStringUTF(c_address));
+                                 DBUS_TYPE_OBJECT_PATH, &c_object_path,
+                                 DBUS_TYPE_INVALID)) {
+           LOGV("... Object Path = %s", c_object_path);
+           env->CallVoidMethod(nat->me,
+                               method_onDeviceRemoved,
+                               env->NewStringUTF(c_object_path));
         } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "RemoteDeviceConnected")) {
-        char *c_address;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_address,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... address = %s", c_address);
-            env->CallVoidMethod(nat->me,
-                                method_onRemoteDeviceConnected,
-                                env->NewStringUTF(c_address));
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "RemoteDeviceDisconnectRequested")) {
-        char *c_address;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_address,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... address = %s", c_address);
-            env->CallVoidMethod(nat->me,
-                                method_onRemoteDeviceDisconnectRequested,
-                                env->NewStringUTF(c_address));
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "RemoteDeviceDisconnected")) {
-        char *c_address;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_address,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... address = %s", c_address);
-            env->CallVoidMethod(nat->me,
-                                method_onRemoteDeviceDisconnected,
-                                env->NewStringUTF(c_address));
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "BondingCreated")) {
-        char *c_address;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_address,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... address = %s", c_address);
-            env->CallVoidMethod(nat->me,
-                                method_onBondingCreated,
-                                env->NewStringUTF(c_address));
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "BondingRemoved")) {
-        char *c_address;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_address,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... address = %s", c_address);
-            env->CallVoidMethod(nat->me,
-                                method_onBondingRemoved,
-                                env->NewStringUTF(c_address));
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "ModeChanged")) {
-        char *c_mode;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_mode,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... mode = %s", c_mode);
-            env->CallVoidMethod(nat->me,
-                                method_onModeChanged,
-                                env->NewStringUTF(c_mode));
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.bluez.Adapter",
-                                      "NameChanged")) {
-        char *c_name;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_name,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... name = %s", c_name);
-            env->CallVoidMethod(nat->me,
-                                method_onNameChanged,
-                                env->NewStringUTF(c_name));
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_signal(msg,
-                                      "org.freedesktop.DBus",
-                                      "NameOwnerChanged")) {
-        char *c_name;
-        char *c_old_owner;
-        char *c_new_owner;
-        if (dbus_message_get_args(msg, &err,
-                                  DBUS_TYPE_STRING, &c_name,
-                                  DBUS_TYPE_STRING, &c_old_owner,
-                                  DBUS_TYPE_STRING, &c_new_owner,
-                                  DBUS_TYPE_INVALID)) {
-            LOGV("... name = %s", c_name);
-            LOGV("... old_owner = %s", c_old_owner);
-            LOGV("... new_owner = %s", c_new_owner);
-            if (!strcmp(c_name, "org.bluez") && c_new_owner[0] != '\0') {
-                // New owner of org.bluez. This can only happen when hcid
-                // restarts. Need to restart framework BT services to recover.
-                LOGE("Looks like hcid restarted");
-                env->CallVoidMethod(nat->me, method_onRestartRequired);
-            }
-        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    }
 
+        return DBUS_HANDLER_RESULT_HANDLED;
+    } else if (dbus_message_is_signal(msg,
+                                      "org.bluez.Adapter",
+                                      "PropertyChanged")) {
+        jobjectArray str_array = parse_adapter_property_change(env, msg);
+        if (str_array != NULL) {
+            /* Check if bluetoothd has (re)started, if so update the path. */
+            jstring property =(jstring) env->GetObjectArrayElement(str_array, 0);
+            const char *c_property = env->GetStringUTFChars(property, NULL);
+            if (!strncmp(c_property, "Powered", strlen("Powered"))) {
+                jstring value =
+                    (jstring) env->GetObjectArrayElement(str_array, 1);
+                const char *c_value = env->GetStringUTFChars(value, NULL);
+                if (!strncmp(c_value, "true", strlen("true")))
+                    nat->adapter = get_adapter_path(nat->conn);
+                env->ReleaseStringUTFChars(value, c_value);
+            }
+            env->ReleaseStringUTFChars(property, c_property);
+
+            env->CallVoidMethod(nat->me,
+                              method_onPropertyChanged,
+                              str_array);
+        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
+        return DBUS_HANDLER_RESULT_HANDLED;
+    } else if (dbus_message_is_signal(msg,
+                                      "org.bluez.Device",
+                                      "PropertyChanged")) {
+        jobjectArray str_array = parse_remote_device_property_change(env, msg);
+        if (str_array != NULL) {
+            const char *remote_device_path = dbus_message_get_path(msg);
+            env->CallVoidMethod(nat->me,
+                            method_onDevicePropertyChanged,
+                            env->NewStringUTF(remote_device_path),
+                            str_array);
+        } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
+        return DBUS_HANDLER_RESULT_HANDLED;
+
+    }
     return a2dp_event_filter(msg, env);
 }
 
 // Called by dbus during WaitForAndDispatchEventNative()
-static DBusHandlerResult agent_event_filter(DBusConnection *conn,
-                                            DBusMessage *msg, void *data) {
+DBusHandlerResult agent_event_filter(DBusConnection *conn,
+                                     DBusMessage *msg, void *data) {
     native_data_t *nat = (native_data_t *)data;
     JNIEnv *env;
-    nat->vm->GetEnv((void**)&env, nat->envVer);
     if (dbus_message_get_type(msg) != DBUS_MESSAGE_TYPE_METHOD_CALL) {
         LOGV("%s: not interested (not a method call).", __FUNCTION__);
         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
     }
-    LOGV("%s: Received method %s:%s", __FUNCTION__,
+    LOGI("%s: Received method %s:%s", __FUNCTION__,
          dbus_message_get_interface(msg), dbus_message_get_member(msg));
 
+    if (nat == NULL) return DBUS_HANDLER_RESULT_HANDLED;
+
+    nat->vm->GetEnv((void**)&env, nat->envVer);
     if (dbus_message_is_method_call(msg,
-            "org.bluez.PasskeyAgent", "Request")) {
+            "org.bluez.Agent", "Cancel")) {
 
-        const char *adapter;
-        const char *address;
-        if (!dbus_message_get_args(msg, NULL,
-                                   DBUS_TYPE_STRING, &adapter,
-                                   DBUS_TYPE_STRING, &address,
-                                   DBUS_TYPE_INVALID)) {
-            LOGE("%s: Invalid arguments for Request() method", __FUNCTION__);
-            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-        }
-
-        LOGV("... address = %s", address);
-
-        dbus_message_ref(msg);  // increment refcount because we pass to java
-
-        env->CallVoidMethod(nat->me, method_onPasskeyAgentRequest,
-                            env->NewStringUTF(address), (int)msg);
-
-        return DBUS_HANDLER_RESULT_HANDLED;
-
-    } else if (dbus_message_is_method_call(msg,
-            "org.bluez.PasskeyAgent", "Cancel")) {
-
-        const char *adapter;
-        const char *address;
-        if (!dbus_message_get_args(msg, NULL,
-                                   DBUS_TYPE_STRING, &adapter,
-                                   DBUS_TYPE_STRING, &address,
-                                   DBUS_TYPE_INVALID)) {
-            LOGE("%s: Invalid arguments for Cancel() method", __FUNCTION__);
-            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-        }
-
-        LOGV("... address = %s", address);
-
-        env->CallVoidMethod(nat->me, method_onPasskeyAgentCancel,
-                            env->NewStringUTF(address));
+        env->CallVoidMethod(nat->me, method_onAgentCancel);
 
         // reply
         DBusMessage *reply = dbus_message_new_method_return(msg);
@@ -933,41 +824,23 @@
         return DBUS_HANDLER_RESULT_HANDLED;
 
     } else if (dbus_message_is_method_call(msg,
-            "org.bluez.PasskeyAgent", "Release")) {
-        LOGW("We are no longer the passkey agent!");
-
-        // reply
-        DBusMessage *reply = dbus_message_new_method_return(msg);
-        if (!reply) {
-            LOGE("%s: Cannot create message reply\n", __FUNCTION__);
-            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-        }
-        dbus_connection_send(nat->conn, reply, NULL);
-        dbus_message_unref(reply);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    } else if (dbus_message_is_method_call(msg,
-            "org.bluez.AuthorizationAgent", "Authorize")) {
-        const char *adapter;
-        const char *address;
-        const char *service;
+            "org.bluez.Agent", "Authorize")) {
+        char *object_path;
         const char *uuid;
         if (!dbus_message_get_args(msg, NULL,
-                                   DBUS_TYPE_STRING, &adapter,
-                                   DBUS_TYPE_STRING, &address,
-                                   DBUS_TYPE_STRING, &service,
+                                   DBUS_TYPE_OBJECT_PATH, &object_path,
                                    DBUS_TYPE_STRING, &uuid,
                                    DBUS_TYPE_INVALID)) {
             LOGE("%s: Invalid arguments for Authorize() method", __FUNCTION__);
             return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
         }
 
-        LOGV("... address = %s", address);
-        LOGV("... service = %s", service);
+        LOGV("... object_path = %s", object_path);
         LOGV("... uuid = %s", uuid);
 
-        bool auth_granted = env->CallBooleanMethod(nat->me,
-                method_onAuthAgentAuthorize, env->NewStringUTF(address),
-                env->NewStringUTF(service), env->NewStringUTF(uuid));
+        bool auth_granted =
+            env->CallBooleanMethod(nat->me, method_onAgentAuthorize,
+                env->NewStringUTF(object_path), env->NewStringUTF(uuid));
 
         // reply
         if (auth_granted) {
@@ -990,43 +863,54 @@
         }
         return DBUS_HANDLER_RESULT_HANDLED;
     } else if (dbus_message_is_method_call(msg,
-            "org.bluez.AuthorizationAgent", "Cancel")) {
-        const char *adapter;
-        const char *address;
-        const char *service;
-        const char *uuid;
+            "org.bluez.Agent", "RequestPinCode")) {
+        char *object_path;
         if (!dbus_message_get_args(msg, NULL,
-                                   DBUS_TYPE_STRING, &adapter,
-                                   DBUS_TYPE_STRING, &address,
-                                   DBUS_TYPE_STRING, &service,
-                                   DBUS_TYPE_STRING, &uuid,
+                                   DBUS_TYPE_OBJECT_PATH, &object_path,
                                    DBUS_TYPE_INVALID)) {
-            LOGE("%s: Invalid arguments for Cancel() method", __FUNCTION__);
+            LOGE("%s: Invalid arguments for RequestPinCode() method", __FUNCTION__);
             return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
         }
 
-        LOGV("... address = %s", address);
-        LOGV("... service = %s", service);
-        LOGV("... uuid = %s", uuid);
-
-        env->CallVoidMethod(nat->me,
-                method_onAuthAgentCancel, env->NewStringUTF(address),
-                env->NewStringUTF(service), env->NewStringUTF(uuid));
-
-        // reply
-        DBusMessage *reply = dbus_message_new_method_return(msg);
-        if (!reply) {
-            LOGE("%s: Cannot create message reply\n", __FUNCTION__);
-            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-        }
-        dbus_connection_send(nat->conn, reply, NULL);
-        dbus_message_unref(reply);
+        dbus_message_ref(msg);  // increment refcount because we pass to java
+        env->CallVoidMethod(nat->me, method_onRequestPinCode,
+                                       env->NewStringUTF(object_path),
+                                       int(msg));
         return DBUS_HANDLER_RESULT_HANDLED;
-
     } else if (dbus_message_is_method_call(msg,
-            "org.bluez.AuthorizationAgent", "Release")) {
-        LOGW("We are no longer the auth agent!");
+            "org.bluez.Agent", "RequestPasskey")) {
+        char *object_path;
+        if (!dbus_message_get_args(msg, NULL,
+                                   DBUS_TYPE_OBJECT_PATH, &object_path,
+                                   DBUS_TYPE_INVALID)) {
+            LOGE("%s: Invalid arguments for RequestPasskey() method", __FUNCTION__);
+            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+        }
 
+        dbus_message_ref(msg);  // increment refcount because we pass to java
+        env->CallVoidMethod(nat->me, method_onRequestPasskey,
+                                       env->NewStringUTF(object_path),
+                                       int(msg));
+    } else if (dbus_message_is_method_call(msg,
+            "org.bluez.Agent", "RequestConfirmation")) {
+        char *object_path;
+        uint32_t passkey;
+        if (!dbus_message_get_args(msg, NULL,
+                                   DBUS_TYPE_OBJECT_PATH, &object_path,
+                                   DBUS_TYPE_UINT32, &passkey,
+                                   DBUS_TYPE_INVALID)) {
+            LOGE("%s: Invalid arguments for RequestConfirmation() method", __FUNCTION__);
+            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+        }
+
+        dbus_message_ref(msg);  // increment refcount because we pass to java
+        env->CallVoidMethod(nat->me, method_onRequestConfirmation,
+                                       env->NewStringUTF(object_path),
+                                       passkey,
+                                       int(msg));
+        return DBUS_HANDLER_RESULT_HANDLED;
+    } else if (dbus_message_is_method_call(msg,
+                  "org.bluez.Agent", "Release")) {
         // reply
         DBusMessage *reply = dbus_message_new_method_return(msg);
         if (!reply) {
@@ -1037,7 +921,7 @@
         dbus_message_unref(reply);
         return DBUS_HANDLER_RESULT_HANDLED;
     } else {
-        LOGV("... ignored");
+        LOGV("%s:%s is ignored", dbus_message_get_interface(msg), dbus_message_get_member(msg));
     }
 
     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
@@ -1055,7 +939,7 @@
 #define BOND_RESULT_REMOTE_DEVICE_DOWN 4
 #define BOND_RESULT_DISCOVERY_IN_PROGRESS 5
 
-void onCreateBondingResult(DBusMessage *msg, void *user, void *n) {
+void onCreatePairedDeviceResult(DBusMessage *msg, void *user, void *n) {
     LOGV(__FUNCTION__);
 
     native_data_t *nat = (native_data_t *)n;
@@ -1106,7 +990,7 @@
     }
 
     env->CallVoidMethod(nat->me,
-                        method_onCreateBondingResult,
+                        method_onCreatePairedDeviceResult,
                         env->NewStringUTF(address),
                         result);
 done:
@@ -1114,7 +998,7 @@
     free(user);
 }
 
-void onGetRemoteServiceChannelResult(DBusMessage *msg, void *user, void *n) {
+void onGetDeviceServiceChannelResult(DBusMessage *msg, void *user, void *n) {
     LOGV(__FUNCTION__);
 
     const char *address = (const char *) user;
@@ -1133,14 +1017,13 @@
         !dbus_message_get_args(msg, &err,
                                DBUS_TYPE_INT32, &channel,
                                DBUS_TYPE_INVALID)) {
-        /* if (!strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.AuthenticationFailed")) */
         LOGE("%s: D-Bus error: %s (%s)\n", __FUNCTION__, err.name, err.message);
         dbus_error_free(&err);
     }
 
 done:
     env->CallVoidMethod(nat->me,
-                        method_onGetRemoteServiceChannelResult,
+                        method_onGetDeviceServiceChannelResult,
                         env->NewStringUTF(address),
                         channel);
     free(user);
diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp
index 7325432..f0885fd 100644
--- a/core/jni/android_util_Binder.cpp
+++ b/core/jni/android_util_Binder.cpp
@@ -25,12 +25,12 @@
 #include <stdio.h>
 
 #include <utils/Atomic.h>
-#include <utils/IInterface.h>
-#include <utils/IPCThreadState.h>
+#include <binder/IInterface.h>
+#include <binder/IPCThreadState.h>
 #include <utils/Log.h>
-#include <utils/Parcel.h>
-#include <utils/ProcessState.h>
-#include <utils/IServiceManager.h>
+#include <binder/Parcel.h>
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
 
 #include <android_runtime/AndroidRuntime.h>
 
diff --git a/core/jni/android_util_Binder.h b/core/jni/android_util_Binder.h
index 16d993d..495e76a 100644
--- a/core/jni/android_util_Binder.h
+++ b/core/jni/android_util_Binder.h
@@ -15,7 +15,7 @@
 ** limitations under the License.
 */
 
-#include <utils/IBinder.h>
+#include <binder/IBinder.h>
 
 #include "jni.h"
 
diff --git a/core/jni/android_util_EventLog.cpp b/core/jni/android_util_EventLog.cpp
index 5e5103a..34b7c89 100644
--- a/core/jni/android_util_EventLog.cpp
+++ b/core/jni/android_util_EventLog.cpp
@@ -51,17 +51,17 @@
     size_t len;
     size_t capacity;
     uint8_t* buf;
-    
+
     ByteBuf(size_t initSize) {
         buf = (uint8_t*)malloc(initSize);
         len = 0;
-        capacity = initSize;        
+        capacity = initSize;
     }
-    
+
     ~ByteBuf() {
         free(buf);
     }
-    
+
     bool ensureExtraCapacity(size_t extra) {
         size_t spaceNeeded = len + extra;
         if (spaceNeeded > capacity) {
@@ -77,7 +77,7 @@
             return true;
         }
     }
- 
+
     void putIntEvent(jint value) {
         bool succeeded = ensureExtraCapacity(INT_BUFFER_SIZE);
         buf[len++] = EVENT_TYPE_INT;
@@ -162,7 +162,7 @@
  * In class android.util.EventLog:
  *  static native int writeEvent(long tag, long value)
  */
-static jint android_util_EventLog_writeEvent_Long(JNIEnv* env, jobject clazz, 
+static jint android_util_EventLog_writeEvent_Long(JNIEnv* env, jobject clazz,
                                                   jint tag, jlong value)
 {
     return android_btWriteLog(tag, EVENT_TYPE_LONG, &value, sizeof(value));
@@ -210,6 +210,8 @@
 /*
  * In class android.util.EventLog:
  *  static native void readEvents(int[] tags, Collection<Event> output)
+ *
+ *  Reads events from the event log, typically /dev/log/events
  */
 static void android_util_EventLog_readEvents(JNIEnv* env, jobject clazz,
                                              jintArray tags,
@@ -273,6 +275,80 @@
     env->ReleaseIntArrayElements(tags, tagValues, 0);
 }
 
+/*
+ * In class android.util.EventLog:
+ *  static native void readEvents(String path, Collection<Event> output)
+ *
+ *  Reads events from a file (See Checkin.Aggregation). Events are stored in
+ *  native raw format (logger_entry + payload).
+ */
+static void android_util_EventLog_readEventsFile(JNIEnv* env, jobject clazz, jstring path,
+            jobject out) {
+    if (path == NULL || out == NULL) {
+        jniThrowException(env, "java/lang/NullPointerException", NULL);
+        return;
+    }
+
+    const char *pathString = env->GetStringUTFChars(path, 0);
+    int fd = open(pathString, O_RDONLY | O_NONBLOCK);
+    env->ReleaseStringUTFChars(path, pathString);
+
+    if (fd < 0) {
+        jniThrowIOException(env, errno);
+        return;
+    }
+
+    uint8_t buf[LOGGER_ENTRY_MAX_LEN];
+    for (;;) {
+        // read log entry structure from file
+        int len = read(fd, buf, sizeof(logger_entry));
+        if (len == 0) {
+            break; // end of file
+        } else if (len < 0) {
+            jniThrowIOException(env, errno);
+        } else if ((size_t) len < sizeof(logger_entry)) {
+            jniThrowException(env, "java/io/IOException", "Event header too short");
+            break;
+        }
+
+        // read event payload
+        logger_entry* entry = (logger_entry*) buf;
+        if (entry->len > LOGGER_ENTRY_MAX_PAYLOAD) {
+            jniThrowException(env,
+                    "java/lang/IllegalArgumentException",
+                    "Too much data for event payload. Corrupt file?");
+            break;
+        }
+
+        len = read(fd, buf + sizeof(logger_entry), entry->len);
+        if (len == 0) {
+            break; // end of file
+        } else if (len < 0) {
+            jniThrowIOException(env, errno);
+        } else if ((size_t) len < entry->len) {
+            jniThrowException(env, "java/io/IOException", "Event payload too short");
+            break;
+        }
+
+        // create EventLog$Event and add it to the collection
+        int buffer_size = sizeof(logger_entry) + entry->len;
+        jbyteArray array = env->NewByteArray(buffer_size);
+        if (array == NULL) break;
+
+        jbyte *bytes = env->GetByteArrayElements(array, NULL);
+        memcpy(bytes, buf, buffer_size);
+        env->ReleaseByteArrayElements(array, bytes, 0);
+
+        jobject event = env->NewObject(gEventClass, gEventInitID, array);
+        if (event == NULL) break;
+
+        env->CallBooleanMethod(out, gCollectionAddID, event);
+        env->DeleteLocalRef(event);
+        env->DeleteLocalRef(array);
+    }
+
+    close(fd);
+}
 
 /*
  * JNI registration.
@@ -292,6 +368,10 @@
     { "readEvents",
       "([ILjava/util/Collection;)V",
       (void*) android_util_EventLog_readEvents
+    },
+    { "readEvents",
+      "(Ljava/lang/String;Ljava/util/Collection;)V",
+      (void*) android_util_EventLog_readEventsFile
     }
 };
 
diff --git a/core/jni/android_util_Process.cpp b/core/jni/android_util_Process.cpp
index aee0ed7..09a0d70 100644
--- a/core/jni/android_util_Process.cpp
+++ b/core/jni/android_util_Process.cpp
@@ -18,9 +18,9 @@
 #define LOG_TAG "Process"
 
 #include <utils/Log.h>
-#include <utils/IPCThreadState.h>
-#include <utils/ProcessState.h>
-#include <utils/IServiceManager.h>
+#include <binder/IPCThreadState.h>
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
 #include <utils/String8.h>
 #include <utils/Vector.h>
 
@@ -368,7 +368,7 @@
     return *((const jint*)v1) - *((const jint*)v2);
 }
 
-jint android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
+static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
 {
     int fd = open("/proc/meminfo", O_RDONLY);
     
@@ -388,7 +388,7 @@
     buffer[len] = 0;
 
     int numFound = 0;
-    int mem = 0;
+    jlong mem = 0;
     
     static const char* const sums[] = { "MemFree:", "Cached:", NULL };
     static const int sumsLen[] = { strlen("MemFree:"), strlen("Cached:"), NULL };
@@ -407,7 +407,7 @@
                     p++;
                     if (*p == 0) p--;
                 }
-                mem += atoi(num) * 1024;
+                mem += atoll(num) * 1024;
                 numFound++;
                 break;
             }
@@ -857,7 +857,7 @@
     {"setGid", "(I)I", (void*)android_os_Process_setGid},
     {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
     {"supportsProcesses", "()Z", (void*)android_os_Process_supportsProcesses},
-    {"getFreeMemory", "()I", (void*)android_os_Process_getFreeMemory},
+    {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
     {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
     {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
     {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
diff --git a/core/jni/android_view_Surface.cpp b/core/jni/android_view_Surface.cpp
index 076775f..bd3c805 100644
--- a/core/jni/android_view_Surface.cpp
+++ b/core/jni/android_view_Surface.cpp
@@ -24,6 +24,7 @@
 
 #include <SkCanvas.h>
 #include <SkBitmap.h>
+#include <SkRegion.h>
 
 #include "jni.h"
 #include <android_runtime/AndroidRuntime.h>
@@ -45,6 +46,7 @@
 static sso_t sso;
 
 struct so_t {
+    jfieldID surfaceControl;
     jfieldID surface;
     jfieldID saveCount;
     jfieldID canvas;
@@ -121,10 +123,50 @@
 
 // ----------------------------------------------------------------------------
 
+static sp<SurfaceControl> getSurfaceControl(JNIEnv* env, jobject clazz)
+{
+    SurfaceControl* const p = 
+        (SurfaceControl*)env->GetIntField(clazz, so.surfaceControl);
+    return sp<SurfaceControl>(p);
+}
+
+static void setSurfaceControl(JNIEnv* env, jobject clazz, 
+        const sp<SurfaceControl>& surface)
+{
+    SurfaceControl* const p = 
+        (SurfaceControl*)env->GetIntField(clazz, so.surfaceControl);
+    if (surface.get()) {
+        surface->incStrong(clazz);
+    }
+    if (p) {
+        p->decStrong(clazz);
+    }
+    env->SetIntField(clazz, so.surfaceControl, (int)surface.get());
+}
+
 static sp<Surface> getSurface(JNIEnv* env, jobject clazz)
 {
-    Surface* const p = (Surface*)env->GetIntField(clazz, so.surface);
-    return sp<Surface>(p);
+    sp<Surface> result((Surface*)env->GetIntField(clazz, so.surface));
+    if (result == 0) {
+        /*
+         * if this method is called from the WindowManager's process, it means
+         * the client is is not remote, and therefore is allowed to have
+         * a Surface (data), so we create it here. 
+         * If we don't have a SurfaceControl, it means we're in a different
+         * process.
+         */
+        
+        SurfaceControl* const control = 
+            (SurfaceControl*)env->GetIntField(clazz, so.surfaceControl);
+        if (control) {
+            result = control->getSurface();
+            if (result != 0) {
+                result->incStrong(clazz);
+                env->SetIntField(clazz, so.surface, (int)result.get());
+            }
+        }
+    }
+    return result;
 }
 
 static void setSurface(JNIEnv* env, jobject clazz, const sp<Surface>& surface)
@@ -153,12 +195,12 @@
     SurfaceComposerClient* client =
             (SurfaceComposerClient*)env->GetIntField(session, sso.client);
 
-    sp<Surface> surface(client->createSurface(pid, dpy, w, h, format, flags));
+    sp<SurfaceControl> surface(client->createSurface(pid, dpy, w, h, format, flags));
     if (surface == 0) {
         doThrow(env, OutOfResourcesException);
         return;
     }
-    setSurface(env, clazz, surface);
+    setSurfaceControl(env, clazz, surface);
 }
 
 static void Surface_initParcel(JNIEnv* env, jobject clazz, jobject argParcel)
@@ -168,19 +210,34 @@
         doThrow(env, "java/lang/NullPointerException", NULL);
         return;
     }
-    const sp<Surface>& rhs = Surface::readFromParcel(parcel);
+    sp<Surface> rhs = new Surface(*parcel);
     setSurface(env, clazz, rhs);
 }
 
 static void Surface_clear(JNIEnv* env, jobject clazz, uintptr_t *ostack)
 {
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (SurfaceControl::isValid(surface)) {
+        surface->clear();
+    }
+    setSurfaceControl(env, clazz, 0);
+    setSurface(env, clazz, 0);
+}
+
+static void Surface_release(JNIEnv* env, jobject clazz, uintptr_t *ostack)
+{
+    setSurfaceControl(env, clazz, 0);
     setSurface(env, clazz, 0);
 }
 
 static jboolean Surface_isValid(JNIEnv* env, jobject clazz)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    return surface->isValid() ? JNI_TRUE : JNI_FALSE;
+    const sp<SurfaceControl>& surfaceControl(getSurfaceControl(env, clazz));
+    if (surfaceControl != 0) {
+        return SurfaceControl::isValid(surfaceControl) ? JNI_TRUE : JNI_FALSE;
+    }
+    const sp<Surface>& surface(getSurface(env, clazz));
+    return Surface::isValid(surface) ? JNI_TRUE : JNI_FALSE;
 }
 
 static inline SkBitmap::Config convertPixelFormat(PixelFormat format)
@@ -200,8 +257,8 @@
 
 static jobject Surface_lockCanvas(JNIEnv* env, jobject clazz, jobject dirtyRect)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (!surface->isValid())
+    const sp<Surface>& surface(getSurface(env, clazz));
+    if (!Surface::isValid(surface))
         return 0;
 
     // get dirty region
@@ -212,7 +269,7 @@
         dirty.top   = env->GetIntField(dirtyRect, ro.t);
         dirty.right = env->GetIntField(dirtyRect, ro.r);
         dirty.bottom= env->GetIntField(dirtyRect, ro.b);
-        if (dirty.left < dirty.right && dirty.top < dirty.bottom) {
+        if (!dirty.isEmpty()) {
             dirtyRegion.set(dirty);    
         }
     } else {
@@ -235,7 +292,8 @@
 
     SkCanvas* nativeCanvas = (SkCanvas*)env->GetIntField(canvas, no.native_canvas);
     SkBitmap bitmap;
-    bitmap.setConfig(convertPixelFormat(info.format), info.w, info.h, info.bpr);
+    ssize_t bpr = info.s * bytesPerPixel(info.format);
+    bitmap.setConfig(convertPixelFormat(info.format), info.w, info.h, bpr);
     if (info.w > 0 && info.h > 0) {
         bitmap.setPixels(info.bits);
     } else {
@@ -243,13 +301,27 @@
         bitmap.setPixels(NULL);
     }
     nativeCanvas->setBitmapDevice(bitmap);
-    nativeCanvas->clipRegion(dirtyRegion.toSkRegion());
+    
+    SkRegion clipReg;
+    if (dirtyRegion.isRect()) { // very common case
+        const Rect& b(dirtyRegion.getBounds());
+        clipReg.setRect(b.left, b.top, b.right, b.bottom);
+    } else {
+        size_t count;
+        Rect const* r = dirtyRegion.getArray(&count);
+        while (count) {
+            clipReg.op(r->left, r->top, r->right, r->bottom, SkRegion::kUnion_Op);
+            r++, count--;
+        }
+    }
+
+    nativeCanvas->clipRegion(clipReg);
     
     int saveCount = nativeCanvas->save();
     env->SetIntField(clazz, so.saveCount, saveCount);
 
     if (dirtyRect) {
-        Rect bounds(dirtyRegion.bounds());
+        const Rect& bounds(dirtyRegion.getBounds());
         env->SetIntField(dirtyRect, ro.l, bounds.left);
         env->SetIntField(dirtyRect, ro.t, bounds.top);
         env->SetIntField(dirtyRect, ro.r, bounds.right);
@@ -268,8 +340,8 @@
         return;
     }
     
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (!surface->isValid())
+    const sp<Surface>& surface(getSurface(env, clazz));
+    if (!Surface::isValid(surface))
         return;
 
     // detach the canvas from the surface
@@ -289,26 +361,8 @@
 static void Surface_unlockCanvas(
         JNIEnv* env, jobject clazz, jobject argCanvas)
 {
-    jobject canvas = env->GetObjectField(clazz, so.canvas);
-    if (canvas != argCanvas) {
-        doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        return;
-    }
-    
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (!surface->isValid())
-        return;
-    
-    status_t err = surface->unlock();
-    if (err < 0) {
-        doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        return;
-    }
-    SkCanvas* nativeCanvas = (SkCanvas*)env->GetIntField(canvas, no.native_canvas);
-    int saveCount = env->GetIntField(clazz, so.saveCount);
-    nativeCanvas->restoreToCount(saveCount);
-    nativeCanvas->setBitmapDevice(SkBitmap());
-    env->SetIntField(clazz, so.saveCount, 0);
+    // XXX: this API has been removed
+    doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_openTransaction(
@@ -353,138 +407,140 @@
 static void Surface_setLayer(
         JNIEnv* env, jobject clazz, jint zorder)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->setLayer(zorder) < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->setLayer(zorder);
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_setPosition(
         JNIEnv* env, jobject clazz, jint x, jint y)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->setPosition(x, y) < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->setPosition(x, y);
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_setSize(
         JNIEnv* env, jobject clazz, jint w, jint h)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->setSize(w, h) < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->setSize(w, h);
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_hide(
         JNIEnv* env, jobject clazz)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->hide() < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->hide();
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_show(
         JNIEnv* env, jobject clazz)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->show() < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->show();
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_freeze(
         JNIEnv* env, jobject clazz)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->freeze() < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->freeze();
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_unfreeze(
         JNIEnv* env, jobject clazz)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->unfreeze() < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->unfreeze();
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_setFlags(
         JNIEnv* env, jobject clazz, jint flags, jint mask)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->setFlags(flags, mask) < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->setFlags(flags, mask);
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_setTransparentRegion(
         JNIEnv* env, jobject clazz, jobject argRegion)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        SkRegion* nativeRegion = (SkRegion*)env->GetIntField(argRegion, no.native_region);
-        if (surface->setTransparentRegionHint(Region(*nativeRegion)) < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    SkRegion* nativeRegion = (SkRegion*)env->GetIntField(argRegion, no.native_region);
+    
+    const SkIRect& b(nativeRegion->getBounds());
+    Region reg(Rect(b.fLeft, b.fTop, b.fRight, b.fBottom));
+    if (nativeRegion->isComplex()) {
+        SkRegion::Iterator it(*nativeRegion);
+        while (!it.done()) {
+            const SkIRect& r(it.rect());
+            reg.addRectUnchecked(r.fLeft, r.fTop, r.fRight, r.fBottom);
+            it.next();
         }
     }
+    
+    status_t err = surface->setTransparentRegionHint(reg);
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_setAlpha(
         JNIEnv* env, jobject clazz, jfloat alpha)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->setAlpha(alpha) < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->setAlpha(alpha);
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_setMatrix(
         JNIEnv* env, jobject clazz,
         jfloat dsdx, jfloat dtdx, jfloat dsdy, jfloat dtdy)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->setMatrix(dsdx, dtdx, dsdy, dtdy) < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->setMatrix(dsdx, dtdx, dsdy, dtdy);
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
 static void Surface_setFreezeTint(
         JNIEnv* env, jobject clazz,
         jint tint)
 {
-    const sp<Surface>& surface = getSurface(env, clazz);
-    if (surface->isValid()) {
-        if (surface->setFreezeTint(tint) < 0) {
-            doThrow(env, "java/lang/IllegalArgumentException", NULL);
-        }
-    }
+    const sp<SurfaceControl>& surface(getSurfaceControl(env, clazz));
+    if (surface == 0) return;
+    status_t err = surface->setFreezeTint(tint);
+    if (err<0 && err!=NO_INIT)
+        doThrow(env, "java/lang/IllegalArgumentException", NULL);
 }
 
+// ----------------------------------------------------------------------------
+
 static void Surface_copyFrom(
         JNIEnv* env, jobject clazz, jobject other)
 {
@@ -496,16 +552,21 @@
         return;
     }
 
-    const sp<Surface>& surface = getSurface(env, clazz);
-    const sp<Surface>& rhs = getSurface(env, other);
-    if (!Surface::isSameSurface(surface, rhs)) {
+    /*
+     * This is used by the WindowManagerService just after constructing
+     * a Surface and is necessary for returning the Surface reference to
+     * the caller. At this point, we should only have a SurfaceControl.
+     */
+    
+    const sp<SurfaceControl>& surface = getSurfaceControl(env, clazz);
+    const sp<SurfaceControl>& rhs = getSurfaceControl(env, other);
+    if (!SurfaceControl::isSameSurface(surface, rhs)) {
         // we reassign the surface only if it's a different one
         // otherwise we would loose our client-side state.
-        setSurface(env, clazz, rhs->dup());
+        setSurfaceControl(env, clazz, rhs);
     }
 }
 
-
 static void Surface_readFromParcel(
         JNIEnv* env, jobject clazz, jobject argParcel)
 {
@@ -515,9 +576,9 @@
         return;
     }
 
-    const sp<Surface>& surface = getSurface(env, clazz);
-    const sp<Surface>& rhs = Surface::readFromParcel(parcel);
-    if (!Surface::isSameSurface(surface, rhs)) {
+    const sp<Surface>& control(getSurface(env, clazz));
+    sp<Surface> rhs = new Surface(*parcel);
+    if (!Surface::isSameSurface(control, rhs)) {
         // we reassign the surface only if it's a different one
         // otherwise we would loose our client-side state.
         setSurface(env, clazz, rhs);
@@ -535,8 +596,8 @@
         return;
     }
 
-    const sp<Surface>& surface = getSurface(env, clazz);
-    Surface::writeToParcel(surface, parcel);
+    const sp<SurfaceControl>& control(getSurfaceControl(env, clazz));
+    SurfaceControl::writeSurfaceToParcel(control, parcel);
 }
 
 // ----------------------------------------------------------------------------
@@ -557,7 +618,8 @@
     {"nativeClassInit",     "()V",  (void*)nativeClassInit },
     {"init",                "(Landroid/view/SurfaceSession;IIIIII)V",  (void*)Surface_init },
     {"init",                "(Landroid/os/Parcel;)V",  (void*)Surface_initParcel },
-	{"clear",               "()V",  (void*)Surface_clear },
+    {"clear",               "()V",  (void*)Surface_clear },
+    {"release",             "()V",  (void*)Surface_release },
 	{"copyFrom",            "(Landroid/view/Surface;)V",  (void*)Surface_copyFrom },
 	{"isValid",             "()Z",  (void*)Surface_isValid },
 	{"lockCanvasNative",    "(Landroid/graphics/Rect;)Landroid/graphics/Canvas;",  (void*)Surface_lockCanvas },
@@ -586,7 +648,8 @@
 
 void nativeClassInit(JNIEnv* env, jclass clazz)
 {
-	so.surface   = env->GetFieldID(clazz, "mSurface", "I");
+    so.surface = env->GetFieldID(clazz, "mSurface", "I");
+    so.surfaceControl = env->GetFieldID(clazz, "mSurfaceControl", "I");
 	so.saveCount = env->GetFieldID(clazz, "mSaveCount", "I");
 	so.canvas    = env->GetFieldID(clazz, "mCanvas", "Landroid/graphics/Canvas;");
 
diff --git a/core/jni/com_google_android_gles_jni_EGLImpl.cpp b/core/jni/com_google_android_gles_jni_EGLImpl.cpp
index 4452065..974fc0b 100644
--- a/core/jni/com_google_android_gles_jni_EGLImpl.cpp
+++ b/core/jni/com_google_android_gles_jni_EGLImpl.cpp
@@ -21,7 +21,6 @@
 #include <EGL/egl.h>
 #include <GLES/gl.h>
 
-#include <ui/EGLNativeWindowSurface.h>
 #include <ui/Surface.h>
 #include <SkBitmap.h>
 #include <SkPixelRef.h>
@@ -338,7 +337,7 @@
         goto not_valid_surface;
 
     jint* base = beginNativeAttribList(_env, attrib_list);
-    EGLSurface sur = eglCreateWindowSurface(dpy, cnf, new EGLNativeWindowSurface(window), base);
+    EGLSurface sur = eglCreateWindowSurface(dpy, cnf, window, base);
     endNativeAttributeList(_env, attrib_list, base);
     return (jint)sur;
 }
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 00d9cf6..9d55dab 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -25,7 +25,7 @@
     <!-- Special broadcasts that only the system can send -->
     <!-- ================================================ -->
     <eat-comment />
-    
+
     <protected-broadcast android:name="android.intent.action.SCREEN_OFF" />
     <protected-broadcast android:name="android.intent.action.SCREEN_ON" />
     <protected-broadcast android:name="android.intent.action.USER_PRESENT" />
@@ -52,12 +52,12 @@
     <protected-broadcast android:name="android.intent.action.AIRPLANE_MODE" />
     <protected-broadcast android:name="android.intent.action.NEW_OUTGOING_CALL" />
     <protected-broadcast android:name="android.intent.action.REBOOT" />
-    
+
     <!-- ====================================== -->
     <!-- Permissions for things that cost money -->
     <!-- ====================================== -->
     <eat-comment />
-    
+
     <!-- Used for permissions that can be used to make the user spend money
          without their direct involvement.  For example, this is the group
          for permissions that allow you to directly place phone calls,
@@ -86,7 +86,7 @@
     <!-- Permissions for accessing messages -->
     <!-- ================================== -->
     <eat-comment />
-    
+
     <!-- Used for permissions that allow an application to send messages
          on behalf of the user or intercept messages being received by the
          user.  This is primarily intended for SMS/MMS messaging, such as
@@ -136,7 +136,7 @@
     <!-- Permissions for accessing personal info (contacts and calendar) -->
     <!-- =============================================================== -->
     <eat-comment />
-    
+
     <!-- Used for permissions that provide access to the user's private data,
          such as contacts, calendar events, e-mail messages, etc.  This includes
          both reading and writing of this data (which should generally be
@@ -190,8 +190,8 @@
         android:description="@string/permdesc_writeCalendar" />
 
     <!-- Allows an application to read the user dictionary. This should
-         really only be required by an IME, or a dictionary editor like 
-         the Settings app. 
+         really only be required by an IME, or a dictionary editor like
+         the Settings app.
          @hide Pending API council approval -->
     <permission android:name="android.permission.READ_USER_DICTIONARY"
         android:permissionGroup="android.permission-group.PERSONAL_INFO"
@@ -227,7 +227,7 @@
     <!-- Permissions for accessing location info -->
     <!-- ======================================= -->
     <eat-comment />
-    
+
     <!-- Used for permissions that allow access to the user's current
          location. -->
     <permission-group android:name="android.permission-group.LOCATION"
@@ -272,7 +272,7 @@
     <!-- Permissions for accessing networks -->
     <!-- ======================================= -->
     <eat-comment />
-    
+
     <!-- Used for permissions that provide access to networking services.  The
          main permission here is internet access, but this is also an
          appropriate group for accessing or modifying any network configuration
@@ -309,11 +309,19 @@
         android:description="@string/permdesc_bluetooth"
         android:label="@string/permlab_bluetooth" />
 
+    <!-- Allows applications to call into AccountAuthenticators. Only
+    the system can get this permission. -->
+    <permission android:name="android.permission.ACCOUNT_MANAGER_SERVICE"
+        android:permissionGroup="android.permission-group.ACCOUNTS"
+        android:protectionLevel="signature"
+        android:description="@string/permdesc_accountManagerService"
+        android:label="@string/permlab_accountManagerService" />
+
     <!-- ================================== -->
     <!-- Permissions for accessing accounts -->
     <!-- ================================== -->
     <eat-comment />
-    
+
     <!-- Permissions for direct access to Google accounts.
          Note that while right now this is only used for Google accounts,
          we expect in the future to have a more general account management
@@ -330,11 +338,33 @@
         android:description="@string/permdesc_getAccounts"
         android:label="@string/permlab_getAccounts" />
 
+    <!-- Allows an application to act as an AccountAuthenticator for
+         the AccountManager -->
+    <permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"
+        android:permissionGroup="android.permission-group.ACCOUNTS"
+        android:protectionLevel="dangerous"
+        android:label="@string/permlab_authenticateAccounts"
+        android:description="@string/permdesc_authenticateAccounts" />
+
+    <!-- Allows an application to request authtokens from the AccountManager -->
+    <permission android:name="android.permission.USE_CREDENTIALS"
+        android:permissionGroup="android.permission-group.ACCOUNTS"
+        android:protectionLevel="dangerous"
+        android:label="@string/permlab_useCredentials"
+        android:description="@string/permdesc_useCredentials" />
+
+    <!-- Allows an application to manage the list of accounts in the AccountManager -->
+    <permission android:name="android.permission.MANAGE_ACCOUNTS"
+        android:permissionGroup="android.permission-group.ACCOUNTS"
+        android:protectionLevel="dangerous"
+        android:label="@string/permlab_manageAccounts"
+        android:description="@string/permdesc_manageAccounts" />
+
     <!-- ================================== -->
     <!-- Permissions for accessing hardware -->
     <!-- ================================== -->
     <eat-comment />
-    
+
     <!-- Used for permissions that provide direct access to the hardware on
          the device.  This includes audio, the camera, vibrator, etc. -->
     <permission-group android:name="android.permission-group.HARDWARE_CONTROLS"
@@ -387,7 +417,7 @@
     <!-- Permissions associated with telephony state -->
     <!-- =========================================== -->
     <eat-comment />
-    
+
     <!-- Used for permissions that are associated with accessing and modifyign
          telephony state: intercepting outgoing calls, reading
          and modifying the phone state.  Note that
@@ -441,7 +471,7 @@
     <!-- Permissions for low-level system interaction -->
     <!-- ============================================ -->
     <eat-comment />
-    
+
     <!-- Group of permissions that are related to system APIs.  Many
          of these are not permissions the user will be expected to understand,
          and such permissions should generally be marked as "normal" protection
@@ -665,7 +695,7 @@
                 android:description="@string/permdesc_writeApnSettings"
                 android:label="@string/permlab_writeApnSettings" />
 
-    <!-- Allows an application to allow access the subscribed feeds 
+    <!-- Allows an application to allow access the subscribed feeds
          ContentProvider. -->
     <permission android:name="android.permission.SUBSCRIBED_FEEDS_READ"
         android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
@@ -677,7 +707,7 @@
         android:label="@string/permlab_subscribedFeedsWrite"
         android:description="@string/permdesc_subscribedFeedsWrite"
         android:protectionLevel="dangerous" />
-        
+
     <!-- Allows applications to change network connectivity state -->
     <permission android:name="android.permission.CHANGE_NETWORK_STATE"
         android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
@@ -728,7 +758,7 @@
     <!-- Permissions for special development tools -->
     <!-- ========================================= -->
     <eat-comment />
-    
+
     <!-- Group of permissions that are related to development features.  These
          are not permissions that should appear in normal applications; they
          protect APIs that are intended only to be used for development
@@ -1088,6 +1118,16 @@
                 android:excludeFromRecents="true">
         </activity>
 
+        <activity android:name="android.accounts.ChooseAccountActivity"
+                android:excludeFromRecents="true"
+                android:exported="true">
+        </activity>
+
+        <activity android:name="android.accounts.GrantCredentialsPermissionActivity"
+                android:excludeFromRecents="true"
+                android:exported="true">
+        </activity>
+
         <service android:name="com.android.server.LoadAverageService"
             android:exported="true" />
 
@@ -1100,7 +1140,7 @@
         <receiver android:name="com.android.server.MasterClearReceiver"
             android:permission="android.permission.MASTER_CLEAR" >
             <intent-filter>
-                <action android:name="android.intent.action.GTALK_DATA_MESSAGE_RECEIVED" />
+                <action android:name="android.intent.action.REMOTE_INTENT" />
                 <category android:name="android.intent.category.MASTER_CLEAR" />
             </intent-filter>
         </receiver>
diff --git a/core/res/res/drawable/stat_sys_signal_flightmode.png b/core/res/res/drawable/stat_sys_signal_flightmode.png
old mode 100644
new mode 100755
Binary files differ
diff --git a/core/res/res/layout/grant_credentials_permission.xml b/core/res/res/layout/grant_credentials_permission.xml
new file mode 100644
index 0000000..fe1c22e
--- /dev/null
+++ b/core/res/res/layout/grant_credentials_permission.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+** Copyright 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.
+*/
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="fill_parent"
+    android:layout_height="wrap_content"
+    android:orientation="vertical">
+    <TextView
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:id="@+id/message" />
+    <Button android:id="@+id/allow"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:text="@string/allow" />
+
+    <Button android:id="@+id/deny"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:text="@string/deny" />
+
+    <ListView android:id="@+id/packages_list"
+       android:layout_width="fill_parent" android:layout_height="fill_parent"/>
+
+</LinearLayout>
diff --git a/core/res/res/values-cs/strings.xml b/core/res/res/values-cs/strings.xml
index 35a169f..0d6137b 100644
--- a/core/res/res/values-cs/strings.xml
+++ b/core/res/res/values-cs/strings.xml
@@ -390,7 +390,6 @@
     <item>"Ostatní"</item>
     <item>"Vlastní"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Mobilní"</string>
   <string-array name="postalAddressTypes">
     <item>"Domů"</item>
     <item>"Práce"</item>
diff --git a/core/res/res/values-da/strings.xml b/core/res/res/values-da/strings.xml
index 3392546..4add1f8 100644
--- a/core/res/res/values-da/strings.xml
+++ b/core/res/res/values-da/strings.xml
@@ -427,7 +427,6 @@
     <item>"Anden"</item>
     <item>"Tilpasset"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Mobil"</string>
   <string-array name="postalAddressTypes">
     <item>"Start"</item>
     <item>"Arbejde"</item>
diff --git a/core/res/res/values-de/strings.xml b/core/res/res/values-de/strings.xml
index 1f9001b..9163c61 100644
--- a/core/res/res/values-de/strings.xml
+++ b/core/res/res/values-de/strings.xml
@@ -390,7 +390,6 @@
     <item>"Andere"</item>
     <item>"Benutzerdefiniert"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Mobil"</string>
   <string-array name="postalAddressTypes">
     <item>"Privat"</item>
     <item>"Arbeit"</item>
diff --git a/core/res/res/values-el/strings.xml b/core/res/res/values-el/strings.xml
index e340095..3158a37 100644
--- a/core/res/res/values-el/strings.xml
+++ b/core/res/res/values-el/strings.xml
@@ -427,7 +427,6 @@
     <item>"Άλλο"</item>
     <item>"Προσαρμοσμένο"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Κινητό"</string>
   <string-array name="postalAddressTypes">
     <item>"Οικία"</item>
     <item>"Εργασία"</item>
diff --git a/core/res/res/values-es-rUS/strings.xml b/core/res/res/values-es-rUS/strings.xml
index 6544d4b..ee28403 100644
--- a/core/res/res/values-es-rUS/strings.xml
+++ b/core/res/res/values-es-rUS/strings.xml
@@ -427,7 +427,6 @@
     <item>"Otros"</item>
     <item>"Personalización"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Celular"</string>
   <string-array name="postalAddressTypes">
     <item>"Página principal"</item>
     <item>"Trabajo"</item>
diff --git a/core/res/res/values-es/strings.xml b/core/res/res/values-es/strings.xml
index b0b2d51..f3ff316 100644
--- a/core/res/res/values-es/strings.xml
+++ b/core/res/res/values-es/strings.xml
@@ -390,7 +390,6 @@
     <item>"Otra"</item>
     <item>"Personalizar"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Móvil"</string>
   <string-array name="postalAddressTypes">
     <item>"Casa"</item>
     <item>"Trabajo"</item>
diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml
index b46ea02..ae3c807 100644
--- a/core/res/res/values-fr/strings.xml
+++ b/core/res/res/values-fr/strings.xml
@@ -390,7 +390,6 @@
     <item>"Autre"</item>
     <item>"Personnalisée"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Mobile"</string>
   <string-array name="postalAddressTypes">
     <item>"Domicile"</item>
     <item>"Bureau"</item>
diff --git a/core/res/res/values-it/strings.xml b/core/res/res/values-it/strings.xml
index 1b8d504..778faac 100644
--- a/core/res/res/values-it/strings.xml
+++ b/core/res/res/values-it/strings.xml
@@ -390,7 +390,6 @@
     <item>"Altro"</item>
     <item>"Personalizzato"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Cellulare"</string>
   <string-array name="postalAddressTypes">
     <item>"Casa"</item>
     <item>"Ufficio"</item>
diff --git a/core/res/res/values-ja/strings.xml b/core/res/res/values-ja/strings.xml
index 6a659ee..4ad87d7 100644
--- a/core/res/res/values-ja/strings.xml
+++ b/core/res/res/values-ja/strings.xml
@@ -427,7 +427,6 @@
     <item>"その他"</item>
     <item>"カスタム"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"携帯"</string>
   <string-array name="postalAddressTypes">
     <item>"自宅"</item>
     <item>"仕事"</item>
diff --git a/core/res/res/values-ko/strings.xml b/core/res/res/values-ko/strings.xml
index 34b19b6..c3a9c70 100644
--- a/core/res/res/values-ko/strings.xml
+++ b/core/res/res/values-ko/strings.xml
@@ -427,7 +427,6 @@
     <item>"기타"</item>
     <item>"맞춤설정"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"모바일"</string>
   <string-array name="postalAddressTypes">
     <item>"집"</item>
     <item>"회사"</item>
diff --git a/core/res/res/values-nl/strings.xml b/core/res/res/values-nl/strings.xml
index 533be17..2bbd02d 100644
--- a/core/res/res/values-nl/strings.xml
+++ b/core/res/res/values-nl/strings.xml
@@ -390,7 +390,6 @@
     <item>"Overig"</item>
     <item>"Aangepast"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Mobiel"</string>
   <string-array name="postalAddressTypes">
     <item>"Thuis"</item>
     <item>"Werk"</item>
diff --git a/core/res/res/values-pl/strings.xml b/core/res/res/values-pl/strings.xml
index 3a8c6a6..3f7921d 100644
--- a/core/res/res/values-pl/strings.xml
+++ b/core/res/res/values-pl/strings.xml
@@ -390,7 +390,6 @@
     <item>"Inne"</item>
     <item>"Niestandardowy"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Komórka"</string>
   <string-array name="postalAddressTypes">
     <item>"Dom"</item>
     <item>"Praca"</item>
diff --git a/core/res/res/values-pt-rPT/strings.xml b/core/res/res/values-pt-rPT/strings.xml
index 04ca746..5b75aad 100644
--- a/core/res/res/values-pt-rPT/strings.xml
+++ b/core/res/res/values-pt-rPT/strings.xml
@@ -427,7 +427,6 @@
     <item>"Outro"</item>
     <item>"Personalizado"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Móvel"</string>
   <string-array name="postalAddressTypes">
     <item>"Residência"</item>
     <item>"Emprego"</item>
diff --git a/core/res/res/values-pt/strings.xml b/core/res/res/values-pt/strings.xml
index 8c5babb..4f84872 100644
--- a/core/res/res/values-pt/strings.xml
+++ b/core/res/res/values-pt/strings.xml
@@ -427,7 +427,6 @@
     <item>"Outros"</item>
     <item>"Personalizado"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Celular"</string>
   <string-array name="postalAddressTypes">
     <item>"Página inicial"</item>
     <item>"Trabalho"</item>
diff --git a/core/res/res/values-ru/strings.xml b/core/res/res/values-ru/strings.xml
index bb218c5..22120f6 100644
--- a/core/res/res/values-ru/strings.xml
+++ b/core/res/res/values-ru/strings.xml
@@ -427,7 +427,6 @@
     <item>"Другой"</item>
     <item>"Особый"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Мобильный"</string>
   <string-array name="postalAddressTypes">
     <item>"Домашний"</item>
     <item>"Рабочий"</item>
diff --git a/core/res/res/values-sv/strings.xml b/core/res/res/values-sv/strings.xml
index a9e7989..40d2500 100644
--- a/core/res/res/values-sv/strings.xml
+++ b/core/res/res/values-sv/strings.xml
@@ -427,7 +427,6 @@
     <item>"Övrigt"</item>
     <item>"Anpassad"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Mobil"</string>
   <string-array name="postalAddressTypes">
     <item>"Hem"</item>
     <item>"Arbete"</item>
diff --git a/core/res/res/values-tr/strings.xml b/core/res/res/values-tr/strings.xml
index e4bbca7..bda67c7 100644
--- a/core/res/res/values-tr/strings.xml
+++ b/core/res/res/values-tr/strings.xml
@@ -427,7 +427,6 @@
     <item>"Diğer"</item>
     <item>"Özel"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"Mobil"</string>
   <string-array name="postalAddressTypes">
     <item>"Ev"</item>
     <item>"İş"</item>
diff --git a/core/res/res/values-zh-rCN/strings.xml b/core/res/res/values-zh-rCN/strings.xml
index bc95c59..6741b3b 100644
--- a/core/res/res/values-zh-rCN/strings.xml
+++ b/core/res/res/values-zh-rCN/strings.xml
@@ -427,7 +427,6 @@
     <item>"其他邮箱"</item>
     <item>"自定义邮箱"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"手机"</string>
   <string-array name="postalAddressTypes">
     <item>"住宅地址"</item>
     <item>"单位地址"</item>
diff --git a/core/res/res/values-zh-rTW/strings.xml b/core/res/res/values-zh-rTW/strings.xml
index 87b3ee2..f355a71 100644
--- a/core/res/res/values-zh-rTW/strings.xml
+++ b/core/res/res/values-zh-rTW/strings.xml
@@ -390,7 +390,6 @@
     <item>"其他信箱"</item>
     <item>"自訂"</item>
   </string-array>
-    <string name="mobileEmailTypeName">"行動裝置"</string>
   <string-array name="postalAddressTypes">
     <item>"住家"</item>
     <item>"公司"</item>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index fd78f83..ad6d94f 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -598,7 +598,7 @@
         <flag name="time" value="0x00000024" />
     </attr>
 
-    <!-- Additional features you can enable in an IME associated with an editor,
+    <!-- Additional features you can enable in an IME associated with an editor
          to improve the integration with your application.  The constants
          here correspond to those defined by
          {@link android.view.inputmethod.EditorInfo#imeOptions}. -->
@@ -682,7 +682,7 @@
     <attr name="y" format="dimension" />
 
     <!-- Specifies how to place the content of an object, both
-         on the x and y axis, within the object itself. -->
+         on the x- and y-axis, within the object itself. -->
     <attr name="gravity">
         <!-- Push object to the top of its container, not changing its size. -->
         <flag name="top" value="0x30" />
@@ -738,7 +738,7 @@
     <attr name="entries" format="reference" />
 
     <!-- Standard gravity constant that a child can supply to its parent.
-         Defines how to place the view, both its x and y axis, within its parent view group. -->
+         Defines how to place the view, both its x- and y-axis, within its parent view group. -->
     <attr name="layout_gravity">
         <!-- Push object to the top of its container, not changing its size. -->
         <flag name="top" value="0x30" />
@@ -1817,7 +1817,7 @@
         <attr name="minEms" format="integer" min="0" />
         <!-- Makes the TextView be at least this many pixels wide -->
         <attr name="minWidth" />
-        <!-- Specifies how to align the text by the view's x and/or y axis
+        <!-- Specifies how to align the text by the view's x- and/or y-axis
              when the text is smaller than the view. -->
         <attr name="gravity" />
         <!-- Whether the text is allowed to be wider than the view (and
@@ -3328,6 +3328,47 @@
         <attr name="configure" format="string" />
     </declare-styleable>
 
+    <!-- =============================== -->
+    <!-- Accounts package class attributes -->
+    <!-- =============================== -->
+
+    <!-- Use <code>account-authenticator</code> as the root tag of the XML resource that
+         describes an account authenticator.
+     -->
+    <declare-styleable name="AccountAuthenticator">
+        <!-- the account type this authenticator handles. -->
+        <attr name="accountType" format="string"/>
+        <!-- the user-visible name of the authenticator. -->
+        <attr name="label"/>
+        <!-- the icon of the authenticator. -->
+        <attr name="icon"/>
+    </declare-styleable>
+
+    <!-- =============================== -->
+    <!-- Accounts package class attributes -->
+    <!-- =============================== -->
+
+    <!-- Use <code>account-authenticator</code> as the root tag of the XML resource that
+         describes an account authenticator.
+     -->
+    <declare-styleable name="SyncAdapter">
+        <!-- the authority of a content provider. -->
+        <attr name="contentAuthority" format="string"/>
+        <attr name="accountType"/>
+    </declare-styleable>
+
+    <!-- =============================== -->
+    <!-- Contacts meta-data attributes -->
+    <!-- =============================== -->
+
+    <declare-styleable name="Icon">
+        <attr name="icon" />
+        <attr name="mimeType" />
+    </declare-styleable>
+
+    <declare-styleable name="IconDefault">
+        <attr name="icon" />
+    </declare-styleable>
 
 </resources>
 
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 7215685..f655b27 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -36,6 +36,6 @@
     <integer name="config_longAnimTime">300</integer>
 
     <!-- Flag indicating whether Last Name comes before First Name.
-         This becomes true in Japan, for example.-->
+        This becomes true in Japan, for example.-->
     <bool name="config_lastname_comes_before_firstname">false</bool>
 </resources>
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 6a6b7fc..f8dd4c1 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -5,16 +5,16 @@
      ***************************************************************
      IMPORTANT NOTE FOR ANYONE MODIFYING THIS FILE
      READ THIS BEFORE YOU MAKE ANY CHANGES
-     
+
      This file defines the binary compatibility for resources.  As such,
      you must be very careful when making changes here, or you will
      completely break backwards compatibility with old applications.
-     
+
      To avoid breaking compatibility, all new resources must be placed
      at the end of the list of resources of the same type.  Placing a resource
      in the middle of type will cause all following resources to be
      assigned new resource numbers, breaking compatibility.
-     
+
      ***************************************************************
      *************************************************************** -->
 <resources>
@@ -22,7 +22,7 @@
   <!-- We don't want to publish private symbols in android.R as part of the
        SDK.  Instead, put them here. -->
   <private-symbols package="com.android.internal" />
-    
+
   <!-- AndroidManifest.xml attributes. -->
   <eat-comment />
 
@@ -569,10 +569,10 @@
   <public type="attr" name="lineSpacingExtra" id="0x01010217" />
   <public type="attr" name="lineSpacingMultiplier" id="0x01010218" />
   <public type="attr" name="listChoiceIndicatorSingle" id="0x01010219" />
-  <public type="attr" name="listChoiceIndicatorMultiple" id="0x0101021a" />    
+  <public type="attr" name="listChoiceIndicatorMultiple" id="0x0101021a" />
   <public type="attr" name="versionCode" id="0x0101021b" />
   <public type="attr" name="versionName" id="0x0101021c" />
-  
+
   <public type="id" name="background" id="0x01020000" />
   <public type="id" name="checkbox" id="0x01020001" />
   <public type="id" name="content" id="0x01020002" />
@@ -601,7 +601,7 @@
   <public type="id" name="button1" id="0x01020019" />
   <public type="id" name="button2" id="0x0102001a" />
   <public type="id" name="button3" id="0x0102001b" />
-  
+
   <public type="style" name="Animation" id="0x01030000" />
   <public type="style" name="Animation.Activity" id="0x01030001" />
   <public type="style" name="Animation.Dialog" id="0x01030002" />
@@ -748,7 +748,7 @@
   <public type="drawable" name="btn_plus" id="0x01080008" />
   <public type="drawable" name="btn_radio" id="0x01080009" />
   <public type="drawable" name="btn_star" id="0x0108000a" />
-  <public type="drawable" name="btn_star_big_off" id="0x0108000b" /> 
+  <public type="drawable" name="btn_star_big_off" id="0x0108000b" />
   <public type="drawable" name="btn_star_big_on" id="0x0108000c" />
   <public type="drawable" name="button_onoff_indicator_on" id="0x0108000d" />
   <public type="drawable" name="button_onoff_indicator_off" id="0x0108000e" />
@@ -916,7 +916,7 @@
   <public type="layout" name="select_dialog_item" id="0x01090011" />
   <public type="layout" name="select_dialog_singlechoice" id="0x01090012" />
   <public type="layout" name="select_dialog_multichoice" id="0x01090013" />
-  
+
   <public type="anim" name="fade_in" id="0x010a0000" />
   <public type="anim" name="fade_out" id="0x010a0001" />
   <public type="anim" name="slide_in_left" id="0x010a0002" />
@@ -929,9 +929,9 @@
      Resources added in version 2 of the platform.
      =============================================================== -->
   <eat-comment />
-  
+
   <public type="attr" name="marqueeRepeatLimit" id="0x0101021d" />
-  
+
 <!-- ===============================================================
      Resources added in version 3 of the platform.
      =============================================================== -->
@@ -1062,7 +1062,7 @@
   <public type="id" name="stopSelectingText" id="0x01020029" />
   <!-- Menu ID to perform a "add to dictionary" operation. -->
   <public type="id" name="addToDictionary" id="0x0102002a" />
-  
+
   <public type="style" name="Theme.InputMethod" id="0x01030054" />
   <public type="style" name="Theme.NoDisplay" id="0x01030055" />
   <public type="style" name="Animation.InputMethod" id="0x01030056" />
@@ -1070,7 +1070,7 @@
   <public type="style" name="ButtonBar" id="0x01030058" />
   <public type="style" name="Theme.Panel" id="0x01030059" />
   <public type="style" name="Theme.Light.Panel" id="0x0103005a" />
-  
+
   <public type="string" name="dialog_alert_title" id="0x01040014" />
   <public type="string" name="VideoView_error_text_invalid_progressive_playback" id="0x01040015" />
 
@@ -1081,7 +1081,7 @@
 
   <!--  Drawable to use as a background for a taller version of the titlebar -->
   <public type="drawable" name="title_bar_tall" id="0x010800a6" />
-  
+
   <public type="integer" name="config_shortAnimTime" id="0x010e0000" />
   <public type="integer" name="config_mediumAnimTime" id="0x010e0001" />
   <public type="integer" name="config_longAnimTime" id="0x010e0002" />
@@ -1145,21 +1145,31 @@
 
   <public-padding type="array" name="donut_resource_pad" end="0x01070010" />
 
-  <public type="drawable" name="stat_sys_vp_phone_call" />
-  <public type="drawable" name="stat_sys_vp_phone_call_on_hold" />
+  <public-padding type="anim" name="donut_resource_pad" end="0x010a0020" />
   
-  <public-padding type="drawable" name="donut_resource_pad" end="0x010800d0" />
-  
-  <public-padding type="layout" name="donut_resource_pad" end="0x01090020" />
+  <public-padding type="integer" name="donut_resource_pad" end="0x010e0010" />
   
   <public type="anim" name="anticipate_interpolator" />
   <public type="anim" name="overshoot_interpolator" />
   <public type="anim" name="anticipate_overshoot_interpolator" />
   <public type="anim" name="bounce_interpolator" />
   <public type="anim" name="linear_interpolator" />
+  
+  <public-padding type="drawable" name="donut_resource_pad" end="0x010800d0" />
+  
+  <public-padding type="layout" name="donut_resource_pad" end="0x01090020" />
+  
+  
+<!-- ===============================================================
+     Resources added in Eclair.
+     =============================================================== -->
+  <eat-comment />
 
-  <public-padding type="anim" name="donut_resource_pad" end="0x010a0020" />
+  <public type="attr" name="accountType" />
+  <public type="attr" name="contentAuthority" />
+
+  <public type="drawable" name="stat_sys_vp_phone_call" />
+  <public type="drawable" name="stat_sys_vp_phone_call_on_hold" />
   
-  <public-padding type="integer" name="donut_resource_pad" end="0x010e0010" />
-  
+
 </resources>
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 4bbd178..0e848398 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -134,7 +134,7 @@
     <string name="RestrictedOnNormal">Voice/SMS service is blocked.</string>
     <!-- Displayed to tell the user that all voice service is blocked by access control. -->
     <string name="RestrictedOnAll">All voice/SMS services are blocked.</string>
-    
+
     <!-- Mappings between TS 27.007 +CFCC/+CLCK "service classes" and human-readable strings--> <skip />
     <!-- Example: Service was enabled for: Voice, Data -->
     <string name="serviceClassVoice">Voice</string>
@@ -229,6 +229,13 @@
     <!-- Displayed when a request failed because there are too many requests right now. -->
     <string name="httpErrorTooManyRequests">Too many requests are being processed. Try again later.</string>
 
+    <!-- Account notifications --> <skip />
+    <!-- A notification is shown when the AccountManager is unable to
+    supply an auth token without prompting the user to re-enter the
+    password.  This is the text that will scroll through the
+    notification bar (will be seen by the user as he uses another application). -->
+    <string name="notification_title">Sign-in error</string>
+
     <!-- Sync notifications --> <skip />
     <!-- A notification is shown when there is a sync error.  This is the text that will scroll through the notification bar (will be seen by the user as he uses another application). -->
     <string name="contentServiceSync">Sync</string>
@@ -299,7 +306,7 @@
 
     <!-- Label for the Android system components when they are shown to the user. -->
     <string name="android_system_label">Android System</string>
-    
+
     <!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permgrouplab_costMoney">Services that cost you money</string>
     <!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
@@ -800,7 +807,7 @@
     <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permlab_readFrameBuffer">read frame buffer</string>
     <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
-    <string name="permdesc_readFrameBuffer">Allows application to use
+    <string name="permdesc_readFrameBuffer">Allows application to
         read the content of the frame buffer.</string>
 
     <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
@@ -961,12 +968,40 @@
         the phone\'s time zone.</string>
 
     <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+    <string name="permlab_accountManagerService">act as the AccountManagerService</string>
+    <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+    <string name="permdesc_accountManagerService">Allows an
+    application to make calls to AccountAuthenticators</string>
+
+    <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permlab_getAccounts">discover known accounts</string>
     <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permdesc_getAccounts">Allows an application to get
       the list of accounts known by the phone.</string>
 
     <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+    <string name="permlab_authenticateAccounts">act as an account authenticator</string>
+    <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+    <string name="permdesc_authenticateAccounts">Allows an application
+    to use the account authenticator capabilities of the
+    AccountManager, including creating accounts and getting and
+    setting their passwords.</string>
+
+    <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+    <string name="permlab_manageAccounts">manage the accounts list</string>
+    <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+    <string name="permdesc_manageAccounts">Allows an application to
+    perform operations like adding, and removing accounts and deleting
+    their password.</string>
+
+    <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+    <string name="permlab_useCredentials">use the authentication
+    credentials of an account</string>
+    <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+    <string name="permdesc_useCredentials">Allows an application to
+    request authentication tokens.</string>
+
+    <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permlab_accessNetworkState">view network state</string>
     <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permdesc_accessNetworkState">Allows an application to view
@@ -1109,9 +1144,6 @@
         <item>Custom</item>
     </string-array>
 
-    <!-- String which means the type "mobile phone". -->
-    <string name="mobileEmailTypeName">Mobile</string>
-
     <!-- The order of these is important, don't reorder without changing Contacts.java --> <skip />
     <!-- Postal address types from android.provider.Contacts. This could be used when adding a new address for a contact, for example. -->
     <string-array name="postalAddressTypes">
@@ -1322,7 +1354,7 @@
 
     <!-- Do not translate.  WebView User Agent string -->
     <string name="web_user_agent"><xliff:g id="x">Mozilla/5.0 (Linux; U; Android %s)
-        AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1</xliff:g></string>
+        AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17</xliff:g></string>
 
     <!-- Title for a JavaScript dialog. "The page at <url of current page> says:" -->
     <string name="js_dialog_title">The page at \'<xliff:g id="title">%s</xliff:g>\' says:</string>
@@ -1378,8 +1410,8 @@
     <string name="menu_delete_shortcut_label">delete</string>
 
     <!-- Strings used for search bar --><skip />
-    
-    <!-- This is the default button label in the system-wide search UI. 
+
+    <!-- This is the default button label in the system-wide search UI.
          It is also used by the home screen's search "widget". It should be short -->
     <string name="search_go">Search</string>
 
@@ -1435,7 +1467,7 @@
         <item quantity="one">tomorrow</item>
         <item quantity="other">in <xliff:g id="count">%d</xliff:g> days</item>
     </plurals>
-    
+
     <!-- This is used to express that something occurred some number of abbreviated seconds in the past (e.g., 5 secs ago). -->
     <plurals name="abbrev_num_seconds_ago">
         <item quantity="one">1 sec ago</item>
@@ -1754,7 +1786,7 @@
     <string name="usb_storage_button_mount">Mount</string>
     <!-- See USB_STORAGE.   This is the button text to ignore the plugging in of the phone.. -->
     <string name="usb_storage_button_unmount">Don\'t mount</string>
-    <!-- See USB_STORAGE_DIALOG.  If there was an error mounting, this is the text. --> 
+    <!-- See USB_STORAGE_DIALOG.  If there was an error mounting, this is the text. -->
     <string name="usb_storage_error_message">There is a problem using your SD card for USB storage.</string>
     <!-- USB_STORAGE: When the user connects the phone to a computer via USB, we show a notification asking if he wants to share files across.  This is the title -->
     <string name="usb_storage_notification_title">USB connected</string>
@@ -1775,7 +1807,7 @@
     <string name="usb_storage_stop_button_mount">Turn Off</string>
     <!-- See USB_STORAGE_STOP.   This is the button text to cancel stoping usb storage. -->
     <string name="usb_storage_stop_button_unmount">Cancel</string>
-    <!-- See USB_STORAGE_STOP_DIALOG.  If there was an error stopping, this is the text. --> 
+    <!-- See USB_STORAGE_STOP_DIALOG.  If there was an error stopping, this is the text. -->
     <string name="usb_storage_stop_error_message">We've encountered a problem turning off USB storage. Check to make sure you have unmounted the USB host, then try again.</string>
 
     <!-- External media format dialog strings -->
@@ -1791,7 +1823,7 @@
     <string name="adb_active_notification_title">USB debugging connected</string>
     <!-- Message of notification shown when ADB is actively connected to the phone. -->
     <string name="adb_active_notification_message">A computer is connected to your phone.</string>
-    
+
     <!-- Used to replace %s in urls retreived from the signin server with locales.  For Some        -->
     <!-- devices we don't support all the locales we ship to and need to replace the '%s' with a    -->
     <!-- locale string based on mcc values.  By default (0-length string) we don't replace the %s   -->
@@ -1801,10 +1833,10 @@
 
     <!-- Title of the pop-up dialog in which the user switches input method components. -->
     <string name="select_input_method">Select Input Method</string>
-    
+
     <string name="fast_scroll_alphabet">\u0020ABCDEFGHIJKLMNOPQRSTUVWXYZ</string>
     <string name="fast_scroll_numeric_alphabet">\u00200123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ</string>
-    
+
     <string name="candidates_style"><u>candidates</u></string>
 
     <!-- External media notification strings -->
@@ -1851,23 +1883,23 @@
 
     <!-- Long label for a button on a full-screen input method for the "Go" action. -->
     <string name="ime_action_go">Go</string>
-    
+
     <!-- Long label for a button on a full-screen input method for the "Search" action. -->
     <string name="ime_action_search">Search</string>
-    
+
     <!-- Long label for a button on a full-screen input method for the "Send" action. -->
     <string name="ime_action_send">Send</string>
-    
+
     <!-- Long label for a button on a full-screen input method for the "Next" action. -->
     <string name="ime_action_next">Next</string>
-    
+
     <!-- Long label for a button on a full-screen input method for the "Done" action. -->
     <string name="ime_action_done">Done</string>
-    
+
     <!-- Long label for a button on a full-screen input method for an unknown action. -->
     <string name="ime_action_default">Execute</string>
-    
-    <!-- Strings for search suggestions. These are going here because they are referenced by both 
+
+    <!-- Strings for search suggestions. These are going here because they are referenced by both
          ContactsProvider and GoogleContactsProvider -->
     <skip />
 
@@ -1878,8 +1910,162 @@
     <!-- This string appears (on two lines) when you type a number into contacts search, to let you create a contact whose phone number is the number you typed.  The first line will be in bigger type than the second. -->
     <string name="create_contact_using">Create contact\nusing <xliff:g id="number" example="555">%s</xliff:g></string>
 
-    <!-- This string array should be overridden by the manufacture to present a list of carrier-id,locale pairs.  This is used at startup to set a default locale by checking the system property ro.carrier for the carrier-id and searching through this array -->
-    <string-array translatable="false" name="carrier_locales">
+    <!-- various string resources for Contacts -->
+    <string-array name="common_nicknames">
+        <item>Albert, Al, Bert, Bertie</item>
+        <item>Alexander, Al, Alex, Lex, Sasha</item>
+        <item>Alexandra, Al, Alex, Allie, Ally, Lex, Lexie, Sandra, Sandy, Sasha</item>
+        <item>Alice, Allie, Ally</item>
+        <item>Alison, Allie, Ally</item>
+        <item>Allison, Allie, Ally</item>
+        <item>Amanda, Mandi, Mandy</item>
+        <item>Andrea, Andie</item>
+        <item>Andrew, Andy, Drew</item>
+        <item>Anthony, Tony, Toni, Tone</item>
+        <item>Arthur, Art, Arty</item>
+        <item>Barbara, Babs, Barb, Barbie</item>
+        <item>Benjamin, Ben, Benji, Benny</item>
+        <item>Bernard, Bern, Bernie</item>
+        <item>Bertram, Bert, Bertie</item>
+        <item>Bradly, Brad</item>
+        <item>Catherine, Cat, Cate, Cath, Catie, Cathy, Kat, Kate, Katie, Kathy</item>
+        <item>Charles, Chuck, Chaz, Charlie, Buck</item>
+        <item>Christine, Chris, Chrissy, Chrissie</item>
+        <item>Christopher, Chris</item>
+        <item>Cynthia, Cindy, Cynth</item>
+        <item>Daniel, Dan, Danny</item>
+        <item>David, Dave</item>
+        <item>Deborah, Deb, Debbie</item>
+        <item>Dennis, Den, Denny, Dean</item>
+        <item>Dolores, Dolly</item>
+        <item>Donald, Don, Donny</item>
+        <item>Donnatella, Donna</item>
+        <item>Dorothea, Dot, Dotty</item>
+        <item>Dorothy, Dot, Dotty</item>
+        <item>Douglas, Doug</item>
+        <item>Edward, Ed, Eddie, Ned, Neddie, Neddy, Ted, Teddy, Teddie</item>
+        <item>Eleanor, Ella, Ellie, Elle</item>
+        <item>Elisabetta, Betta</item>
+        <item>Elizabeth, Beth, Bess, Bessie, Betsy, Betty, Bette, Eliza, Lisa, Liza, Liz</item>
+        <item>Emily, Em, Ems, Emmy</item>
+        <item>Emma, Em, Ems, Emmy</item>
+        <item>Erica, Rikki, Rikkie, Ricky</item>
+        <item>Eugene, Gene</item>
+        <item>Florence, Flo</item>
+        <item>Frances, Fran, Francie</item>
+        <item>Francis, Fran, Frank</item>
+        <item>Frederick, Fred, Freddy</item>
+        <item>Gabriel, Gabe</item>
+        <item>Geoffrey, Jeff</item>
+        <item>Gerald, Gerry</item>
+        <item>Gerard, Gerry</item>
+        <item>Gregory, Greg</item>
+        <item>Harold, Hal, Hank, Harry</item>
+        <item>Henry, Hal, Hank, Harry</item>
+        <item>Herbert, Bert, Bertie</item>
+        <item>Irving, Irv</item>
+        <item>Isabella, Isa, Izzy</item>
+        <item>Jacob, Jake</item>
+        <item>Jacqueline, Jackie</item>
+        <item>James, Jim, Jimmy, Jamie, Jock</item>
+        <item>Janet, Jan</item>
+        <item>Janice, Jan</item>
+        <item>Jason, Jay</item>
+        <item>Jefferson, Jeff</item>
+        <item>Jeffrey, Jeff</item>
+        <item>Jennifer, Jen, Jenny</item>
+        <item>Jerome, Jerry</item>
+        <item>Jessica, Jessie</item>
+        <item>John, Jack, Jacky, Johnny, Jon</item>
+        <item>Jonathan, Jon, John</item>
+        <item>Joseph, Joe, Joey</item>
+        <item>Joshua, Josh</item>
+        <item>Kaitlyn, Cat, Cate, Catie, Cath, Cathy, Kat, Kate, Katie, Kathy</item>
+        <item>Katherine, Cat, Cate, Catie, Cath, Cathy, Kat, Kate, Katie, Kathy</item>
+        <item>Kathleen, Cat, Cate, Catie, Cath, Cathy, Kat, Kate, Katie, Kathy</item>
+        <item>Katrina, Cat, Cate, Catie, Cath, Cathy, Kat, Kate, Katie, Kathy</item>
+        <item>Kenneth, Ken</item>
+        <item>Kevin, Kev</item>
+        <item>Laura, Lauri, Laurie</item>
+        <item>Lauren, Lauri, Laurie</item>
+        <item>Laurence, Larry, Lauri, Laurie</item>
+        <item>Lawrence, Larry, Lauri, Laurie</item>
+        <item>Leonard, Leo, Len, Lenny</item>
+        <item>Leopold, Leo, Len, Lenny</item>
+        <item>Madeline, Maddie, Maddy</item>
+        <item>Margaret, Marge, Marg, Maggie, Mags, Meg, Peggy</item>
+        <item>Matthew, Matt, Mattie</item>
+        <item>Maureen, Mo</item>
+        <item>Maurice, Mo</item>
+        <item>Megan, Meg</item>
+        <item>Michael, Mickey, Mick, Mike, Mikey</item>
+        <item>Morris, Mo</item>
+        <item>Nancy, Nan</item>
+        <item>Nathan, Nat, Nate</item>
+        <item>Nathaniel, Nat, Nate</item>
+        <item>Nicholas, Nick</item>
+        <item>Pamela, Pam</item>
+        <item>Patricia, Pat, Patsy, Patty, Trish, Tricia</item>
+        <item>Patrick, Paddy, Pat, Patty, Patter, Rick, Ricky</item>
+        <item>Peter, Pete</item>
+        <item>Raymond, Ray</item>
+        <item>Philip, Phil</item>
+        <item>Rebecca, Becca</item>
+        <item>Richard, Rick, Rich, Dick</item>
+        <item>Robert, Bob, Rob, Robbie, Bobby, Rab</item>
+        <item>Roberta, Bobbie</item>
+        <item>Rodney. Rod</item>
+        <item>Ronald, Ron, Ronnie</item>
+        <item>Rosemary, Rosie, Rose</item>
+        <item>Russell, Russ, Rusty</item>
+        <item>Ryan, Ry</item>
+        <item>Samantha, Sam</item>
+        <item>Samuel, Sam, Sammy</item>
+        <item>Sophia, Sophie</item>
+        <item>Stephanie, Steph, Stephie</item>
+        <item>Stephen, Steve</item>
+        <item>Steven, Steve</item>
+        <item>Stuart, Stu</item>
+        <item>Susan, Sue, Susie, Suzie</item>
+        <item>Suzanne, Sue, Susie, Suzie</item>
+        <item>Teresa, Terrie, Terry</item>
+        <item>Theodora, Teddie, Thea, Theo</item>
+        <item>Theodore, Ted, Teddy, Theo</item>
+        <item>Thomas, Tom, Thom, Tommy</item>
+        <item>Timothy, Tim, Timmy</item>
+        <item>Valerie, Val</item>
+        <item>Veronica, Ronnie, Roni, Nica, Nikki, Nikka</item>
+        <item>Victor, Vic</item>
+        <item>Victoria, Vicky, Vicki, Vickie, Tori</item>
+        <item>Vincent, Vince, Vin, Vinnie</item>
+        <item>Vivian, Vivi</item>
+        <item>Walter, Walt, Wally</item>
+        <item>Wendy, Wen, Wendel</item>
+        <item>William, Bill, Billy, Will, Willy, Liam</item>
+        <item>Yvonna, Vonna</item>
+        <item>Zachary, Zach, Zack, Zac</item>
+    </string-array>
+    <string name="common_name_prefixes">
+        1LT, 1ST, 2LT, 2ND, 3RD, ADMIRAL, CAPT, CAPTAIN, COL, CPT, DR,
+        GEN, GENERAL, LCDR, LT, LTC, LTG, LTJG, MAJ, MAJOR, MG, MR,
+        MRS, MS, PASTOR, PROF, REP, REVEREND, REV, SEN, ST
+    </string>
+    <string name="common_name_suffixes">
+        B.A., BA, D.D.S., DDS, I, II, III, IV, IX, JR, M.A., M.D, MA,
+        MD, MS, PH.D., PHD, SR, V, VI, VII, VIII, X
+    </string>
+    <string name="common_last_name_prefixes">
+        D', DE, DEL, DI, LA, LE, MC, SAN, ST, TER, VAN, VON
+    </string>
+    <string name="common_name_conjunctions">
+        &amp;, AND, OR
+    </string>
+
+    <!-- This string array should be overridden by the manufacture to present a list of carrier-id,locale,wifi-channel sets.  This is used at startup to set system defaults by checking the system property ro.carrier for the carrier-id and searching through this array -->
+    <!-- An Array of [[Carrier-ID]                     -->
+    <!--              [default-locale]                 -->
+    <!--              [default-wifi-allowed-channels]] -->
+    <string-array translatable="false" name="carrier_properties">
     </string-array>
 
      <!-- Title for the selected state of a CompoundButton. -->
@@ -1888,4 +2074,19 @@
      <!-- Title for the unselected state of a CompoundButton. -->
      <string name="accessibility_compound_button_unselected">not checked</string>
 
+     <string name="grant_credentials_permission_message_desc">The
+     listed applications are requesting permission to access the login credentials for account %s from
+     %s. Do you wish to grant this permission? If so then your answer will be remembered and you will not be prompted
+     again.</string>
+
+     <string name="grant_credentials_permission_message_with_authtokenlabel_desc">The
+     listed applications are requesting permission to access the %s login credentials for account %s from
+     %s. Do you wish to grant this permission? If so then your answer will be remembered and you will not be prompted
+     again.</string>
+
+     <string name="allow">Allow</string>
+     <string name="deny">Deny</string>
+     <string name="permission_request_notification_title">Permission Requested</string>
+     <string name="permission_request_notification_subtitle">for account %s</string>
+
 </resources>
diff --git a/core/res/res/values/styles.xml b/core/res/res/values/styles.xml
index 8eda12e..6df8b0a 100644
--- a/core/res/res/values/styles.xml
+++ b/core/res/res/values/styles.xml
@@ -687,8 +687,8 @@
 
     <style name="MediaButton">
         <item name="android:background">@android:drawable/media_button_background</item>
-        <item name="android:layout_width">71px</item>
-        <item name="android:layout_height">52px</item>
+        <item name="android:layout_width">71dip</item>
+        <item name="android:layout_height">52dip</item>
     </style>
 
     <style name="MediaButton.Previous">
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index a3579c7..20aa6e7 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -133,6 +133,7 @@
     <assign-permission name="android.permission.READ_FRAME_BUFFER" uid="shell" />
     <assign-permission name="android.permission.DEVICE_POWER" uid="shell" />
     <assign-permission name="android.permission.INSTALL_LOCATION_PROVIDER" uid="shell" />
+    <assign-permission name="android.permission.BACKUP" uid="shell" />
 
     <assign-permission name="android.permission.MODIFY_AUDIO_SETTINGS" uid="media" />
     <assign-permission name="android.permission.ACCESS_DRM" uid="media" />
@@ -147,5 +148,7 @@
             file="/system/framework/android.test.runner.jar" />
     <library name="com.android.im.plugin"
             file="/system/framework/com.android.im.plugin.jar"/>          
+    <library name="javax.obex"
+            file="/system/framework/javax.obex.jar"/>
 
 </permissions>
diff --git a/docs/html/guide/appendix/faq/commontasks.jd b/docs/html/guide/appendix/faq/commontasks.jd
index 0f89e75..259b5d1 100644
--- a/docs/html/guide/appendix/faq/commontasks.jd
+++ b/docs/html/guide/appendix/faq/commontasks.jd
@@ -427,7 +427,7 @@
         <td>Activity</td>
         <td>By setting the theme of an activity to
             {@link android.R.style#Theme_Dialog 
-            android:theme=&quot;android:style/Theme.Dialog&quot;}, 
+            android:theme=&quot;&#064;android:style/Theme.Dialog&quot;}, 
             your activity will take on
             the appearance of a normal dialog, floating on top of whatever was
             underneath it.  You usually set the theme through the
diff --git a/docs/html/guide/developing/device.jd b/docs/html/guide/developing/device.jd
index 8051678..2c42e78 100644
--- a/docs/html/guide/developing/device.jd
+++ b/docs/html/guide/developing/device.jd
@@ -145,7 +145,7 @@
               <code>SUBSYSTEM=="usb_device", SYSFS{idVendor}=="0bb4", MODE="0666"</code></p>
           </li>
           <li>Now execute:<br/>
-              <code>chmod a+rx /etc/udev/rules.d/50-android.rules</code>
+              <code>chmod a+r /etc/udev/rules.d/50-android.rules</code>
           </li>
         </ol>
 
diff --git a/docs/html/guide/developing/tools/adb.jd b/docs/html/guide/developing/tools/adb.jd
index b111047..e8c726f 100644
--- a/docs/html/guide/developing/tools/adb.jd
+++ b/docs/html/guide/developing/tools/adb.jd
@@ -313,7 +313,7 @@
 <li><code>&lt;tty&gt;</code> &mdash; the tty for PPP stream. For example <code>dev:/dev/omap_csmi_ttyl</code>. </li>
 <li><code>[parm]... </code> &mdash zero or more PPP/PPPD options, such as <code>defaultroute</code>, <code>local</code>, <code>notty</code>, etc.</li></ul>
 
-<p>Note that you should not automatically start a PDP connection. </p></td>
+<p>Note that you should not automatically start a PPP connection. </p></td>
 <td></td>
 </tr>
 
diff --git a/docs/html/guide/developing/tools/ddms.jd b/docs/html/guide/developing/tools/ddms.jd
index fa04216..f55940d 100644
--- a/docs/html/guide/developing/tools/ddms.jd
+++ b/docs/html/guide/developing/tools/ddms.jd
@@ -1,7 +1,7 @@
-page.title=Using Dalvik Debug Monitor Service (DDMS)
+page.title=Using the Dalvik Debug Monitor
 @jd:body
 
-<p>Android ships with a debugging tool called the Dalvik Debug Monitor Service (DDMS),
+<p>Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS),
     which provides port-forwarding services, screen capture on the device, thread
     and heap information on the device, logcat, process, and radio state information,
     incoming call and SMS spoofing, location data spoofing, and more. This page
@@ -106,7 +106,7 @@
         </ul>
     </li>
     <li> <strong>utime</strong> - cumulative time spent executing user code, in &quot;jiffies&quot; (usually
-        10ms). Only available under Linux. </li>
+        10ms). </li>
     <li> <strong>stime</strong> - cumulative time spent executing system code, in &quot;jiffies&quot;  (usually
         10ms). </li>
     <li> <strong>Name</strong> - the name of the thread</li>
@@ -214,14 +214,15 @@
 
 <h2 id="screen-capture">Screen Capture</h2>
 <p>You can capture screen images on the device or emulator by selecting <strong>Device</strong>
-    &gt; <strong>Screen capture...</strong> in the menu bar, or press CTRL-S.</p>
+    &gt; <strong>Screen capture...</strong> in the menu bar, or press CTRL-S.
+	Be sure to select a device first.</p>
 
 <h2 id="exploring-processes">Exploring Processes</h2>
 <p>You can see the output of <code>ps -x</code> for a specific VM by selecting <strong>Device</strong>
     &gt; <strong>Show process status</strong>... in the menu bar.</p>
 
 <h2 id="cause-a-gc-to-occur">Cause a GC to Occur</h2>
-<p>Cause garbage collection to occury by pressing the trash can button on the toolbar. </p>
+<p>Cause garbage collection to occur in the selected application by pressing the trash can button on the toolbar. </p>
 
 <h2 id="running-dumpsys-and-dumpstate">Running Dumpsys and Dumpstate on the Device (logcat)<a name="logcat" id="logcat"></a> </h2>
 <ul>
@@ -239,7 +240,7 @@
 
 <h2 id="stop-a-vitrual-machine">Stop a Virtual Machine </h2>
 <p>You can stop a virtual machine by selecting <strong>Actions</strong> &gt; <strong>Halt
-VM</strong>. Pressing this  button causes the VM to call <code>System.exit(1)</code>.</p>
+VM</strong>. Pressing this button causes the VM to call <code>Runtime.halt(1)</code>.</p>
 
 <h2 id="known-issues" style="color:#FF0000">Known issues with DDMS </h2>
 <p>DDMS has the following known limitations:</p>
diff --git a/docs/html/guide/topics/manifest/manifest-element.jd b/docs/html/guide/topics/manifest/manifest-element.jd
index a9d1090..48e598a 100644
--- a/docs/html/guide/topics/manifest/manifest-element.jd
+++ b/docs/html/guide/topics/manifest/manifest-element.jd
@@ -44,8 +44,11 @@
 
 <dt><a name="package"></a>{@code package}</dt>
 <dd>A full Java package name for the application.  The name should 
-be unique.  For example, applications published by Google could have 
-names in the form <code>com.google.app.<i>application_name</i></code>.
+be unique.  The name may contain uppercase or lowercase letters ('A'
+through 'Z'), numbers, and underscores ('_').  However, individual
+package name parts may only start with letters.  For example, applications
+published by Google could have names in the form
+<code>com.google.app.<i>application_name</i></code>.
 
 <p>
 The package name serves as a unique identifier for the application.  
diff --git a/graphics/java/android/graphics/BitmapFactory.java b/graphics/java/android/graphics/BitmapFactory.java
index c8bed24..076cd0c 100644
--- a/graphics/java/android/graphics/BitmapFactory.java
+++ b/graphics/java/android/graphics/BitmapFactory.java
@@ -18,6 +18,7 @@
 
 import android.content.res.AssetManager;
 import android.content.res.Resources;
+import android.os.MemoryFile;
 import android.util.DisplayMetrics;
 import android.util.TypedValue;
 
@@ -518,6 +519,17 @@
      * @return the decoded bitmap, or null
      */
     public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
+        try {
+            if (MemoryFile.isMemoryFile(fd)) {
+                int mappedlength = MemoryFile.getMappedSize(fd);
+                MemoryFile file = new MemoryFile(fd, mappedlength, "r");
+                InputStream is = file.getInputStream();
+                return decodeStream(is, outPadding, opts);
+            }
+        } catch (IOException ex) {
+            // invalid filedescriptor, no need to call nativeDecodeFileDescriptor()
+            return null;
+        }
         return nativeDecodeFileDescriptor(fd, outPadding, opts);
     }
 
@@ -530,7 +542,7 @@
      * @return the decoded bitmap, or null
      */
     public static Bitmap decodeFileDescriptor(FileDescriptor fd) {
-        return nativeDecodeFileDescriptor(fd, null, null);
+        return decodeFileDescriptor(fd, null, null);
     }
 
     private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage,
diff --git a/graphics/java/android/graphics/drawable/Drawable.java b/graphics/java/android/graphics/drawable/Drawable.java
index 0a0e4eb..193f399 100644
--- a/graphics/java/android/graphics/drawable/Drawable.java
+++ b/graphics/java/android/graphics/drawable/Drawable.java
@@ -102,7 +102,7 @@
     private int[] mStateSet = StateSet.WILD_CARD;
     private int mLevel = 0;
     private int mChangingConfigurations = 0;
-    private Rect mBounds = ZERO_BOUNDS_RECT;
+    private Rect mBounds = ZERO_BOUNDS_RECT;  // lazily becomes a new Rect()
     /*package*/ Callback mCallback = null;
     private boolean mVisible = true;
 
diff --git a/graphics/java/android/renderscript/Matrix.java b/graphics/java/android/renderscript/Matrix.java
new file mode 100644
index 0000000..a266d6b
--- /dev/null
+++ b/graphics/java/android/renderscript/Matrix.java
@@ -0,0 +1,192 @@
+/*
+ * 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.
+ */
+
+package android.renderscript;
+
+import java.lang.Math;
+import android.util.Log;
+
+
+/**
+ * @hide
+ *
+ **/
+public class Matrix {
+
+    public Matrix() {
+        mMat = new float[16];
+        loadIdentity();
+    }
+
+    public float get(int i, int j) {
+        return mMat[i*4 + j];
+    }
+
+    public void set(int i, int j, float v) {
+        mMat[i*4 + j] = v;
+    }
+
+    public void loadIdentity() {
+        mMat[0] = 1;
+        mMat[1] = 0;
+        mMat[2] = 0;
+        mMat[3] = 0;
+
+        mMat[4] = 0;
+        mMat[5] = 1;
+        mMat[6] = 0;
+        mMat[7] = 0;
+    
+        mMat[8] = 0;
+        mMat[9] = 0;
+        mMat[10] = 1;
+        mMat[11] = 0;
+
+        mMat[12] = 0;
+        mMat[13] = 0;
+        mMat[14] = 0;
+        mMat[15] = 1;
+    }
+
+    public void load(Matrix src) {
+        mMat = src.mMat;
+    }
+
+    public void loadRotate(float rot, float x, float y, float z) {
+        float c, s;
+        mMat[3] = 0;
+        mMat[7] = 0;
+        mMat[11]= 0;
+        mMat[12]= 0;
+        mMat[13]= 0;
+        mMat[14]= 0;
+        mMat[15]= 1;
+        rot *= (float)(java.lang.Math.PI / 180.0f);
+        c = (float)java.lang.Math.cos(rot);
+        s = (float)java.lang.Math.sin(rot);
+    
+        float len = (float)java.lang.Math.sqrt(x*x + y*y + z*z);
+        if (!(len != 1)) {
+            float recipLen = 1.f / len;
+            x *= recipLen;
+            y *= recipLen;
+            z *= recipLen;
+        }
+        float nc = 1.0f - c;
+        float xy = x * y;
+        float yz = y * z;
+        float zx = z * x;
+        float xs = x * s;
+        float ys = y * s;
+        float zs = z * s;		
+        mMat[ 0] = x*x*nc +  c;
+        mMat[ 4] =  xy*nc - zs;
+        mMat[ 8] =  zx*nc + ys;
+        mMat[ 1] =  xy*nc + zs;
+        mMat[ 5] = y*y*nc +  c;
+        mMat[ 9] =  yz*nc - xs;
+        mMat[ 2] =  zx*nc - ys;
+        mMat[ 6] =  yz*nc + xs;
+        mMat[10] = z*z*nc +  c;
+    }
+
+    public void loadScale(float x, float y, float z) {
+        loadIdentity();
+        mMat[0] = x;
+        mMat[5] = y;
+        mMat[10] = z;
+    }
+    
+    public void loadTranslate(float x, float y, float z) {
+        loadIdentity();
+        mMat[12] = x;
+        mMat[13] = y;
+        mMat[14] = z;
+    }
+
+    public void loadMultiply(Matrix lhs, Matrix rhs) {
+        for (int i=0 ; i<4 ; i++) {
+            float ri0 = 0;
+            float ri1 = 0;
+            float ri2 = 0;
+            float ri3 = 0;
+            for (int j=0 ; j<4 ; j++) {
+                float rhs_ij = rhs.get(i,j);
+                ri0 += lhs.get(j,0) * rhs_ij;
+                ri1 += lhs.get(j,1) * rhs_ij;
+                ri2 += lhs.get(j,2) * rhs_ij;
+                ri3 += lhs.get(j,3) * rhs_ij;
+            }
+            set(i,0, ri0);
+            set(i,1, ri1);
+            set(i,2, ri2);
+            set(i,3, ri3);
+        }
+    }
+
+    public void loadOrtho(float l, float r, float b, float t, float n, float f) {
+        loadIdentity();
+        mMat[0] = 2 / (r - l);
+        mMat[5] = 2 / (t - b);
+        mMat[10]= -2 / (f - n);
+        mMat[12]= -(r + l) / (r - l);
+        mMat[13]= -(t + b) / (t - b);
+        mMat[14]= -(f + n) / (f - n);
+    }
+
+    public void loadFrustum(float l, float r, float b, float t, float n, float f) {
+        loadIdentity();
+        mMat[0] = 2 * n / (r - l);
+        mMat[5] = 2 * n / (t - b);
+        mMat[8] = (r + l) / (r - l);
+        mMat[9] = (t + b) / (t - b);
+        mMat[10]= -(f + n) / (f - n);
+        mMat[11]= -1;
+        mMat[14]= -2*f*n / (f - n);
+        mMat[15]= 0;
+    }
+
+    public void multiply(Matrix rhs) {
+        Matrix tmp = new Matrix();
+        tmp.loadMultiply(this, rhs);
+        load(tmp);
+    }
+    public void rotate(float rot, float x, float y, float z) {
+        Matrix tmp = new Matrix();
+        tmp.loadRotate(rot, x, y, z);
+        multiply(tmp);
+    }
+    public void scale(float x, float y, float z) {
+        Matrix tmp = new Matrix();
+        tmp.loadScale(x, y, z);
+        multiply(tmp);
+    }
+    public void translate(float x, float y, float z) {
+        Matrix tmp = new Matrix();
+        tmp.loadTranslate(x, y, z);
+        multiply(tmp);
+    }
+
+
+
+    float[] mMat;
+
+}
+
+
+
+
+
diff --git a/graphics/java/android/renderscript/ProgramVertexAlloc.java b/graphics/java/android/renderscript/ProgramVertexAlloc.java
new file mode 100644
index 0000000..82bcc30
--- /dev/null
+++ b/graphics/java/android/renderscript/ProgramVertexAlloc.java
@@ -0,0 +1,116 @@
+/*
+ * 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.
+ */
+
+package android.renderscript;
+
+import java.lang.Math;
+import android.util.Log;
+
+
+/**
+ * @hide
+ *
+ **/
+public class ProgramVertexAlloc {
+    public static final int MODELVIEW_OFFSET = 0;
+    public static final int PROJECTION_OFFSET = 16;
+    public static final int TEXTURE_OFFSET = 32;
+
+    Matrix mModel;
+    Matrix mProjection;
+    Matrix mTexture;
+
+    public RenderScript.Allocation mAlloc;
+
+    public ProgramVertexAlloc(RenderScript rs) {
+        mModel = new Matrix();
+        mProjection = new Matrix();
+        mTexture = new Matrix();
+
+        mAlloc = rs.allocationCreatePredefSized(
+            RenderScript.ElementPredefined.USER_FLOAT, 
+            48);
+
+        mAlloc.subData1D(MODELVIEW_OFFSET, 16, mModel.mMat);
+        mAlloc.subData1D(PROJECTION_OFFSET, 16, mProjection.mMat);
+        mAlloc.subData1D(TEXTURE_OFFSET, 16, mTexture.mMat);
+    }
+
+    public void loadModelview(Matrix m) {
+        mModel = m;
+        mAlloc.subData1D(MODELVIEW_OFFSET, 16, m.mMat);
+    }
+
+    public void loadProjection(Matrix m) {
+        mProjection = m;
+        mAlloc.subData1D(PROJECTION_OFFSET, 16, m.mMat);
+    }
+
+    public void loadTexture(Matrix m) {
+        mTexture = m;
+        mAlloc.subData1D(TEXTURE_OFFSET, 16, m.mMat);
+    }
+
+    public void setupOrthoWindow(int w, int h) {
+        mProjection.loadOrtho(0,w, h,0, -1,1);
+        mAlloc.subData1D(PROJECTION_OFFSET, 16, mProjection.mMat);
+    }
+
+    public void setupOrthoNormalized(int w, int h) {
+        // range -1,1 in the narrow axis.
+        if(w > h) {
+            float aspect = ((float)w) / h;
+            mProjection.loadOrtho(-aspect,aspect,  -1,1,  -1,1);
+        } else {
+            float aspect = ((float)h) / w;
+            mProjection.loadOrtho(-1,1, -aspect,aspect,  -1,1);
+        }
+        mAlloc.subData1D(PROJECTION_OFFSET, 16, mProjection.mMat);
+    }
+
+    public void setupProjectionNormalized(int w, int h) {
+        // range -1,1 in the narrow axis at z = 0.
+        Matrix m1 = new Matrix();
+        Matrix m2 = new Matrix();
+
+        if(w > h) {
+            float aspect = ((float)w) / h;
+            m1.loadFrustum(-aspect,aspect,  -1,1,  1,100);
+        } else {
+            float aspect = ((float)h) / w;
+            m1.loadFrustum(-1,1, -aspect,aspect, 1,100);
+        }
+
+        m2.loadRotate(180, 0, 1, 0);
+        m1.loadMultiply(m1, m2);
+
+        m2.loadScale(-2, 2, 1);
+        m1.loadMultiply(m1, m2);
+
+        m2.loadTranslate(0, 0, 2);
+        m1.loadMultiply(m1, m2);
+
+        mProjection = m1;
+        mAlloc.subData1D(PROJECTION_OFFSET, 16, mProjection.mMat);
+    }
+
+}
+
+
+
+
+
+
diff --git a/graphics/java/android/renderscript/RSSurfaceView.java b/graphics/java/android/renderscript/RSSurfaceView.java
new file mode 100644
index 0000000..f024bf6
--- /dev/null
+++ b/graphics/java/android/renderscript/RSSurfaceView.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2008 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.renderscript;
+
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.concurrent.Semaphore;
+
+import android.content.Context;
+import android.os.Handler;
+import android.os.Message;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.util.Log;
+import android.view.Surface;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+
+/**
+ * @hide
+ *
+ **/
+public class RSSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
+    private SurfaceHolder mSurfaceHolder;
+
+    /**
+     * Standard View constructor. In order to render something, you
+     * must call {@link #setRenderer} to register a renderer.
+     */
+    public RSSurfaceView(Context context) {
+        super(context);
+        init();
+        Log.v(RenderScript.LOG_TAG, "RSSurfaceView");
+    }
+
+    /**
+     * Standard View constructor. In order to render something, you
+     * must call {@link #setRenderer} to register a renderer.
+     */
+    public RSSurfaceView(Context context, AttributeSet attrs) {
+        super(context, attrs);
+        init();
+        Log.v(RenderScript.LOG_TAG, "RSSurfaceView");
+    }
+
+    private void init() {
+        // Install a SurfaceHolder.Callback so we get notified when the
+        // underlying surface is created and destroyed
+        SurfaceHolder holder = getHolder();
+        holder.addCallback(this);
+        holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
+    }
+
+    /**
+     * This method is part of the SurfaceHolder.Callback interface, and is
+     * not normally called or subclassed by clients of RSSurfaceView.
+     */
+    public void surfaceCreated(SurfaceHolder holder) {
+        Log.v(RenderScript.LOG_TAG, "surfaceCreated");
+        mSurfaceHolder = holder;
+        //mGLThread.surfaceCreated();
+    }
+
+    /**
+     * This method is part of the SurfaceHolder.Callback interface, and is
+     * not normally called or subclassed by clients of RSSurfaceView.
+     */
+    public void surfaceDestroyed(SurfaceHolder holder) {
+        // Surface will be destroyed when we return
+        Log.v(RenderScript.LOG_TAG, "surfaceDestroyed");
+        //mGLThread.surfaceDestroyed();
+    }
+
+    /**
+     * This method is part of the SurfaceHolder.Callback interface, and is
+     * not normally called or subclassed by clients of RSSurfaceView.
+     */
+    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
+        Log.v(RenderScript.LOG_TAG, "surfaceChanged");
+
+        //mGLThread.onWindowResize(w, h);
+    }
+
+    /**
+     * Inform the view that the activity is paused. The owner of this view must
+     * call this method when the activity is paused. Calling this method will
+     * pause the rendering thread.
+     * Must not be called before a renderer has been set.
+     */
+    public void onPause() {
+        Log.v(RenderScript.LOG_TAG, "onPause");
+        //mGLThread.onPause();
+    }
+
+    /**
+     * Inform the view that the activity is resumed. The owner of this view must
+     * call this method when the activity is resumed. Calling this method will
+     * recreate the OpenGL display and resume the rendering
+     * thread.
+     * Must not be called before a renderer has been set.
+     */
+    public void onResume() {
+        Log.v(RenderScript.LOG_TAG, "onResume");
+        //mGLThread.onResume();
+    }
+
+    /**
+     * Queue a runnable to be run on the GL rendering thread. This can be used
+     * to communicate with the Renderer on the rendering thread.
+     * Must not be called before a renderer has been set.
+     * @param r the runnable to be run on the GL rendering thread.
+     */
+    public void queueEvent(Runnable r) {
+        Log.v(RenderScript.LOG_TAG, "queueEvent");
+        //mGLThread.queueEvent(r);
+    }
+
+    /**
+     * This method is used as part of the View class and is not normally
+     * called or subclassed by clients of RSSurfaceView.
+     * Must not be called before a renderer has been set.
+     */
+    @Override
+    protected void onDetachedFromWindow() {
+        super.onDetachedFromWindow();
+        //mGLThread.requestExitAndWait();
+    }
+
+    // ----------------------------------------------------------------------
+
+    public RenderScript createRenderScript() {
+        Log.v(RenderScript.LOG_TAG, "createRenderScript 1");
+        Surface sur = null;
+        while ((sur == null) || (mSurfaceHolder == null)) {
+            sur = getHolder().getSurface();
+        }
+        Log.v(RenderScript.LOG_TAG, "createRenderScript 2");
+        RenderScript rs = new RenderScript(sur);
+        Log.v(RenderScript.LOG_TAG, "createRenderScript 3 rs");
+        return rs;
+    }
+
+}
+
diff --git a/graphics/java/android/renderscript/RenderScript.java b/graphics/java/android/renderscript/RenderScript.java
new file mode 100644
index 0000000..f829b08
--- /dev/null
+++ b/graphics/java/android/renderscript/RenderScript.java
@@ -0,0 +1,1003 @@
+/*
+ * Copyright (C) 2008 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.
+ */
+
+/**
+ * @hide
+ *
+ **/
+package android.renderscript;
+
+import java.io.InputStream;
+import java.io.IOException;
+
+import android.os.Bundle;
+import android.content.res.Resources;
+import android.util.Log;
+import android.util.Config;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.Window;
+import android.view.View;
+import android.view.Surface;
+import android.graphics.Bitmap;
+import android.graphics.Color;
+
+/**
+ * @hide
+ *
+ **/
+public class RenderScript {
+    static final String LOG_TAG = "libRS_jni";
+    private static final boolean DEBUG  = false;
+    private static final boolean LOG_ENABLED = DEBUG ? Config.LOGD : Config.LOGV;
+
+
+
+     /*
+     * We use a class initializer to allow the native code to cache some
+     * field offsets.
+     */
+    private static boolean sInitialized;
+    native private static void _nInit();
+
+    static {
+        sInitialized = false;
+        try {
+            System.loadLibrary("rs_jni");
+            _nInit();
+            sInitialized = true;
+        } catch (UnsatisfiedLinkError e) {
+            Log.d(LOG_TAG, "RenderScript JNI library not found!");
+        }
+    }
+
+    native private int  nDeviceCreate();
+    native private void nDeviceDestroy(int dev);
+    native private int  nContextCreate(int dev, Surface sur, int ver);
+    native private void nContextDestroy(int con);
+
+    //void rsContextBindSampler (uint32_t slot, RsSampler sampler);
+    //void rsContextBindRootScript (RsScript sampler);
+    native private void nContextBindRootScript(int script);
+    native private void nContextBindSampler(int sampler, int slot);
+    native private void nContextBindProgramFragmentStore(int pfs);
+    native private void nContextBindProgramFragment(int pf);
+    native private void nContextBindProgramVertex(int pf);
+
+    native private void nAssignName(int obj, byte[] name);
+    native private int  nFileOpen(byte[] name);
+
+    native private void nElementBegin();
+    native private void nElementAddPredefined(int predef);
+    native private void nElementAdd(int kind, int type, int norm, int bits);
+    native private int  nElementCreate();
+    native private int  nElementGetPredefined(int predef);
+    native private void nElementDestroy(int obj);
+
+    native private void nTypeBegin(int elementID);
+    native private void nTypeAdd(int dim, int val);
+    native private int  nTypeCreate();
+    native private void nTypeDestroy(int id);
+
+    native private int  nAllocationCreateTyped(int type);
+    native private int  nAllocationCreatePredefSized(int predef, int count);
+    native private int  nAllocationCreateSized(int elem, int count);
+    native private int  nAllocationCreateFromBitmap(int dstFmt, boolean genMips, Bitmap bmp);
+
+    native private void nAllocationUploadToTexture(int alloc, int baseMioLevel);
+    native private void nAllocationDestroy(int alloc);
+    native private void nAllocationData(int id, int[] d);
+    native private void nAllocationData(int id, float[] d);
+    native private void nAllocationSubData1D(int id, int off, int count, int[] d);
+    native private void nAllocationSubData1D(int id, int off, int count, float[] d);
+    native private void nAllocationSubData2D(int id, int xoff, int yoff, int w, int h, int[] d);
+    native private void nAllocationSubData2D(int id, int xoff, int yoff, int w, int h, float[] d);
+
+    native private void nTriangleMeshDestroy(int id);
+    native private void nTriangleMeshBegin(int vertex, int index);
+    native private void nTriangleMeshAddVertex_XY (float x, float y);
+    native private void nTriangleMeshAddVertex_XYZ (float x, float y, float z);
+    native private void nTriangleMeshAddVertex_XY_ST (float x, float y, float s, float t);
+    native private void nTriangleMeshAddVertex_XYZ_ST (float x, float y, float z, float s, float t);
+    native private void nTriangleMeshAddVertex_XYZ_ST_NORM (float x, float y, float z, float s, float t, float nx, float ny, float nz);
+    native private void nTriangleMeshAddTriangle(int i1, int i2, int i3);
+    native private int  nTriangleMeshCreate();
+
+    native private void nAdapter1DDestroy(int id);
+    native private void nAdapter1DBindAllocation(int ad, int alloc);
+    native private void nAdapter1DSetConstraint(int ad, int dim, int value);
+    native private void nAdapter1DData(int ad, int[] d);
+    native private void nAdapter1DSubData(int ad, int off, int count, int[] d);
+    native private void nAdapter1DData(int ad, float[] d);
+    native private void nAdapter1DSubData(int ad, int off, int count, float[] d);
+    native private int  nAdapter1DCreate();
+
+    native private void nScriptDestroy(int script);
+    native private void nScriptBindAllocation(int vtm, int alloc, int slot);
+    native private void nScriptCBegin();
+    native private void nScriptCSetClearColor(float r, float g, float b, float a);
+    native private void nScriptCSetClearDepth(float depth);
+    native private void nScriptCSetClearStencil(int stencil);
+    native private void nScriptCAddType(int type);
+    native private void nScriptCSetRoot(boolean isRoot);
+    native private void nScriptCSetScript(byte[] script, int offset, int length);
+    native private int  nScriptCCreate();
+
+    native private void nSamplerDestroy(int sampler);
+    native private void nSamplerBegin();
+    native private void nSamplerSet(int param, int value);
+    native private int  nSamplerCreate();
+
+    native private void nProgramFragmentStoreBegin(int in, int out);
+    native private void nProgramFragmentStoreDepthFunc(int func);
+    native private void nProgramFragmentStoreDepthMask(boolean enable);
+    native private void nProgramFragmentStoreColorMask(boolean r, boolean g, boolean b, boolean a);
+    native private void nProgramFragmentStoreBlendFunc(int src, int dst);
+    native private void nProgramFragmentStoreDither(boolean enable);
+    native private int  nProgramFragmentStoreCreate();
+    native private void nProgramFragmentStoreDestroy(int pgm);
+
+    native private void nProgramFragmentBegin(int in, int out);
+    native private void nProgramFragmentBindTexture(int vpf, int slot, int a);
+    native private void nProgramFragmentBindSampler(int vpf, int slot, int s);
+    native private void nProgramFragmentSetType(int slot, int vt);
+    native private void nProgramFragmentSetEnvMode(int slot, int env);
+    native private void nProgramFragmentSetTexEnable(int slot, boolean enable);
+    native private int  nProgramFragmentCreate();
+    native private void nProgramFragmentDestroy(int pgm);
+
+    native private void nProgramVertexDestroy(int pv);
+    native private void nProgramVertexBindAllocation(int pv, int slot, int mID);
+    native private void nProgramVertexBegin(int inID, int outID);
+    native private void nProgramVertexSetType(int slot, int mID);
+    native private void nProgramVertexSetTextureMatrixEnable(boolean enable);
+    native private void nProgramVertexAddLight(int id);
+    native private int  nProgramVertexCreate();
+
+    native private void nLightBegin();
+    native private void nLightSetIsMono(boolean isMono);
+    native private void nLightSetIsLocal(boolean isLocal);
+    native private int  nLightCreate();
+    native private void nLightDestroy(int l);
+    native private void nLightSetColor(int l, float r, float g, float b);
+    native private void nLightSetPosition(int l, float x, float y, float z);
+
+
+    private int     mDev;
+    private int     mContext;
+    private Surface mSurface;
+
+
+
+    ///////////////////////////////////////////////////////////////////////////////////
+    //
+
+    RenderScript(Surface sur) {
+        mSurface = sur;
+        mDev = nDeviceCreate();
+        mContext = nContextCreate(mDev, mSurface, 0);
+    }
+
+    private class BaseObj {
+        BaseObj() {
+            mID = 0;
+        }
+
+        public int getID() {
+            return mID;
+        }
+
+        int mID;
+        String mName;
+
+        public void setName(String s) throws IllegalStateException, IllegalArgumentException
+        {
+            if(s.length() < 1) {
+                throw new IllegalArgumentException("setName does not accept a zero length string.");
+            }
+            if(mName != null) {
+                throw new IllegalArgumentException("setName object already has a name.");
+            }
+
+            try {
+                byte[] bytes = s.getBytes("UTF-8");
+                nAssignName(mID, bytes);
+                mName = s;
+            } catch (java.io.UnsupportedEncodingException e) {
+                throw new RuntimeException(e);
+            }
+        }
+
+        protected void finalize() throws Throwable
+        {
+            if (mID != 0) {
+                Log.v(LOG_TAG,
+                      "Element finalized without having released the RS reference.");
+            }
+            super.finalize();
+        }
+    }
+
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // Element
+
+    public enum ElementPredefined {
+        USER_U8 (0),
+        USER_I8 (1),
+        USER_U16 (2),
+        USER_I16 (3),
+        USER_U32 (4),
+        USER_I32 (5),
+        USER_FLOAT (6),
+
+        A_8                (7),
+        RGB_565            (8),
+        RGB_888            (11),
+        RGBA_5551          (9),
+        RGBA_4444          (10),
+        RGBA_8888          (12),
+
+        INDEX_16           (13),
+        INDEX_32           (14),
+        XY_F32             (15),
+        XYZ_F32            (16),
+        ST_XY_F32          (17),
+        ST_XYZ_F32         (18),
+        NORM_XYZ_F32       (19),
+        NORM_ST_XYZ_F32    (20);
+
+        int mID;
+        ElementPredefined(int id) {
+            mID = id;
+        }
+    }
+
+    public enum DataType {
+        FLOAT (0),
+        UNSIGNED (1),
+        SIGNED (2);
+
+        int mID;
+        DataType(int id) {
+            mID = id;
+        }
+    }
+
+    public enum DataKind {
+        USER (0),
+        RED (1),
+        GREEN (2),
+        BLUE (3),
+        ALPHA (4),
+        LUMINANCE (5),
+        INTENSITY (6),
+        X (7),
+        Y (8),
+        Z (9),
+        W (10),
+        S (11),
+        T (12),
+        Q (13),
+        R (14),
+        NX (15),
+        NY (16),
+        NZ (17),
+        INDEX (18);
+
+        int mID;
+        DataKind(int id) {
+            mID = id;
+        }
+    }
+
+    public enum DepthFunc {
+        ALWAYS (0),
+        LESS (1),
+        LEQUAL (2),
+        GREATER (3),
+        GEQUAL (4),
+        EQUAL (5),
+        NOTEQUAL (6);
+
+        int mID;
+        DepthFunc(int id) {
+            mID = id;
+        }
+    }
+
+    public enum BlendSrcFunc {
+        ZERO (0),
+        ONE (1),
+        DST_COLOR (2),
+        ONE_MINUS_DST_COLOR (3),
+        SRC_ALPHA (4),
+        ONE_MINUS_SRC_ALPHA (5),
+        DST_ALPHA (6),
+        ONE_MINUS_DST_ALPA (7),
+        SRC_ALPHA_SATURATE (8);
+
+        int mID;
+        BlendSrcFunc(int id) {
+            mID = id;
+        }
+    }
+
+    public enum BlendDstFunc {
+        ZERO (0),
+        ONE (1),
+        SRC_COLOR (2),
+        ONE_MINUS_SRC_COLOR (3),
+        SRC_ALPHA (4),
+        ONE_MINUS_SRC_ALPHA (5),
+        DST_ALPHA (6),
+        ONE_MINUS_DST_ALPA (7);
+
+        int mID;
+        BlendDstFunc(int id) {
+            mID = id;
+        }
+    }
+
+    public enum EnvMode {
+        REPLACE (0),
+        MODULATE (1),
+        DECAL (2);
+
+        int mID;
+        EnvMode(int id) {
+            mID = id;
+        }
+    }
+
+    public enum SamplerParam {
+        FILTER_MIN (0),
+        FILTER_MAG (1),
+        WRAP_MODE_S (2),
+        WRAP_MODE_T (3),
+        WRAP_MODE_R (4);
+
+        int mID;
+        SamplerParam(int id) {
+            mID = id;
+        }
+    }
+
+    public enum SamplerValue {
+        NEAREST (0),
+        LINEAR (1),
+        LINEAR_MIP_LINEAR (2),
+        WRAP (3),
+        CLAMP (4);
+
+        int mID;
+        SamplerValue(int id) {
+            mID = id;
+        }
+    }
+
+
+
+    public class Element extends BaseObj {
+        Element(int id) {
+            mID = id;
+        }
+
+        public void estroy() {
+            nElementDestroy(mID);
+            mID = 0;
+        }
+    }
+
+    public void elementBegin() {
+        nElementBegin();
+    }
+
+    public void elementAddPredefined(ElementPredefined e) {
+        nElementAddPredefined(e.mID);
+    }
+
+    public void elementAdd(DataType dt, DataKind dk, boolean isNormalized, int bits) {
+        int norm = 0;
+        if (isNormalized) {
+            norm = 1;
+        }
+        nElementAdd(dt.mID, dk.mID, norm, bits);
+    }
+
+    public Element elementCreate() {
+        int id = nElementCreate();
+        return new Element(id);
+    }
+
+    public Element elementGetPredefined(ElementPredefined predef) {
+        int id = nElementGetPredefined(predef.mID);
+        return new Element(id);
+    }
+
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // Type
+
+    public enum Dimension {
+        X (0),
+        Y (1),
+        Z (2),
+        LOD (3),
+        FACE (4),
+        ARRAY_0 (100);
+
+        int mID;
+        Dimension(int id) {
+            mID = id;
+        }
+    }
+
+    public class Type extends BaseObj {
+        Type(int id) {
+            mID = id;
+        }
+
+        public void destroy() {
+            nTypeDestroy(mID);
+            mID = 0;
+        }
+    }
+
+    public void typeBegin(Element e) {
+        nTypeBegin(e.mID);
+    }
+
+    public void typeAdd(Dimension d, int value) {
+        nTypeAdd(d.mID, value);
+    }
+
+    public Type typeCreate() {
+        int id = nTypeCreate();
+        return new Type(id);
+    }
+
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // Allocation
+
+    public class Allocation extends BaseObj {
+        Allocation(int id) {
+            mID = id;
+        }
+
+        public void uploadToTexture(int baseMipLevel) {
+            nAllocationUploadToTexture(mID, baseMipLevel);
+        }
+
+        public void destroy() {
+            nAllocationDestroy(mID);
+            mID = 0;
+        }
+
+        public void data(int[] d) {
+            nAllocationData(mID, d);
+        }
+
+        public void data(float[] d) {
+            nAllocationData(mID, d);
+        }
+
+        public void subData1D(int off, int count, int[] d) {
+            nAllocationSubData1D(mID, off, count, d);
+        }
+
+        public void subData1D(int off, int count, float[] d) {
+            nAllocationSubData1D(mID, off, count, d);
+        }
+
+        public void subData2D(int xoff, int yoff, int w, int h, int[] d) {
+            nAllocationSubData2D(mID, xoff, yoff, w, h, d);
+        }
+
+        public void subData2D(int xoff, int yoff, int w, int h, float[] d) {
+            nAllocationSubData2D(mID, xoff, yoff, w, h, d);
+        }
+    }
+
+    public Allocation allocationCreateTyped(Type type) {
+        int id = nAllocationCreateTyped(type.mID);
+        return new Allocation(id);
+    }
+
+    public Allocation allocationCreatePredefSized(ElementPredefined e, int count) {
+        int id = nAllocationCreatePredefSized(e.mID, count);
+        return new Allocation(id);
+    }
+
+    public Allocation allocationCreateSized(Element e, int count) {
+        int id = nAllocationCreateSized(e.mID, count);
+        return new Allocation(id);
+    }
+
+    public Allocation allocationCreateFromBitmap(Bitmap b, ElementPredefined dstFmt, boolean genMips) {
+        int id = nAllocationCreateFromBitmap(dstFmt.mID, genMips, b); 
+        return new Allocation(id);
+    }
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // Adapter1D
+
+    public class Adapter1D extends BaseObj {
+        Adapter1D(int id) {
+            mID = id;
+        }
+
+        public void destroy() {
+            nAdapter1DDestroy(mID);
+            mID = 0;
+        }
+
+        public void bindAllocation(Allocation a) {
+            nAdapter1DBindAllocation(mID, a.mID);
+        }
+
+        public void setConstraint(Dimension dim, int value) {
+            nAdapter1DSetConstraint(mID, dim.mID, value);
+        }
+
+        public void data(int[] d) {
+            nAdapter1DData(mID, d);
+        }
+
+        public void subData(int off, int count, int[] d) {
+            nAdapter1DSubData(mID, off, count, d);
+        }
+
+        public void data(float[] d) {
+            nAdapter1DData(mID, d);
+        }
+
+        public void subData(int off, int count, float[] d) {
+            nAdapter1DSubData(mID, off, count, d);
+        }
+    }
+
+    public Adapter1D adapter1DCreate() {
+        int id = nAdapter1DCreate();
+        return new Adapter1D(id);
+    }
+
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // Triangle Mesh
+
+    public class TriangleMesh extends BaseObj {
+        TriangleMesh(int id) {
+            mID = id;
+        }
+
+        public void destroy() {
+            nTriangleMeshDestroy(mID);
+            mID = 0;
+        }
+    }
+
+    public void triangleMeshBegin(Element vertex, Element index) {
+        nTriangleMeshBegin(vertex.mID, index.mID);
+    }
+
+    public void triangleMeshAddVertex_XY(float x, float y) {
+        nTriangleMeshAddVertex_XY(x, y);
+    }
+
+    public void triangleMeshAddVertex_XYZ(float x, float y, float z) {
+        nTriangleMeshAddVertex_XYZ(x, y, z);
+    }
+
+    public void triangleMeshAddVertex_XY_ST(float x, float y, float s, float t) {
+        nTriangleMeshAddVertex_XY_ST(x, y, s, t);
+    }
+
+    public void triangleMeshAddVertex_XYZ_ST(float x, float y, float z, float s, float t) {
+        nTriangleMeshAddVertex_XYZ_ST(x, y, z, s, t);
+    }
+
+    public void triangleMeshAddVertex_XYZ_ST_NORM(float x, float y, float z, float s, float t, float nx, float ny, float nz) {
+        nTriangleMeshAddVertex_XYZ_ST_NORM(x, y, z, s, t, nx, ny, nz);
+    }
+
+    public void triangleMeshAddTriangle(int i1, int i2, int i3) {
+        nTriangleMeshAddTriangle(i1, i2, i3);
+    }
+
+    public TriangleMesh triangleMeshCreate() {
+        int id = nTriangleMeshCreate();
+        return new TriangleMesh(id);
+    }
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // Script
+
+    public class Script extends BaseObj {
+        Script(int id) {
+            mID = id;
+        }
+
+        public void destroy() {
+            nScriptDestroy(mID);
+            mID = 0;
+        }
+
+        public void bindAllocation(Allocation va, int slot) {
+            nScriptBindAllocation(mID, va.mID, slot);
+        }
+    }
+
+    public void scriptCBegin() {
+        nScriptCBegin();
+    }
+
+    public void scriptCSetClearColor(float r, float g, float b, float a) {
+        nScriptCSetClearColor(r, g, b, a);
+    }
+
+    public void scriptCSetClearDepth(float d) {
+        nScriptCSetClearDepth(d);
+    }
+
+    public void scriptCSetClearStencil(int stencil) {
+        nScriptCSetClearStencil(stencil);
+    }
+
+    public void scriptCAddType(Type t) {
+        nScriptCAddType(t.mID);
+    }
+
+    public void scriptCSetRoot(boolean r) {
+        nScriptCSetRoot(r);
+    }
+
+    public void scriptCSetScript(String s) {
+        try {
+            byte[] bytes = s.getBytes("UTF-8");
+            nScriptCSetScript(bytes, 0, bytes.length);
+        } catch (java.io.UnsupportedEncodingException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public void scriptCSetScript(Resources resources, int id) {
+        InputStream is = resources.openRawResource(id);
+        try {
+            try {
+                scriptCSetScript(is);
+            } finally {
+                is.close();
+            }
+        } catch(IOException e) {
+            throw new Resources.NotFoundException();
+        }
+    }
+
+    public void  scriptCSetScript(InputStream is) throws IOException {
+        byte[] buf = new byte[1024];
+        int currentPos = 0;
+        while(true) {
+            int bytesLeft = buf.length - currentPos;
+            if (bytesLeft == 0) {
+                byte[] buf2 = new byte[buf.length * 2];
+                System.arraycopy(buf, 0, buf2, 0, buf.length);
+                buf = buf2;
+                bytesLeft = buf.length - currentPos;
+            }
+            int bytesRead = is.read(buf, currentPos, bytesLeft);
+            if (bytesRead <= 0) {
+                break;
+            }
+            currentPos += bytesRead;
+        }
+        nScriptCSetScript(buf, 0, currentPos);
+    }
+
+    public Script scriptCCreate() {
+        int id = nScriptCCreate();
+        return new Script(id);
+    }
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // ProgramVertex
+
+    public class ProgramVertex extends BaseObj {
+        ProgramVertex(int id) {
+            mID = id;
+        }
+
+        public void destroy() {
+            nProgramVertexDestroy(mID);
+            mID = 0;
+        }
+
+        public void bindAllocation(int slot, Allocation va) {
+            nProgramVertexBindAllocation(mID, slot, va.mID);
+        }
+    }
+
+    public void programVertexBegin(Element in, Element out) {
+        int inID = 0;
+        int outID = 0;
+        if (in != null) {
+            inID = in.mID;
+        }
+        if (out != null) {
+            outID = out.mID;
+        }
+        nProgramVertexBegin(inID, outID);
+    }
+
+    public void programVertexSetType(int slot, Type t) {
+        nProgramVertexSetType(slot, t.mID);
+    }
+
+    public void programVertexSetTextureMatrixEnable(boolean enable) {
+        nProgramVertexSetTextureMatrixEnable(enable);
+    }
+
+    public void programVertexAddLight(Light l) {
+        nProgramVertexAddLight(l.mID);
+    }
+
+    public ProgramVertex programVertexCreate() {
+        int id = nProgramVertexCreate();
+        return new ProgramVertex(id);
+    }
+
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // ProgramFragmentStore
+
+    public class ProgramFragmentStore extends BaseObj {
+        ProgramFragmentStore(int id) {
+            mID = id;
+        }
+
+        public void destroy() {
+            nProgramFragmentStoreDestroy(mID);
+            mID = 0;
+        }
+    }
+
+    public void programFragmentStoreBegin(Element in, Element out) {
+        int inID = 0;
+        int outID = 0;
+        if (in != null) {
+            inID = in.mID;
+        }
+        if (out != null) {
+            outID = out.mID;
+        }
+        nProgramFragmentStoreBegin(inID, outID);
+    }
+
+    public void programFragmentStoreDepthFunc(DepthFunc func) {
+        nProgramFragmentStoreDepthFunc(func.mID);
+    }
+
+    public void programFragmentStoreDepthMask(boolean enable) {
+        nProgramFragmentStoreDepthMask(enable);
+    }
+
+    public void programFragmentStoreColorMask(boolean r, boolean g, boolean b, boolean a) {
+        nProgramFragmentStoreColorMask(r,g,b,a);
+    }
+
+    public void programFragmentStoreBlendFunc(BlendSrcFunc src, BlendDstFunc dst) {
+        nProgramFragmentStoreBlendFunc(src.mID, dst.mID);
+    }
+
+    public void programFragmentStoreDitherEnable(boolean enable) {
+        nProgramFragmentStoreDither(enable);
+    }
+
+    public ProgramFragmentStore programFragmentStoreCreate() {
+        int id = nProgramFragmentStoreCreate();
+        return new ProgramFragmentStore(id);
+    }
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // ProgramFragment
+
+    public class ProgramFragment extends BaseObj {
+        ProgramFragment(int id) {
+            mID = id;
+        }
+
+        public void destroy() {
+            nProgramFragmentDestroy(mID);
+            mID = 0;
+        }
+
+        public void bindTexture(Allocation va, int slot) {
+            nProgramFragmentBindTexture(mID, slot, va.mID);
+        }
+
+        public void bindSampler(Sampler vs, int slot) {
+            nProgramFragmentBindSampler(mID, slot, vs.mID);
+        }
+    }
+
+    public void programFragmentBegin(Element in, Element out) {
+        int inID = 0;
+        int outID = 0;
+        if (in != null) {
+            inID = in.mID;
+        }
+        if (out != null) {
+            outID = out.mID;
+        }
+        nProgramFragmentBegin(inID, outID);
+    }
+
+    public void programFragmentSetType(int slot, Type t) {
+        nProgramFragmentSetType(slot, t.mID);
+    }
+
+    public void programFragmentSetType(int slot, EnvMode t) {
+        nProgramFragmentSetEnvMode(slot, t.mID);
+    }
+
+    public void programFragmentSetTexEnable(int slot, boolean enable) {
+        nProgramFragmentSetTexEnable(slot, enable);
+    }
+
+    public void programFragmentSetTexEnvMode(int slot, EnvMode env) {
+        nProgramFragmentSetEnvMode(slot, env.mID);
+    }
+
+    public ProgramFragment programFragmentCreate() {
+        int id = nProgramFragmentCreate();
+        return new ProgramFragment(id);
+    }
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // Sampler
+
+    public class Sampler extends BaseObj {
+        Sampler(int id) {
+            mID = id;
+        }
+
+        public void destroy() {
+            nSamplerDestroy(mID);
+            mID = 0;
+        }
+    }
+
+    public void samplerBegin() {
+        nSamplerBegin();
+    }
+
+    public void samplerSet(SamplerParam p, SamplerValue v) {
+        nSamplerSet(p.mID, v.mID);
+    }
+
+    public Sampler samplerCreate() {
+        int id = nSamplerCreate();
+        return new Sampler(id);
+    }
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // Light
+
+    public class Light extends BaseObj {
+        Light(int id) {
+            mID = id;
+        }
+
+        public void destroy() {
+            nLightDestroy(mID);
+            mID = 0;
+        }
+
+        public void setColor(float r, float g, float b) {
+            nLightSetColor(mID, r, g, b);
+        }
+
+        public void setPosition(float x, float y, float z) {
+            nLightSetPosition(mID, x, y, z);
+        }
+    }
+
+    public void lightBegin() {
+        nLightBegin();
+    }
+
+    public void lightSetIsMono(boolean isMono) {
+        nLightSetIsMono(isMono);
+    }
+
+    public void lightSetIsLocal(boolean isLocal) {
+        nLightSetIsLocal(isLocal);
+    }
+
+    public Light lightCreate() {
+        int id = nLightCreate();
+        return new Light(id);
+    }
+
+    //////////////////////////////////////////////////////////////////////////////////
+    // File
+
+    public class File extends BaseObj {
+        File(int id) {
+            mID = id;
+        }
+
+        public void destroy() {
+            //nLightDestroy(mID);
+            mID = 0;
+        }
+    }
+
+    public File fileOpen(String s) throws IllegalStateException, IllegalArgumentException
+    {
+        if(s.length() < 1) {
+            throw new IllegalArgumentException("fileOpen does not accept a zero length string.");
+        }
+
+        try {
+            byte[] bytes = s.getBytes("UTF-8");
+            int id = nFileOpen(bytes);
+            return new File(id);
+        } catch (java.io.UnsupportedEncodingException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+
+    ///////////////////////////////////////////////////////////////////////////////////
+    // Root state
+
+    public void contextBindRootScript(Script s) {
+        nContextBindRootScript(s.mID);
+    }
+
+    //public void contextBindSampler(Sampler s, int slot) {
+        //nContextBindSampler(s.mID);
+    //}
+
+    public void contextBindProgramFragmentStore(ProgramFragmentStore pfs) {
+        nContextBindProgramFragmentStore(pfs.mID);
+    }
+
+    public void contextBindProgramFragment(ProgramFragment pf) {
+        nContextBindProgramFragment(pf.mID);
+    }
+
+    public void contextBindProgramVertex(ProgramVertex pf) {
+        nContextBindProgramVertex(pf.mID);
+    }
+
+/*
+    RsAdapter2D rsAdapter2DCreate ();
+    void rsAdapter2DBindAllocation (RsAdapter2D adapt, RsAllocation alloc);
+    void rsAdapter2DDestroy (RsAdapter2D adapter);
+    void rsAdapter2DSetConstraint (RsAdapter2D adapter, RsDimension dim, uint32_t value);
+    void rsAdapter2DData (RsAdapter2D adapter, const void * data);
+    void rsAdapter2DSubData (RsAdapter2D adapter, uint32_t xoff, uint32_t yoff, uint32_t w, uint32_t h, const void * data);
+    void rsSamplerBegin ();
+    void rsSamplerSet (RsSamplerParam p, RsSamplerValue value);
+    RsSampler rsSamplerCreate ();
+    void rsSamplerBind (RsSampler sampler, RsAllocation alloc);
+*/
+
+}
+
diff --git a/graphics/jni/Android.mk b/graphics/jni/Android.mk
new file mode 100644
index 0000000..a19134d
--- /dev/null
+++ b/graphics/jni/Android.mk
@@ -0,0 +1,39 @@
+ifeq ($(BUILD_RENDERSCRIPT),true)
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+    android_renderscript_RenderScript.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+        libandroid_runtime \
+        libacc \
+        libnativehelper \
+        libRS \
+        libcutils \
+        libskia \
+        libutils \
+        libui
+
+LOCAL_STATIC_LIBRARIES :=
+
+rs_generated_include_dir := $(call intermediates-dir-for,SHARED_LIBRARIES,libRS,,)
+
+LOCAL_C_INCLUDES += \
+	$(JNI_H_INCLUDE) \
+	$(LOCAL_PATH)/../../libs/rs \
+	$(rs_generated_include_dir) \
+	$(call include-path-for, corecg graphics)
+
+LOCAL_CFLAGS +=
+
+LOCAL_LDLIBS := -lpthread
+LOCAL_ADDITIONAL_DEPENDENCIES := $(addprefix $(rs_generated_include_dir)/,rsgApiFuncDecl.h)
+LOCAL_MODULE:= librs_jni
+LOCAL_ADDITIONAL_DEPENDENCIES += $(rs_generated_source)
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
+
+endif
diff --git a/graphics/jni/android_renderscript_RenderScript.cpp b/graphics/jni/android_renderscript_RenderScript.cpp
new file mode 100644
index 0000000..573610c
--- /dev/null
+++ b/graphics/jni/android_renderscript_RenderScript.cpp
@@ -0,0 +1,1111 @@
+/*
+ * Copyright (C) 2006 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 "libRS_jni"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <math.h>
+#include <utils/misc.h>
+
+#include <ui/Surface.h>
+
+#include <core/SkBitmap.h>
+
+
+#include "jni.h"
+#include "JNIHelp.h"
+#include "android_runtime/AndroidRuntime.h"
+
+#include <RenderScript.h>
+#include <RenderScriptEnv.h>
+
+//#define LOG_API LOGE
+#define LOG_API(...)
+
+using namespace android;
+
+// ---------------------------------------------------------------------------
+
+static void doThrow(JNIEnv* env, const char* exc, const char* msg = NULL)
+{
+    jclass npeClazz = env->FindClass(exc);
+    env->ThrowNew(npeClazz, msg);
+}
+
+static jfieldID gContextId = 0;
+static jfieldID gNativeBitmapID = 0;
+
+static void _nInit(JNIEnv *_env, jclass _this)
+{
+    gContextId             = _env->GetFieldID(_this, "mContext", "I");
+
+    jclass bitmapClass = _env->FindClass("android/graphics/Bitmap");
+    gNativeBitmapID = _env->GetFieldID(bitmapClass, "mNativeBitmap", "I");
+}
+
+
+// ---------------------------------------------------------------------------
+
+static void
+nAssignName(JNIEnv *_env, jobject _this, jint obj, jbyteArray str)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nAssignName, con(%p), obj(%p)", con, obj);
+
+    jint len = _env->GetArrayLength(str);
+    jbyte * cptr = (jbyte *) _env->GetPrimitiveArrayCritical(str, 0);
+    rsAssignName((void *)obj, (const char *)cptr, len);
+    _env->ReleasePrimitiveArrayCritical(str, cptr, JNI_ABORT);
+}
+
+
+static jint
+nFileOpen(JNIEnv *_env, jobject _this, jbyteArray str)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nFileOpen, con(%p)", con);
+
+    jint len = _env->GetArrayLength(str);
+    jbyte * cptr = (jbyte *) _env->GetPrimitiveArrayCritical(str, 0);
+    jint ret = (jint)rsFileOpen((const char *)cptr, len);
+    _env->ReleasePrimitiveArrayCritical(str, cptr, JNI_ABORT);
+    return ret;
+}
+
+// ---------------------------------------------------------------------------
+
+static jint
+nDeviceCreate(JNIEnv *_env, jobject _this)
+{
+    LOG_API("nDeviceCreate");
+    return (jint)rsDeviceCreate();
+}
+
+static void
+nDeviceDestroy(JNIEnv *_env, jobject _this, jint dev)
+{
+    LOG_API("nDeviceDestroy");
+    return rsDeviceDestroy((RsDevice)dev);
+}
+
+static jint
+nContextCreate(JNIEnv *_env, jobject _this, jint dev, jobject wnd, jint ver)
+{
+    LOG_API("nContextCreate");
+
+    if (wnd == NULL) {
+        not_valid_surface:
+        doThrow(_env, "java/lang/IllegalArgumentException",
+                "Make sure the SurfaceView or associated SurfaceHolder has a valid Surface");
+        return 0;
+    }
+    jclass surface_class = _env->FindClass("android/view/Surface");
+    jfieldID surfaceFieldID = _env->GetFieldID(surface_class, "mSurface", "I");
+    Surface * window = (Surface*)_env->GetIntField(wnd, surfaceFieldID);
+    if (window == NULL)
+        goto not_valid_surface;
+
+    return (jint)rsContextCreate((RsDevice)dev, window, ver);
+}
+
+static void
+nContextDestroy(JNIEnv *_env, jobject _this, jint con)
+{
+    LOG_API("nContextDestroy, con(%p)", (RsContext)con);
+    return rsContextDestroy((RsContext)con);
+}
+
+
+static void
+nElementBegin(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nElementBegin, con(%p)", con);
+    rsElementBegin();
+}
+
+static void
+nElementAddPredefined(JNIEnv *_env, jobject _this, jint predef)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nElementAddPredefined, con(%p), predef(%i)", con, predef);
+    rsElementAddPredefined((RsElementPredefined)predef);
+}
+
+static void
+nElementAdd(JNIEnv *_env, jobject _this, jint kind, jint type, jint norm, jint bits)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nElementAdd, con(%p), kind(%i), type(%i), norm(%i), bits(%i)", con, kind, type, norm, bits);
+    rsElementAdd((RsDataKind)kind, (RsDataType)type, norm != 0, (size_t)bits);
+}
+
+static jint
+nElementCreate(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nElementCreate, con(%p)", con);
+    return (jint)rsElementCreate();
+}
+
+static jint
+nElementGetPredefined(JNIEnv *_env, jobject _this, jint predef)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nElementGetPredefined, con(%p) predef(%i)", con, predef);
+    return (jint)rsElementGetPredefined((RsElementPredefined)predef);
+}
+
+static void
+nElementDestroy(JNIEnv *_env, jobject _this, jint e)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nElementDestroy, con(%p) e(%p)", con, (RsElement)e);
+    rsElementDestroy((RsElement)e);
+}
+
+// -----------------------------------
+
+static void
+nTypeBegin(JNIEnv *_env, jobject _this, jint eID)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTypeBegin, con(%p) e(%p)", con, (RsElement)eID);
+    rsTypeBegin((RsElement)eID);
+}
+
+static void
+nTypeAdd(JNIEnv *_env, jobject _this, jint dim, jint val)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTypeAdd, con(%p) dim(%i), val(%i)", con, dim, val);
+    rsTypeAdd((RsDimension)dim, val);
+}
+
+static jint
+nTypeCreate(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTypeCreate, con(%p)", con);
+    return (jint)rsTypeCreate();
+}
+
+static void
+nTypeDestroy(JNIEnv *_env, jobject _this, jint eID)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTypeDestroy, con(%p), t(%p)", con, (RsType)eID);
+    rsTypeDestroy((RsType)eID);
+}
+
+// -----------------------------------
+
+static jint
+nAllocationCreateTyped(JNIEnv *_env, jobject _this, jint e)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nAllocationCreateTyped, con(%p), e(%p)", con, (RsElement)e);
+    return (jint) rsAllocationCreateTyped((RsElement)e);
+}
+
+static jint
+nAllocationCreatePredefSized(JNIEnv *_env, jobject _this, jint predef, jint count)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nAllocationCreatePredefSized, con(%p), predef(%i), count(%i)", con, predef, count);
+    return (jint) rsAllocationCreatePredefSized((RsElementPredefined)predef, count);
+}
+
+static jint
+nAllocationCreateSized(JNIEnv *_env, jobject _this, jint e, jint count)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nAllocationCreateSized, con(%p), e(%p), count(%i)", con, (RsElement)e, count);
+    return (jint) rsAllocationCreateSized((RsElement)e, count);
+}
+
+static void
+nAllocationUploadToTexture(JNIEnv *_env, jobject _this, jint a, jint mip)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nAllocationUploadToTexture, con(%p), a(%p), mip(%i)", con, (RsAllocation)a, mip);
+    rsAllocationUploadToTexture((RsAllocation)a, mip);
+}
+
+static RsElementPredefined SkBitmapToPredefined(SkBitmap::Config cfg)
+{
+    switch (cfg) {
+    case SkBitmap::kA8_Config:
+        return RS_ELEMENT_A_8;
+    case SkBitmap::kARGB_4444_Config:
+        return RS_ELEMENT_RGBA_4444;
+    case SkBitmap::kARGB_8888_Config:
+        return RS_ELEMENT_RGBA_8888;
+    case SkBitmap::kRGB_565_Config:
+        return RS_ELEMENT_RGB_565;
+
+    default:
+        break;
+    }
+    // If we don't have a conversion mark it as a user type.
+    LOGE("Unsupported bitmap type");
+    return RS_ELEMENT_USER_U8;
+}
+
+static int
+nAllocationCreateFromBitmap(JNIEnv *_env, jobject _this, jint dstFmt, jboolean genMips, jobject jbitmap)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    SkBitmap const * nativeBitmap =
+            (SkBitmap const *)_env->GetIntField(jbitmap, gNativeBitmapID);
+    const SkBitmap& bitmap(*nativeBitmap);
+    SkBitmap::Config config = bitmap.getConfig();
+
+    RsElementPredefined e = SkBitmapToPredefined(config);
+
+    if (e != RS_ELEMENT_USER_U8) {
+        bitmap.lockPixels();
+        const int w = bitmap.width();
+        const int h = bitmap.height();
+        const void* ptr = bitmap.getPixels();
+        jint id = (jint)rsAllocationCreateFromBitmap(w, h, (RsElementPredefined)dstFmt, e, genMips, ptr);
+        bitmap.unlockPixels();
+        return id;
+    }
+    return 0;
+}
+
+
+static void
+nAllocationDestroy(JNIEnv *_env, jobject _this, jint a)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nAllocationDestroy, con(%p), a(%p)", con, (RsAllocation)a);
+    rsAllocationDestroy((RsAllocation)a);
+}
+
+static void
+nAllocationData_i(JNIEnv *_env, jobject _this, jint alloc, jintArray data)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nAllocationData_i, con(%p), alloc(%p), len(%i)", con, (RsAllocation)alloc, len);
+    jint *ptr = _env->GetIntArrayElements(data, NULL);
+    rsAllocationData((RsAllocation)alloc, ptr);
+    _env->ReleaseIntArrayElements(data, ptr, JNI_ABORT);
+}
+
+static void
+nAllocationData_f(JNIEnv *_env, jobject _this, jint alloc, jfloatArray data)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nAllocationData_i, con(%p), alloc(%p), len(%i)", con, (RsAllocation)alloc, len);
+    jfloat *ptr = _env->GetFloatArrayElements(data, NULL);
+    rsAllocationData((RsAllocation)alloc, ptr);
+    _env->ReleaseFloatArrayElements(data, ptr, JNI_ABORT);
+}
+
+static void
+nAllocationSubData1D_i(JNIEnv *_env, jobject _this, jint alloc, jint offset, jint count, jintArray data)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nAllocation1DSubData_i, con(%p), adapter(%p), offset(%i), count(%i), len(%i)", con, (RsAllocation)alloc, offset, count, len);
+    jint *ptr = _env->GetIntArrayElements(data, NULL);
+    rsAllocation1DSubData((RsAllocation)alloc, offset, count, ptr);
+    _env->ReleaseIntArrayElements(data, ptr, JNI_ABORT);
+}
+
+static void
+nAllocationSubData1D_f(JNIEnv *_env, jobject _this, jint alloc, jint offset, jint count, jfloatArray data)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nAllocation1DSubData_f, con(%p), adapter(%p), offset(%i), count(%i), len(%i)", con, (RsAllocation)alloc, offset, count, len);
+    jfloat *ptr = _env->GetFloatArrayElements(data, NULL);
+    rsAllocation1DSubData((RsAllocation)alloc, offset, count, ptr);
+    _env->ReleaseFloatArrayElements(data, ptr, JNI_ABORT);
+}
+
+static void
+nAllocationSubData2D_i(JNIEnv *_env, jobject _this, jint alloc, jint xoff, jint yoff, jint w, jint h, jintArray data)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nAllocation2DSubData_i, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i)", con, (RsAllocation)alloc, xoff, yoff, w, h, len);
+    jint *ptr = _env->GetIntArrayElements(data, NULL);
+    rsAllocation2DSubData((RsAllocation)alloc, xoff, yoff, w, h, ptr);
+    _env->ReleaseIntArrayElements(data, ptr, JNI_ABORT);
+}
+
+static void
+nAllocationSubData2D_f(JNIEnv *_env, jobject _this, jint alloc, jint xoff, jint yoff, jint w, jint h, jfloatArray data)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nAllocation2DSubData_i, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i)", con, (RsAllocation)alloc, xoff, yoff, w, h, len);
+    jfloat *ptr = _env->GetFloatArrayElements(data, NULL);
+    rsAllocation2DSubData((RsAllocation)alloc, xoff, yoff, w, h, ptr);
+    _env->ReleaseFloatArrayElements(data, ptr, JNI_ABORT);
+}
+
+
+
+// -----------------------------------
+
+static void
+nTriangleMeshDestroy(JNIEnv *_env, jobject _this, jint tm)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTriangleMeshDestroy, con(%p), tm(%p)", con, (RsAllocation)tm);
+    rsTriangleMeshDestroy((RsTriangleMesh)tm);
+}
+
+static void
+nTriangleMeshBegin(JNIEnv *_env, jobject _this, jint v, jint i)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTriangleMeshBegin, con(%p), vertex(%p), index(%p)", con, (RsElement)v, (RsElement)i);
+    rsTriangleMeshBegin((RsElement)v, (RsElement)i);
+}
+
+static void
+nTriangleMeshAddVertex_XY(JNIEnv *_env, jobject _this, jfloat x, jfloat y)
+{
+    float v[] = {x, y};
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTriangleMeshAddVertex_XY, con(%p), x(%f), y(%f)", con, x, y);
+    rsTriangleMeshAddVertex(v);
+}
+
+static void
+nTriangleMeshAddVertex_XYZ(JNIEnv *_env, jobject _this, jfloat x, jfloat y, jfloat z)
+{
+    float v[] = {x, y, z};
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTriangleMeshAddVertex_XYZ, con(%p), x(%f), y(%f), z(%f)", con, x, y, z);
+    rsTriangleMeshAddVertex(v);
+}
+
+static void
+nTriangleMeshAddVertex_XY_ST(JNIEnv *_env, jobject _this, jfloat x, jfloat y, jfloat s, jfloat t)
+{
+    float v[] = {s, t, x, y};
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTriangleMeshAddVertex_XY_ST, con(%p), x(%f), y(%f), s(%f), t(%f)", con, x, y, s, t);
+    rsTriangleMeshAddVertex(v);
+}
+
+static void
+nTriangleMeshAddVertex_XYZ_ST(JNIEnv *_env, jobject _this, jfloat x, jfloat y, jfloat z, jfloat s, jfloat t)
+{
+    float v[] = {s, t, x, y, z};
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTriangleMeshAddVertex_XYZ_ST, con(%p), x(%f), y(%f), z(%f), s(%f), t(%f)", con, x, y, z, s, t);
+    rsTriangleMeshAddVertex(v);
+}
+
+static void
+nTriangleMeshAddVertex_XYZ_ST_NORM(JNIEnv *_env, jobject _this, jfloat x, jfloat y, jfloat z, jfloat s, jfloat t, jfloat nx, jfloat ny, jfloat nz)
+{
+    float v[] = {nx, ny, nz, s, t, x, y, z};
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTriangleMeshAddVertex_XYZ_ST, con(%p), x(%f), y(%f), z(%f), s(%f), t(%f)", con, x, y, z, s, t);
+    rsTriangleMeshAddVertex(v);
+}
+
+static void
+nTriangleMeshAddTriangle(JNIEnv *_env, jobject _this, jint i1, jint i2, jint i3)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTriangleMeshAddTriangle, con(%p), i1(%i), i2(%i), i3(%i)", con, i1, i2, i3);
+    rsTriangleMeshAddTriangle(i1, i2, i3);
+}
+
+static jint
+nTriangleMeshCreate(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nTriangleMeshCreate, con(%p)", con);
+    return (jint) rsTriangleMeshCreate();
+}
+
+// -----------------------------------
+
+static void
+nAdapter1DDestroy(JNIEnv *_env, jobject _this, jint adapter)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nAdapter1DDestroy, con(%p), adapter(%p)", con, (RsAdapter1D)adapter);
+    rsAdapter1DDestroy((RsAdapter1D)adapter);
+}
+
+static void
+nAdapter1DBindAllocation(JNIEnv *_env, jobject _this, jint adapter, jint alloc)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nAdapter1DBindAllocation, con(%p), adapter(%p), alloc(%p)", con, (RsAdapter1D)adapter, (RsAllocation)alloc);
+    rsAdapter1DBindAllocation((RsAdapter1D)adapter, (RsAllocation)alloc);
+}
+
+static void
+nAdapter1DSetConstraint(JNIEnv *_env, jobject _this, jint adapter, jint dim, jint value)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nAdapter1DSetConstraint, con(%p), adapter(%p), dim(%i), value(%i)", con, (RsAdapter1D)adapter, dim, value);
+    rsAdapter1DSetConstraint((RsAdapter1D)adapter, (RsDimension)dim, value);
+}
+
+static void
+nAdapter1DData_i(JNIEnv *_env, jobject _this, jint adapter, jintArray data)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nAdapter1DData_i, con(%p), adapter(%p), len(%i)", con, (RsAdapter1D)adapter, len);
+    jint *ptr = _env->GetIntArrayElements(data, NULL);
+    rsAdapter1DData((RsAdapter1D)adapter, ptr);
+    _env->ReleaseIntArrayElements(data, ptr, 0/*JNI_ABORT*/);
+}
+
+static void
+nAdapter1DSubData_i(JNIEnv *_env, jobject _this, jint adapter, jint offset, jint count, jintArray data)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nAdapter1DSubData_i, con(%p), adapter(%p), offset(%i), count(%i), len(%i)", con, (RsAdapter1D)adapter, offset, count, len);
+    jint *ptr = _env->GetIntArrayElements(data, NULL);
+    rsAdapter1DSubData((RsAdapter1D)adapter, offset, count, ptr);
+    _env->ReleaseIntArrayElements(data, ptr, 0/*JNI_ABORT*/);
+}
+
+static void
+nAdapter1DData_f(JNIEnv *_env, jobject _this, jint adapter, jfloatArray data)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nAdapter1DData_f, con(%p), adapter(%p), len(%i)", con, (RsAdapter1D)adapter, len);
+    jfloat *ptr = _env->GetFloatArrayElements(data, NULL);
+    rsAdapter1DData((RsAdapter1D)adapter, ptr);
+    _env->ReleaseFloatArrayElements(data, ptr, 0/*JNI_ABORT*/);
+}
+
+static void
+nAdapter1DSubData_f(JNIEnv *_env, jobject _this, jint adapter, jint offset, jint count, jfloatArray data)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nAdapter1DSubData_f, con(%p), adapter(%p), offset(%i), count(%i), len(%i)", con, (RsAdapter1D)adapter, offset, count, len);
+    jfloat *ptr = _env->GetFloatArrayElements(data, NULL);
+    rsAdapter1DSubData((RsAdapter1D)adapter, offset, count, ptr);
+    _env->ReleaseFloatArrayElements(data, ptr, 0/*JNI_ABORT*/);
+}
+
+static jint
+nAdapter1DCreate(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nAdapter1DCreate, con(%p)", con);
+    return (jint)rsAdapter1DCreate();
+}
+
+// -----------------------------------
+
+static void
+nScriptDestroy(JNIEnv *_env, jobject _this, jint script)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nScriptDestroy, con(%p), script(%p)", con, (RsScript)script);
+    rsScriptDestroy((RsScript)script);
+}
+
+static void
+nScriptBindAllocation(JNIEnv *_env, jobject _this, jint script, jint alloc, jint slot)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nScriptBindAllocation, con(%p), script(%p), alloc(%p), slot(%i)", con, (RsScript)script, (RsAllocation)alloc, slot);
+    rsScriptBindAllocation((RsScript)script, (RsAllocation)alloc, slot);
+}
+
+static void
+nScriptCBegin(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nScriptCBegin, con(%p)", con);
+    rsScriptCBegin();
+}
+
+static void
+nScriptCSetClearColor(JNIEnv *_env, jobject _this, jfloat r, jfloat g, jfloat b, jfloat a)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nScriptCSetClearColor, con(%p), r(%f), g(%f), b(%f), a(%f)", con, r, g, b, a);
+    rsScriptCSetClearColor(r, g, b, a);
+}
+
+static void
+nScriptCSetClearDepth(JNIEnv *_env, jobject _this, jfloat d)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nScriptCSetClearColor, con(%p), depth(%f)", con, d);
+    rsScriptCSetClearDepth(d);
+}
+
+static void
+nScriptCSetClearStencil(JNIEnv *_env, jobject _this, jint stencil)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nScriptCSetClearStencil, con(%p), stencil(%i)", con, stencil);
+    rsScriptCSetClearStencil(stencil);
+}
+
+static void
+nScriptCAddType(JNIEnv *_env, jobject _this, jint type)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nScriptCAddType, con(%p), type(%p)", con, (RsType)type);
+    rsScriptCAddType((RsType)type);
+}
+
+static void
+nScriptCSetRoot(JNIEnv *_env, jobject _this, jboolean isRoot)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nScriptCSetRoot, con(%p), isRoot(%i)", con, isRoot);
+    rsScriptCSetRoot(isRoot);
+}
+
+static void
+nScriptCSetScript(JNIEnv *_env, jobject _this, jbyteArray scriptRef,
+                  jint offset, jint length)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("!!! nScriptCSetScript, con(%p)", con);
+    jint _exception = 0;
+    jint remaining;
+    jbyte* script_base = 0;
+    jbyte* script_ptr;
+    if (!scriptRef) {
+        _exception = 1;
+        //_env->ThrowNew(IAEClass, "script == null");
+        goto exit;
+    }
+    if (offset < 0) {
+        _exception = 1;
+        //_env->ThrowNew(IAEClass, "offset < 0");
+        goto exit;
+    }
+    if (length < 0) {
+        _exception = 1;
+        //_env->ThrowNew(IAEClass, "length < 0");
+        goto exit;
+    }
+    remaining = _env->GetArrayLength(scriptRef) - offset;
+    if (remaining < length) {
+        _exception = 1;
+        //_env->ThrowNew(IAEClass, "length > script.length - offset");
+        goto exit;
+    }
+    script_base = (jbyte *)
+        _env->GetPrimitiveArrayCritical(scriptRef, (jboolean *)0);
+    script_ptr = script_base + offset;
+
+    rsScriptCSetText((const char *)script_ptr, length);
+
+exit:
+    if (script_base) {
+        _env->ReleasePrimitiveArrayCritical(scriptRef, script_base,
+                _exception ? JNI_ABORT: 0);
+    }
+}
+
+static jint
+nScriptCCreate(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nScriptCCreate, con(%p)", con);
+    return (jint)rsScriptCCreate();
+}
+
+// ---------------------------------------------------------------------------
+
+static void
+nProgramFragmentStoreBegin(JNIEnv *_env, jobject _this, jint in, jint out)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentStoreBegin, con(%p), in(%p), out(%p)", con, (RsElement)in, (RsElement)out);
+    rsProgramFragmentStoreBegin((RsElement)in, (RsElement)out);
+}
+
+static void
+nProgramFragmentStoreDepthFunc(JNIEnv *_env, jobject _this, jint func)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentStoreDepthFunc, con(%p), func(%i)", con, func);
+    rsProgramFragmentStoreDepthFunc((RsDepthFunc)func);
+}
+
+static void
+nProgramFragmentStoreDepthMask(JNIEnv *_env, jobject _this, jboolean enable)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentStoreDepthMask, con(%p), enable(%i)", con, enable);
+    rsProgramFragmentStoreDepthMask(enable);
+}
+
+static void
+nProgramFragmentStoreColorMask(JNIEnv *_env, jobject _this, jboolean r, jboolean g, jboolean b, jboolean a)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentStoreColorMask, con(%p), r(%i), g(%i), b(%i), a(%i)", con, r, g, b, a);
+    rsProgramFragmentStoreColorMask(r, g, b, a);
+}
+
+static void
+nProgramFragmentStoreBlendFunc(JNIEnv *_env, jobject _this, int src, int dst)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentStoreBlendFunc, con(%p), src(%i), dst(%i)", con, src, dst);
+    rsProgramFragmentStoreBlendFunc((RsBlendSrcFunc)src, (RsBlendDstFunc)dst);
+}
+
+static void
+nProgramFragmentStoreDither(JNIEnv *_env, jobject _this, jboolean enable)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentStoreDither, con(%p), enable(%i)", con, enable);
+    rsProgramFragmentStoreDither(enable);
+}
+
+static jint
+nProgramFragmentStoreCreate(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentStoreCreate, con(%p)", con);
+
+    return (jint)rsProgramFragmentStoreCreate();
+}
+
+static void
+nProgramFragmentStoreDestroy(JNIEnv *_env, jobject _this, jint pgm)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentStoreDestroy, con(%p), pgm(%i)", con, pgm);
+    rsProgramFragmentStoreDestroy((RsProgramFragmentStore)pgm);
+}
+
+// ---------------------------------------------------------------------------
+
+static void
+nProgramFragmentBegin(JNIEnv *_env, jobject _this, jint in, jint out)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentBegin, con(%p), in(%p), out(%p)", con, (RsElement)in, (RsElement)out);
+    rsProgramFragmentBegin((RsElement)in, (RsElement)out);
+}
+
+static void
+nProgramFragmentBindTexture(JNIEnv *_env, jobject _this, jint vpf, jint slot, jint a)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentBindTexture, con(%p), vpf(%p), slot(%i), a(%p)", con, (RsProgramFragment)vpf, slot, (RsAllocation)a);
+    rsProgramFragmentBindTexture((RsProgramFragment)vpf, slot, (RsAllocation)a);
+}
+
+static void
+nProgramFragmentBindSampler(JNIEnv *_env, jobject _this, jint vpf, jint slot, jint a)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentBindSampler, con(%p), vpf(%p), slot(%i), a(%p)", con, (RsProgramFragment)vpf, slot, (RsSampler)a);
+    rsProgramFragmentBindSampler((RsProgramFragment)vpf, slot, (RsSampler)a);
+}
+
+static void
+nProgramFragmentSetType(JNIEnv *_env, jobject _this, jint slot, jint vt)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentSetType, con(%p), slot(%i), vt(%p)", con, slot, (RsType)vt);
+    rsProgramFragmentSetType(slot, (RsType)vt);
+}
+
+static void
+nProgramFragmentSetEnvMode(JNIEnv *_env, jobject _this, jint slot, jint env)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentSetEnvMode, con(%p), slot(%i), vt(%i)", con, slot, env);
+    rsProgramFragmentSetEnvMode(slot, (RsTexEnvMode)env);
+}
+
+static void
+nProgramFragmentSetTexEnable(JNIEnv *_env, jobject _this, jint slot, jboolean enable)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentSetTexEnable, con(%p), slot(%i), enable(%i)", con, slot, enable);
+    rsProgramFragmentSetTexEnable(slot, enable);
+}
+
+static jint
+nProgramFragmentCreate(JNIEnv *_env, jobject _this, jint slot, jboolean enable)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentCreate, con(%p)", con);
+    return (jint)rsProgramFragmentCreate();
+}
+
+static void
+nProgramFragmentDestroy(JNIEnv *_env, jobject _this, jint pgm)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentDestroy, con(%p), pgm(%i)", con, pgm);
+    rsProgramFragmentDestroy((RsProgramFragment)pgm);
+}
+
+// ---------------------------------------------------------------------------
+
+static void
+nProgramVertexBegin(JNIEnv *_env, jobject _this, jint in, jint out)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramVertexBegin, con(%p), in(%p), out(%p)", con, (RsElement)in, (RsElement)out);
+    rsProgramVertexBegin((RsElement)in, (RsElement)out);
+}
+
+static void
+nProgramVertexBindAllocation(JNIEnv *_env, jobject _this, jint vpv, jint slot, jint a)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramVertexBindAllocation, con(%p), vpf(%p), slot(%i), a(%p)", con, (RsProgramVertex)vpv, slot, (RsAllocation)a);
+    rsProgramVertexBindAllocation((RsProgramFragment)vpv, slot, (RsAllocation)a);
+}
+
+static void
+nProgramVertexSetType(JNIEnv *_env, jobject _this, jint slot, jint t)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramVertexSetType, con(%p), vpf(%p), slot(%i), a(%p)", con, (RsProgramVertex)vpv, slot, (RsType)t);
+    rsProgramVertexSetType(slot, (RsType)t);
+}
+
+static void
+nProgramVertexSetTextureMatrixEnable(JNIEnv *_env, jobject _this, jboolean enable)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramVertexSetTextureMatrixEnable, con(%p), enable(%i)", con, enable);
+    rsProgramVertexSetTextureMatrixEnable(enable);
+}
+
+static void
+nProgramVertexAddLight(JNIEnv *_env, jobject _this, jint light)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramVertexAddLight, con(%p), light(%p)", con, (RsLight)light);
+    rsProgramVertexAddLight((RsLight)light);
+}
+
+static jint
+nProgramVertexCreate(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramVertexCreate, con(%p)", con);
+    return (jint)rsProgramVertexCreate();
+}
+
+static void
+nProgramVertexDestroy(JNIEnv *_env, jobject _this, jint pgm)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nProgramFragmentDestroy, con(%p), pgm(%i)", con, pgm);
+    rsProgramFragmentDestroy((RsProgramFragment)pgm);
+}
+
+
+
+
+// ---------------------------------------------------------------------------
+
+static void
+nContextBindRootScript(JNIEnv *_env, jobject _this, jint script)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nContextBindRootScript, con(%p), script(%p)", con, (RsScript)script);
+    rsContextBindRootScript((RsScript)script);
+}
+
+static void
+nContextBindProgramFragmentStore(JNIEnv *_env, jobject _this, jint pfs)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nContextBindProgramFragmentStore, con(%p), pfs(%p)", con, (RsProgramFragmentStore)pfs);
+    rsContextBindProgramFragmentStore((RsProgramFragmentStore)pfs);
+}
+
+static void
+nContextBindProgramFragment(JNIEnv *_env, jobject _this, jint pf)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nContextBindProgramFragment, con(%p), pf(%p)", con, (RsProgramFragment)pf);
+    rsContextBindProgramFragment((RsProgramFragment)pf);
+}
+
+static void
+nContextBindProgramVertex(JNIEnv *_env, jobject _this, jint pf)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nContextBindProgramVertex, con(%p), pf(%p)", con, (RsProgramVertex)pf);
+    rsContextBindProgramVertex((RsProgramVertex)pf);
+}
+
+// ---------------------------------------------------------------------------
+
+static void
+nSamplerDestroy(JNIEnv *_env, jobject _this, jint s)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nSamplerDestroy, con(%p), sampler(%p)", con, (RsSampler)s);
+    rsSamplerDestroy((RsSampler)s);
+}
+
+static void
+nSamplerBegin(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nSamplerBegin, con(%p)", con);
+    rsSamplerBegin();
+}
+
+static void
+nSamplerSet(JNIEnv *_env, jobject _this, jint p, jint v)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nSamplerSet, con(%p), param(%i), value(%i)", con, p, v);
+    rsSamplerSet((RsSamplerParam)p, (RsSamplerValue)v);
+}
+
+static jint
+nSamplerCreate(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nSamplerCreate, con(%p)", con);
+    return (jint)rsSamplerCreate();
+}
+
+// ---------------------------------------------------------------------------
+
+static void
+nLightBegin(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nLightBegin, con(%p)", con);
+    rsLightBegin();
+}
+
+static void
+nLightSetIsMono(JNIEnv *_env, jobject _this, jboolean isMono)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nLightSetIsMono, con(%p), isMono(%i)", con, isMono);
+    rsLightSetMonochromatic(isMono);
+}
+
+static void
+nLightSetIsLocal(JNIEnv *_env, jobject _this, jboolean isLocal)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nLightSetIsLocal, con(%p), isLocal(%i)", con, isLocal);
+    rsLightSetLocal(isLocal);
+}
+
+static jint
+nLightCreate(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nLightCreate, con(%p)", con);
+    return (jint)rsLightCreate();
+}
+
+static void
+nLightDestroy(JNIEnv *_env, jobject _this, jint light)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nLightDestroy, con(%p), light(%p)", con, (RsLight)light);
+    rsLightDestroy((RsLight)light);
+}
+
+static void
+nLightSetColor(JNIEnv *_env, jobject _this, jint light, float r, float g, float b)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nLightSetColor, con(%p), light(%p), r(%f), g(%f), b(%f)", con, (RsLight)light, r, g, b);
+    rsLightSetColor((RsLight)light, r, g, b);
+}
+
+static void
+nLightSetPosition(JNIEnv *_env, jobject _this, jint light, float x, float y, float z)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nLightSetPosition, con(%p), light(%p), x(%f), y(%f), z(%f)", con, (RsLight)light, x, y, z);
+    rsLightSetPosition((RsLight)light, x, y, z);
+}
+
+// ---------------------------------------------------------------------------
+
+
+static const char *classPathName = "android/renderscript/RenderScript";
+
+static JNINativeMethod methods[] = {
+{"_nInit",                         "()V",                                  (void*)_nInit },
+{"nDeviceCreate",                  "()I",                                  (void*)nDeviceCreate },
+{"nDeviceDestroy",                 "(I)V",                                 (void*)nDeviceDestroy },
+{"nContextCreate",                 "(ILandroid/view/Surface;I)I",          (void*)nContextCreate },
+{"nContextDestroy",                "(I)V",                                 (void*)nContextDestroy },
+{"nAssignName",                    "(I[B)V",                               (void*)nAssignName },
+
+{"nFileOpen",                      "([B)I",                                (void*)nFileOpen },
+
+{"nElementBegin",                  "()V",                                  (void*)nElementBegin },
+{"nElementAddPredefined",          "(I)V",                                 (void*)nElementAddPredefined },
+{"nElementAdd",                    "(IIII)V",                              (void*)nElementAdd },
+{"nElementCreate",                 "()I",                                  (void*)nElementCreate },
+{"nElementGetPredefined",          "(I)I",                                 (void*)nElementGetPredefined },
+{"nElementDestroy",                "(I)V",                                 (void*)nElementDestroy },
+
+{"nTypeBegin",                     "(I)V",                                 (void*)nTypeBegin },
+{"nTypeAdd",                       "(II)V",                                (void*)nTypeAdd },
+{"nTypeCreate",                    "()I",                                  (void*)nTypeCreate },
+{"nTypeDestroy",                   "(I)V",                                 (void*)nTypeDestroy },
+
+{"nAllocationCreateTyped",         "(I)I",                                 (void*)nAllocationCreateTyped },
+{"nAllocationCreatePredefSized",   "(II)I",                                (void*)nAllocationCreatePredefSized },
+{"nAllocationCreateSized",         "(II)I",                                (void*)nAllocationCreateSized },
+{"nAllocationCreateFromBitmap",    "(IZLandroid/graphics/Bitmap;)I",       (void*)nAllocationCreateFromBitmap },
+{"nAllocationUploadToTexture",     "(II)V",                                (void*)nAllocationUploadToTexture },
+{"nAllocationDestroy",             "(I)V",                                 (void*)nAllocationDestroy },
+{"nAllocationData",                "(I[I)V",                               (void*)nAllocationData_i },
+{"nAllocationData",                "(I[F)V",                               (void*)nAllocationData_f },
+{"nAllocationSubData1D",           "(III[I)V",                             (void*)nAllocationSubData1D_i },
+{"nAllocationSubData1D",           "(III[F)V",                             (void*)nAllocationSubData1D_f },
+{"nAllocationSubData2D",           "(IIIII[I)V",                           (void*)nAllocationSubData2D_i },
+{"nAllocationSubData2D",           "(IIIII[F)V",                           (void*)nAllocationSubData2D_f },
+
+{"nTriangleMeshDestroy",           "(I)V",                                 (void*)nTriangleMeshDestroy },
+{"nTriangleMeshBegin",             "(II)V",                                (void*)nTriangleMeshBegin },
+{"nTriangleMeshAddVertex_XY",      "(FF)V",                                (void*)nTriangleMeshAddVertex_XY },
+{"nTriangleMeshAddVertex_XYZ",     "(FFF)V",                               (void*)nTriangleMeshAddVertex_XYZ },
+{"nTriangleMeshAddVertex_XY_ST",   "(FFFF)V",                              (void*)nTriangleMeshAddVertex_XY_ST },
+{"nTriangleMeshAddVertex_XYZ_ST",  "(FFFFF)V",                             (void*)nTriangleMeshAddVertex_XYZ_ST },
+{"nTriangleMeshAddVertex_XYZ_ST_NORM",  "(FFFFFFFF)V",                     (void*)nTriangleMeshAddVertex_XYZ_ST_NORM },
+{"nTriangleMeshAddTriangle",       "(III)V",                               (void*)nTriangleMeshAddTriangle },
+{"nTriangleMeshCreate",            "()I",                                  (void*)nTriangleMeshCreate },
+
+{"nAdapter1DDestroy",              "(I)V",                                 (void*)nAdapter1DDestroy },
+{"nAdapter1DBindAllocation",       "(II)V",                                (void*)nAdapter1DBindAllocation },
+{"nAdapter1DSetConstraint",        "(III)V",                               (void*)nAdapter1DSetConstraint },
+{"nAdapter1DData",                 "(I[I)V",                               (void*)nAdapter1DData_i },
+{"nAdapter1DSubData",              "(III[I)V",                             (void*)nAdapter1DSubData_i },
+{"nAdapter1DData",                 "(I[F)V",                               (void*)nAdapter1DData_f },
+{"nAdapter1DSubData",              "(III[F)V",                             (void*)nAdapter1DSubData_f },
+{"nAdapter1DCreate",               "()I",                                  (void*)nAdapter1DCreate },
+
+{"nScriptDestroy",                 "(I)V",                                 (void*)nScriptDestroy },
+{"nScriptBindAllocation",          "(III)V",                               (void*)nScriptBindAllocation },
+{"nScriptCBegin",                  "()V",                                  (void*)nScriptCBegin },
+{"nScriptCSetClearColor",          "(FFFF)V",                              (void*)nScriptCSetClearColor },
+{"nScriptCSetClearDepth",          "(F)V",                                 (void*)nScriptCSetClearDepth },
+{"nScriptCSetClearStencil",        "(I)V",                                 (void*)nScriptCSetClearStencil },
+{"nScriptCAddType",                "(I)V",                                 (void*)nScriptCAddType },
+{"nScriptCSetRoot",                "(Z)V",                                 (void*)nScriptCSetRoot },
+{"nScriptCSetScript",              "([BII)V",                              (void*)nScriptCSetScript },
+{"nScriptCCreate",                 "()I",                                  (void*)nScriptCCreate },
+
+{"nProgramFragmentStoreBegin",     "(II)V",                                (void*)nProgramFragmentStoreBegin },
+{"nProgramFragmentStoreDepthFunc", "(I)V",                                 (void*)nProgramFragmentStoreDepthFunc },
+{"nProgramFragmentStoreDepthMask", "(Z)V",                                 (void*)nProgramFragmentStoreDepthMask },
+{"nProgramFragmentStoreColorMask", "(ZZZZ)V",                              (void*)nProgramFragmentStoreColorMask },
+{"nProgramFragmentStoreBlendFunc", "(II)V",                                (void*)nProgramFragmentStoreBlendFunc },
+{"nProgramFragmentStoreDither",    "(Z)V",                                 (void*)nProgramFragmentStoreDither },
+{"nProgramFragmentStoreCreate",    "()I",                                  (void*)nProgramFragmentStoreCreate },
+{"nProgramFragmentStoreDestroy",   "(I)V",                                 (void*)nProgramFragmentStoreDestroy },
+
+{"nProgramFragmentBegin",          "(II)V",                                (void*)nProgramFragmentBegin },
+{"nProgramFragmentBindTexture",    "(III)V",                               (void*)nProgramFragmentBindTexture },
+{"nProgramFragmentBindSampler",    "(III)V",                               (void*)nProgramFragmentBindSampler },
+{"nProgramFragmentSetType",        "(II)V",                                (void*)nProgramFragmentSetType },
+{"nProgramFragmentSetEnvMode",     "(II)V",                                (void*)nProgramFragmentSetEnvMode },
+{"nProgramFragmentSetTexEnable",   "(IZ)V",                                (void*)nProgramFragmentSetTexEnable },
+{"nProgramFragmentCreate",         "()I",                                  (void*)nProgramFragmentCreate },
+{"nProgramFragmentDestroy",        "(I)V",                                 (void*)nProgramFragmentDestroy },
+
+{"nProgramVertexDestroy",          "(I)V",                                 (void*)nProgramVertexDestroy },
+{"nProgramVertexBindAllocation",   "(III)V",                               (void*)nProgramVertexBindAllocation },
+{"nProgramVertexBegin",            "(II)V",                                (void*)nProgramVertexBegin },
+{"nProgramVertexSetType",          "(II)V",                                (void*)nProgramVertexSetType },
+{"nProgramVertexSetTextureMatrixEnable",   "(Z)V",                         (void*)nProgramVertexSetTextureMatrixEnable },
+{"nProgramVertexAddLight",         "(I)V",                                 (void*)nProgramVertexAddLight },
+{"nProgramVertexCreate",           "()I",                                  (void*)nProgramVertexCreate },
+
+{"nLightBegin",                    "()V",                                  (void*)nLightBegin },
+{"nLightSetIsMono",                "(Z)V",                                 (void*)nLightSetIsMono },
+{"nLightSetIsLocal",               "(Z)V",                                 (void*)nLightSetIsLocal },
+{"nLightCreate",                   "()I",                                  (void*)nLightCreate },
+{"nLightDestroy",                  "(I)V",                                 (void*)nLightDestroy },
+{"nLightSetColor",                 "(IFFF)V",                              (void*)nLightSetColor },
+{"nLightSetPosition",              "(IFFF)V",                              (void*)nLightSetPosition },
+
+{"nContextBindRootScript",         "(I)V",                                 (void*)nContextBindRootScript },
+{"nContextBindProgramFragmentStore","(I)V",                                (void*)nContextBindProgramFragmentStore },
+{"nContextBindProgramFragment",    "(I)V",                                 (void*)nContextBindProgramFragment },
+{"nContextBindProgramVertex",      "(I)V",                                 (void*)nContextBindProgramVertex },
+
+{"nSamplerDestroy",                "(I)V",                                 (void*)nSamplerDestroy },
+{"nSamplerBegin",                  "()V",                                  (void*)nSamplerBegin },
+{"nSamplerSet",                    "(II)V",                                (void*)nSamplerSet },
+{"nSamplerCreate",                 "()I",                                  (void*)nSamplerCreate },
+
+};
+
+static int registerFuncs(JNIEnv *_env)
+{
+    return android::AndroidRuntime::registerNativeMethods(
+            _env, classPathName, methods, NELEM(methods));
+}
+
+// ---------------------------------------------------------------------------
+
+jint JNI_OnLoad(JavaVM* vm, void* reserved)
+{
+    JNIEnv* env = NULL;
+    jint result = -1;
+
+    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
+        LOGE("ERROR: GetEnv failed\n");
+        goto bail;
+    }
+    assert(env != NULL);
+
+    if (registerFuncs(env) < 0) {
+        LOGE("ERROR: MediaPlayer native registration failed\n");
+        goto bail;
+    }
+
+    /* success -- return valid version number */
+    result = JNI_VERSION_1_4;
+
+bail:
+    return result;
+}
diff --git a/include/android_runtime/AndroidRuntime.h b/include/android_runtime/AndroidRuntime.h
index 78bef91..99ab2f0 100644
--- a/include/android_runtime/AndroidRuntime.h
+++ b/include/android_runtime/AndroidRuntime.h
@@ -20,7 +20,7 @@
 #define _RUNTIME_ANDROID_RUNTIME_H
 
 #include <utils/Errors.h>
-#include <utils/IBinder.h>
+#include <binder/IBinder.h>
 #include <utils/String8.h>
 #include <utils/String16.h>
 #include <utils/Vector.h>
@@ -98,6 +98,7 @@
 
 private:
     static int startReg(JNIEnv* env);
+    int startVm(JavaVM** pJavaVM, JNIEnv** pEnv);
 
     Vector<JavaVMOption> mOptions;
 
diff --git a/include/utils/Binder.h b/include/binder/Binder.h
similarity index 96%
rename from include/utils/Binder.h
rename to include/binder/Binder.h
index b5b8d98..47b2bb9 100644
--- a/include/utils/Binder.h
+++ b/include/binder/Binder.h
@@ -17,7 +17,7 @@
 #ifndef ANDROID_BINDER_H
 #define ANDROID_BINDER_H
 
-#include <utils/IBinder.h>
+#include <binder/IBinder.h>
 
 // ---------------------------------------------------------------------------
 namespace android {
@@ -27,7 +27,7 @@
 public:
                         BBinder();
 
-    virtual String16    getInterfaceDescriptor() const;
+    virtual const String16& getInterfaceDescriptor() const;
     virtual bool        isBinderAlive() const;
     virtual status_t    pingBinder();
     virtual status_t    dump(int fd, const Vector<String16>& args);
@@ -71,6 +71,7 @@
 
             Extras*     mExtras;
             void*       mReserved0;
+    static  String16    sEmptyDescriptor;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/include/utils/BpBinder.h b/include/binder/BpBinder.h
similarity index 94%
rename from include/utils/BpBinder.h
rename to include/binder/BpBinder.h
index 7b96e29..7ef93aa 100644
--- a/include/utils/BpBinder.h
+++ b/include/binder/BpBinder.h
@@ -17,7 +17,7 @@
 #ifndef ANDROID_BPBINDER_H
 #define ANDROID_BPBINDER_H
 
-#include <utils/IBinder.h>
+#include <binder/IBinder.h>
 #include <utils/KeyedVector.h>
 #include <utils/threads.h>
 
@@ -31,7 +31,7 @@
 
     inline  int32_t     handle() const { return mHandle; }
 
-    virtual String16    getInterfaceDescriptor() const;
+    virtual const String16&    getInterfaceDescriptor() const;
     virtual bool        isBinderAlive() const;
     virtual status_t    pingBinder();
     virtual status_t    dump(int fd, const Vector<String16>& args);
@@ -106,6 +106,7 @@
     };
 
             void                reportOneDeath(const Obituary& obit);
+            bool                isDescriptorCached() const;
 
     mutable Mutex               mLock;
             volatile int32_t    mAlive;
@@ -113,6 +114,7 @@
             Vector<Obituary>*   mObituaries;
             ObjectManager       mObjects;
             Parcel*             mConstantData;
+    mutable String16            mDescriptorCache;
 };
 
 }; // namespace android
diff --git a/include/utils/IBinder.h b/include/binder/IBinder.h
similarity index 97%
rename from include/utils/IBinder.h
rename to include/binder/IBinder.h
index 7370330..884b5c1 100644
--- a/include/utils/IBinder.h
+++ b/include/binder/IBinder.h
@@ -56,7 +56,7 @@
         FLAG_ONEWAY             = 0x00000001
     };
 
-    inline                  IBinder() { }
+                          IBinder();
 
     /**
      * Check if this IBinder implements the interface named by
@@ -69,7 +69,7 @@
      * Return the canonical name of the interface provided by this IBinder
      * object.
      */
-    virtual String16        getInterfaceDescriptor() const = 0;
+    virtual const String16& getInterfaceDescriptor() const = 0;
 
     virtual bool            isBinderAlive() const = 0;
     virtual status_t        pingBinder() = 0;
@@ -147,7 +147,7 @@
     virtual BpBinder*       remoteBinder();
 
 protected:
-    inline virtual          ~IBinder() { }
+    virtual          ~IBinder();
 
 private:
 };
diff --git a/include/utils/IInterface.h b/include/binder/IInterface.h
similarity index 82%
rename from include/utils/IInterface.h
rename to include/binder/IInterface.h
index 959722a..273d922 100644
--- a/include/utils/IInterface.h
+++ b/include/binder/IInterface.h
@@ -18,7 +18,7 @@
 #ifndef ANDROID_IINTERFACE_H
 #define ANDROID_IINTERFACE_H
 
-#include <utils/Binder.h>
+#include <binder/Binder.h>
 
 namespace android {
 
@@ -27,10 +27,12 @@
 class IInterface : public virtual RefBase
 {
 public:
+            IInterface();
             sp<IBinder>         asBinder();
             sp<const IBinder>   asBinder() const;
-
+            
 protected:
+    virtual                     ~IInterface();
     virtual IBinder*            onAsBinder() = 0;
 };
 
@@ -49,7 +51,7 @@
 {
 public:
     virtual sp<IInterface>      queryLocalInterface(const String16& _descriptor);
-    virtual String16            getInterfaceDescriptor() const;
+    virtual const String16&     getInterfaceDescriptor() const;
 
 protected:
     virtual IBinder*            onAsBinder();
@@ -72,11 +74,14 @@
 #define DECLARE_META_INTERFACE(INTERFACE)                               \
     static const String16 descriptor;                                   \
     static sp<I##INTERFACE> asInterface(const sp<IBinder>& obj);        \
-    virtual String16 getInterfaceDescriptor() const;                    \
+    virtual const String16& getInterfaceDescriptor() const;             \
+    I##INTERFACE();                                                     \
+    virtual ~I##INTERFACE();                                            \
+
 
 #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \
     const String16 I##INTERFACE::descriptor(NAME);                      \
-    String16 I##INTERFACE::getInterfaceDescriptor() const {             \
+    const String16& I##INTERFACE::getInterfaceDescriptor() const {      \
         return I##INTERFACE::descriptor;                                \
     }                                                                   \
     sp<I##INTERFACE> I##INTERFACE::asInterface(const sp<IBinder>& obj)  \
@@ -92,9 +97,16 @@
         }                                                               \
         return intr;                                                    \
     }                                                                   \
+    I##INTERFACE::I##INTERFACE() { }                                    \
+    I##INTERFACE::~I##INTERFACE() { }                                   \
+
+
+#define CHECK_INTERFACE(interface, data, reply)                         \
+    if (!data.checkInterface(this)) { return PERMISSION_DENIED; }       \
+
 
 // ----------------------------------------------------------------------
-// No user-servicable parts after this...
+// No user-serviceable parts after this...
 
 template<typename INTERFACE>
 inline sp<IInterface> BnInterface<INTERFACE>::queryLocalInterface(
@@ -105,7 +117,7 @@
 }
 
 template<typename INTERFACE>
-inline String16 BnInterface<INTERFACE>::getInterfaceDescriptor() const
+inline const String16& BnInterface<INTERFACE>::getInterfaceDescriptor() const
 {
     return INTERFACE::getInterfaceDescriptor();
 }
diff --git a/include/utils/IMemory.h b/include/binder/IMemory.h
similarity index 94%
rename from include/utils/IMemory.h
rename to include/binder/IMemory.h
index 35a3fd7..ae042cb 100644
--- a/include/utils/IMemory.h
+++ b/include/binder/IMemory.h
@@ -23,7 +23,7 @@
 
 #include <utils/RefBase.h>
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
+#include <binder/IInterface.h>
 
 namespace android {
 
@@ -59,6 +59,10 @@
             const Parcel& data,
             Parcel* reply,
             uint32_t flags = 0);
+    
+    BnMemoryHeap();
+protected:
+    virtual ~BnMemoryHeap();
 };
 
 // ----------------------------------------------------------------------------
@@ -85,6 +89,10 @@
             const Parcel& data,
             Parcel* reply,
             uint32_t flags = 0);
+
+    BnMemory();
+protected:
+    virtual ~BnMemory();
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/utils/IPCThreadState.h b/include/binder/IPCThreadState.h
similarity index 98%
rename from include/utils/IPCThreadState.h
rename to include/binder/IPCThreadState.h
index 0490fd3..78306b2 100644
--- a/include/utils/IPCThreadState.h
+++ b/include/binder/IPCThreadState.h
@@ -18,8 +18,8 @@
 #define ANDROID_IPC_THREAD_STATE_H
 
 #include <utils/Errors.h>
-#include <utils/Parcel.h>
-#include <utils/ProcessState.h>
+#include <binder/Parcel.h>
+#include <binder/ProcessState.h>
 #include <utils/Vector.h>
 
 #ifdef HAVE_WIN32_PROC
diff --git a/include/utils/IPermissionController.h b/include/binder/IPermissionController.h
similarity index 97%
rename from include/utils/IPermissionController.h
rename to include/binder/IPermissionController.h
index cb1dd34..f9d371b 100644
--- a/include/utils/IPermissionController.h
+++ b/include/binder/IPermissionController.h
@@ -18,7 +18,7 @@
 #ifndef ANDROID_IPERMISSION_CONTROLLER_H
 #define ANDROID_IPERMISSION_CONTROLLER_H
 
-#include <utils/IInterface.h>
+#include <binder/IInterface.h>
 
 namespace android {
 
diff --git a/include/utils/IServiceManager.h b/include/binder/IServiceManager.h
similarity index 94%
rename from include/utils/IServiceManager.h
rename to include/binder/IServiceManager.h
index e3d99fe..24e9e99 100644
--- a/include/utils/IServiceManager.h
+++ b/include/binder/IServiceManager.h
@@ -18,8 +18,8 @@
 #ifndef ANDROID_ISERVICE_MANAGER_H
 #define ANDROID_ISERVICE_MANAGER_H
 
-#include <utils/IInterface.h>
-#include <utils/IPermissionController.h>
+#include <binder/IInterface.h>
+#include <binder/IPermissionController.h>
 #include <utils/Vector.h>
 #include <utils/String16.h>
 
@@ -78,6 +78,8 @@
 bool checkCallingPermission(const String16& permission);
 bool checkCallingPermission(const String16& permission,
                             int32_t* outPid, int32_t* outUid);
+bool checkPermission(const String16& permission, pid_t pid, uid_t uid);
+
 
 // ----------------------------------------------------------------------
 
diff --git a/include/utils/MemoryBase.h b/include/binder/MemoryBase.h
similarity index 97%
rename from include/utils/MemoryBase.h
rename to include/binder/MemoryBase.h
index eb5a9d2..463e26d 100644
--- a/include/utils/MemoryBase.h
+++ b/include/binder/MemoryBase.h
@@ -20,7 +20,7 @@
 #include <stdlib.h>
 #include <stdint.h>
 
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 
 
 namespace android {
diff --git a/include/utils/MemoryDealer.h b/include/binder/MemoryDealer.h
similarity index 91%
rename from include/utils/MemoryDealer.h
rename to include/binder/MemoryDealer.h
index 454b627..03ac70a 100644
--- a/include/utils/MemoryDealer.h
+++ b/include/binder/MemoryDealer.h
@@ -21,9 +21,9 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 #include <utils/threads.h>
-#include <utils/MemoryHeapBase.h>
+#include <binder/MemoryHeapBase.h>
 
 namespace android {
 // ----------------------------------------------------------------------------
@@ -39,6 +39,10 @@
 public:
     // all values must be page-aligned
     virtual sp<IMemory> mapMemory(size_t offset, size_t size) = 0;
+
+    HeapInterface();
+protected:
+    virtual ~HeapInterface();
 };
 
 // ----------------------------------------------------------------------------
@@ -61,6 +65,10 @@
     virtual void        dump(const char* what, uint32_t flags = 0) const = 0;
     virtual void        dump(String8& res,
             const char* what, uint32_t flags = 0) const = 0;
+
+    AllocatorInterface();
+protected:
+    virtual ~AllocatorInterface();
 };
 
 // ----------------------------------------------------------------------------
@@ -71,6 +79,7 @@
 class SharedHeap : public HeapInterface, public MemoryHeapBase
 {
 public:
+                        SharedHeap();
                         SharedHeap(size_t size, uint32_t flags = 0, char const * name = NULL);
     virtual             ~SharedHeap();
     virtual sp<IMemory> mapMemory(size_t offset, size_t size);
@@ -117,13 +126,22 @@
             mFirst = mLast = newNode;
             newNode->prev = newNode->next = 0;
         } else {
-            insertBefore(mFirst, newNode);
+            newNode->prev = 0;
+            newNode->next = mFirst;
+            mFirst->prev = newNode;
+            mFirst = newNode;
         }
     }
     
     void insertTail(NODE* newNode) {
-        if (mLast == 0) insertBeginning(newNode);
-        else            insertAfter(mLast, newNode);
+        if (mLast == 0) {
+            insertHead(newNode);
+        } else {
+            newNode->prev = mLast;
+            newNode->next = 0;
+            mLast->next = newNode;
+            mLast = newNode;
+        }
     }
 
     NODE* remove(NODE* node) {
@@ -200,8 +218,6 @@
             const sp<HeapInterface>& heap,
             const sp<AllocatorInterface>& allocator);
 
-    virtual ~MemoryDealer();
-
     virtual sp<IMemory> allocate(size_t size, uint32_t flags = 0);
     virtual void        deallocate(size_t offset);
     virtual void        dump(const char* what, uint32_t flags = 0) const;
@@ -210,6 +226,9 @@
     sp<IMemoryHeap> getMemoryHeap() const { return heap(); }
     sp<AllocatorInterface> getAllocator() const { return allocator(); }
 
+protected:
+    virtual ~MemoryDealer();
+
 private:    
     const sp<HeapInterface>&        heap() const;
     const sp<AllocatorInterface>&   allocator() const;
diff --git a/include/utils/MemoryHeapBase.h b/include/binder/MemoryHeapBase.h
similarity index 98%
rename from include/utils/MemoryHeapBase.h
rename to include/binder/MemoryHeapBase.h
index 574acf4..83c7283 100644
--- a/include/utils/MemoryHeapBase.h
+++ b/include/binder/MemoryHeapBase.h
@@ -20,7 +20,7 @@
 #include <stdlib.h>
 #include <stdint.h>
 
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 
 
 namespace android {
diff --git a/include/utils/MemoryHeapPmem.h b/include/binder/MemoryHeapPmem.h
similarity index 95%
rename from include/utils/MemoryHeapPmem.h
rename to include/binder/MemoryHeapPmem.h
index 60335ad..dbf26ff 100644
--- a/include/utils/MemoryHeapPmem.h
+++ b/include/binder/MemoryHeapPmem.h
@@ -20,9 +20,9 @@
 #include <stdlib.h>
 #include <stdint.h>
 
-#include <utils/MemoryDealer.h>
-#include <utils/MemoryHeapBase.h>
-#include <utils/IMemory.h>
+#include <binder/MemoryDealer.h>
+#include <binder/MemoryHeapBase.h>
+#include <binder/IMemory.h>
 #include <utils/SortedVector.h>
 
 namespace android {
diff --git a/include/utils/Parcel.h b/include/binder/Parcel.h
similarity index 98%
rename from include/utils/Parcel.h
rename to include/binder/Parcel.h
index af1490a..58c2d9a 100644
--- a/include/utils/Parcel.h
+++ b/include/binder/Parcel.h
@@ -57,7 +57,8 @@
 
     status_t            writeInterfaceToken(const String16& interface);
     bool                enforceInterface(const String16& interface) const;
-            
+    bool                checkInterface(IBinder*) const;    
+
     void                freeData();
 
     const size_t*       objects() const;
@@ -147,7 +148,7 @@
                                             release_func relFunc, void* relCookie);
     
     void                print(TextOutput& to, uint32_t flags = 0) const;
-    
+        
 private:
                         Parcel(const Parcel& o);
     Parcel&             operator=(const Parcel& o);
diff --git a/include/binder/Permission.h b/include/binder/Permission.h
new file mode 100644
index 0000000..9542d50
--- /dev/null
+++ b/include/binder/Permission.h
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+
+#ifndef BINDER_PERMISSION_H
+#define BINDER_PERMISSION_H
+
+#include <stdint.h>
+#include <unistd.h>
+
+#include <utils/SortedVector.h>
+#include <utils/String16.h>
+#include <utils/threads.h>
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+/*
+ * Permission caches the result of the permission check for the given
+ * permission name and the provided uid/pid. It also handles a few
+ * known cases efficiently (caller is in the same process or is root).
+ * The package manager does something similar but lives in dalvik world
+ * and is therefore extremely slow to access.
+ */
+
+class Permission
+{
+public:
+            Permission(char const* name);
+            Permission(const String16& name);
+            Permission(const Permission& rhs);
+    virtual ~Permission();
+
+    bool operator < (const Permission& rhs) const;
+
+    // checks the current binder call's caller has access to this permission
+    bool checkCalling() const;
+    
+    // checks the specified pid/uid has access to this permission
+    bool check(pid_t pid, uid_t uid) const;
+    
+protected:
+    virtual bool doCheckPermission(pid_t pid, uid_t uid) const;
+
+private:
+    Permission& operator = (const Permission& rhs) const;
+    const String16 mPermissionName;
+    mutable SortedVector<uid_t> mGranted;
+    const pid_t mPid;
+    mutable Mutex mLock;
+};
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+
+#endif /* BINDER_PERMISSION_H */
diff --git a/include/utils/ProcessState.h b/include/binder/ProcessState.h
similarity index 98%
rename from include/utils/ProcessState.h
rename to include/binder/ProcessState.h
index 39584f4..feeb3c3 100644
--- a/include/utils/ProcessState.h
+++ b/include/binder/ProcessState.h
@@ -17,7 +17,7 @@
 #ifndef ANDROID_PROCESS_STATE_H
 #define ANDROID_PROCESS_STATE_H
 
-#include <utils/IBinder.h>
+#include <binder/IBinder.h>
 #include <utils/KeyedVector.h>
 #include <utils/String8.h>
 #include <utils/String16.h>
diff --git a/include/media/AudioRecord.h b/include/media/AudioRecord.h
index 13e51ee..503cb31 100644
--- a/include/media/AudioRecord.h
+++ b/include/media/AudioRecord.h
@@ -26,8 +26,8 @@
 
 #include <utils/RefBase.h>
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
-#include <utils/IMemory.h>
+#include <binder/IInterface.h>
+#include <binder/IMemory.h>
 #include <utils/threads.h>
 
 
@@ -39,21 +39,10 @@
 {
 public:
 
-    // input sources values must always be defined in the range
-    // [AudioRecord::DEFAULT_INPUT, AudioRecord::NUM_INPUT_SOURCES[
-    enum input_source {
-        DEFAULT_INPUT   =-1,
-        MIC_INPUT       = 0,
-        VOICE_UPLINK_INPUT = 1,
-        VOICE_DOWNLINK_INPUT = 2,
-        VOICE_CALL_INPUT = 3,
-        NUM_INPUT_SOURCES
-    };
-
     static const int DEFAULT_SAMPLE_RATE = 8000;
 
     /* Events used by AudioRecord callback function (callback_t).
-     * 
+     *
      * to keep in sync with frameworks/base/media/java/android/media/AudioRecord.java
      */
     enum event_type {
@@ -61,7 +50,7 @@
         EVENT_OVERRUN = 1,          // PCM buffer overrun occured.
         EVENT_MARKER = 2,           // Record head is at the specified marker position
                                     // (See setMarkerPosition()).
-        EVENT_NEW_POS = 3,          // Record head is at a new position 
+        EVENT_NEW_POS = 3,          // Record head is at a new position
                                     // (See setPositionUpdatePeriod()).
     };
 
@@ -123,11 +112,11 @@
      *
      * Parameters:
      *
-     * inputSource:        Select the audio input to record to (e.g. AudioRecord::MIC_INPUT).
+     * inputSource:        Select the audio input to record to (e.g. AUDIO_SOURCE_DEFAULT).
      * sampleRate:         Track sampling rate in Hz.
-     * format:             PCM sample format (e.g AudioSystem::PCM_16_BIT for signed
+     * format:             Audio format (e.g AudioSystem::PCM_16_BIT for signed
      *                     16 bits per sample).
-     * channelCount:       Number of PCM channels (e.g 2 for stereo).
+     * channels:           Channel mask: see AudioSystem::audio_channels.
      * frameCount:         Total size of track PCM buffer in frames. This defines the
      *                     latency of the track.
      * flags:              A bitmask of acoustic values from enum record_flags.  It enables
@@ -148,7 +137,7 @@
                         AudioRecord(int inputSource,
                                     uint32_t sampleRate = 0,
                                     int format          = 0,
-                                    int channelCount    = 0,
+                                    uint32_t channels = AudioSystem::CHANNEL_IN_MONO,
                                     int frameCount      = 0,
                                     uint32_t flags      = 0,
                                     callback_t cbf = 0,
@@ -166,14 +155,14 @@
      * Returned status (from utils/Errors.h) can be:
      *  - NO_ERROR: successful intialization
      *  - INVALID_OPERATION: AudioRecord is already intitialized or record device is already in use
-     *  - BAD_VALUE: invalid parameter (channelCount, format, sampleRate...)
+     *  - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
      *  - NO_INIT: audio server or audio hardware not initialized
      *  - PERMISSION_DENIED: recording is not allowed for the requesting process
      * */
             status_t    set(int inputSource     = 0,
                             uint32_t sampleRate = 0,
                             int format          = 0,
-                            int channelCount    = 0,
+                            uint32_t channels = AudioSystem::CHANNEL_IN_MONO,
                             int frameCount      = 0,
                             uint32_t flags      = 0,
                             callback_t cbf = 0,
@@ -199,6 +188,7 @@
 
             int         format() const;
             int         channelCount() const;
+            int         channels() const;
             uint32_t    frameCount() const;
             int         frameSize() const;
             int         inputSource() const;
@@ -222,8 +212,8 @@
 
     /* Sets marker position. When record reaches the number of frames specified,
      * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
-     * with marker == 0 cancels marker notification callback. 
-     * If the AudioRecord has been opened with no callback function associated, 
+     * with marker == 0 cancels marker notification callback.
+     * If the AudioRecord has been opened with no callback function associated,
      * the operation will fail.
      *
      * Parameters:
@@ -238,10 +228,10 @@
             status_t    getMarkerPosition(uint32_t *marker);
 
 
-    /* Sets position update period. Every time the number of frames specified has been recorded, 
-     * a callback with event type EVENT_NEW_POS is called. 
-     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification 
-     * callback. 
+    /* Sets position update period. Every time the number of frames specified has been recorded,
+     * a callback with event type EVENT_NEW_POS is called.
+     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
+     * callback.
      * If the AudioRecord has been opened with no callback function associated,
      * the operation will fail.
      *
@@ -257,8 +247,8 @@
             status_t    getPositionUpdatePeriod(uint32_t *updatePeriod);
 
 
-    /* Gets record head position. The position is the  total number of frames 
-     * recorded since record start. 
+    /* Gets record head position. The position is the  total number of frames
+     * recorded since record start.
      *
      * Parameters:
      *
@@ -270,8 +260,16 @@
      */
             status_t    getPosition(uint32_t *position);
 
-            
-            
+    /* returns a handle on the audio input used by this AudioRecord.
+     *
+     * Parameters:
+     *  none.
+     *
+     * Returned value:
+     *  handle on audio hardware input
+     */
+            audio_io_handle_t    getInput() { return mInput; }
+
     /* obtains a buffer of "frameCount" frames. The buffer must be
      * filled entirely. If the track is stopped, obtainBuffer() returns
      * STOPPED instead of NO_ERROR as long as there are buffers availlable,
@@ -342,6 +340,7 @@
     bool                    mMarkerReached;
     uint32_t                mNewPosition;
     uint32_t                mUpdatePeriod;
+    audio_io_handle_t       mInput;
 };
 
 }; // namespace android
diff --git a/include/media/AudioSystem.h b/include/media/AudioSystem.h
index 3a3a714..0ea04a4 100644
--- a/include/media/AudioSystem.h
+++ b/include/media/AudioSystem.h
@@ -24,36 +24,130 @@
 namespace android {
 
 typedef void (*audio_error_callback)(status_t err);
+typedef void * audio_io_handle_t;
+
+class IAudioPolicyService;
+class String8;
 
 class AudioSystem
 {
 public:
 
     enum stream_type {
-        DEFAULT         =-1,
-        VOICE_CALL      = 0,
-        SYSTEM          = 1,
-        RING            = 2,
-        MUSIC           = 3,
-        ALARM           = 4,
-        NOTIFICATION    = 5,
-        BLUETOOTH_SCO   = 6,
+        DEFAULT          =-1,
+        VOICE_CALL       = 0,
+        SYSTEM           = 1,
+        RING             = 2,
+        MUSIC            = 3,
+        ALARM            = 4,
+        NOTIFICATION     = 5,
+        BLUETOOTH_SCO    = 6,
         ENFORCED_AUDIBLE = 7, // Sounds that cannot be muted by user and must be routed to speaker
+        DTMF             = 8,
+        TTS              = 9,
         NUM_STREAM_TYPES
     };
 
-    enum audio_output_type {
-        AUDIO_OUTPUT_DEFAULT      =-1,
-        AUDIO_OUTPUT_HARDWARE     = 0,
-        AUDIO_OUTPUT_A2DP         = 1,
-        NUM_AUDIO_OUTPUT_TYPES
+    // Audio sub formats (see AudioSystem::audio_format).
+    enum pcm_sub_format {
+        PCM_SUB_16_BIT          = 0x1, // must be 1 for backward compatibility
+        PCM_SUB_8_BIT           = 0x2, // must be 2 for backward compatibility
     };
 
+    // MP3 sub format field definition : can use 11 LSBs in the same way as MP3 frame header to specify
+    // bit rate, stereo mode, version...
+    enum mp3_sub_format {
+        //TODO
+    };
+
+    // AMR NB/WB sub format field definition: specify frame block interleaving, bandwidth efficient or octet aligned,
+    // encoding mode for recording...
+    enum amr_sub_format {
+        //TODO
+    };
+
+    // AAC sub format field definition: specify profile or bitrate for recording...
+    enum aac_sub_format {
+        //TODO
+    };
+
+    // VORBIS sub format field definition: specify quality for recording...
+    enum vorbis_sub_format {
+        //TODO
+    };
+
+    // Audio format consists in a main format field (upper 8 bits) and a sub format field (lower 24 bits).
+    // The main format indicates the main codec type. The sub format field indicates options and parameters
+    // for each format. The sub format is mainly used for record to indicate for instance the requested bitrate
+    // or profile. It can also be used for certain formats to give informations not present in the encoded
+    // audio stream (e.g. octet alignement for AMR).
     enum audio_format {
-        FORMAT_DEFAULT = 0,
-        PCM_16_BIT,
-        PCM_8_BIT,
-        INVALID_FORMAT
+        INVALID_FORMAT      = -1,
+        FORMAT_DEFAULT      = 0,
+        PCM                 = 0x00000000, // must be 0 for backward compatibility
+        MP3                 = 0x01000000,
+        AMR_NB              = 0x02000000,
+        AMR_WB              = 0x03000000,
+        AAC                 = 0x04000000,
+        HE_AAC_V1           = 0x05000000,
+        HE_AAC_V2           = 0x06000000,
+        VORBIS              = 0x07000000,
+        MAIN_FORMAT_MASK    = 0xFF000000,
+        SUB_FORMAT_MASK     = 0x00FFFFFF,
+        // Aliases
+        PCM_16_BIT          = (PCM|PCM_SUB_16_BIT),
+        PCM_8_BIT          = (PCM|PCM_SUB_8_BIT)
+    };
+
+
+    // Channel mask definitions must be kept in sync with JAVA values in /media/java/android/media/AudioFormat.java
+    enum audio_channels {
+        // output channels
+        CHANNEL_OUT_FRONT_LEFT = 0x1,
+        CHANNEL_OUT_FRONT_RIGHT = 0x2,
+        CHANNEL_OUT_FRONT_CENTER = 0x4,
+        CHANNEL_OUT_LOW_FREQUENCY = 0x8,
+        CHANNEL_OUT_BACK_LEFT = 0x10,
+        CHANNEL_OUT_BACK_RIGHT = 0x20,
+        CHANNEL_OUT_FRONT_LEFT_OF_CENTER = 0x40,
+        CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x80,
+        CHANNEL_OUT_BACK_CENTER = 0x100,
+        CHANNEL_OUT_MONO = CHANNEL_OUT_FRONT_LEFT,
+        CHANNEL_OUT_STEREO = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT),
+        CHANNEL_OUT_QUAD = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
+                CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT),
+        CHANNEL_OUT_SURROUND = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
+                CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_BACK_CENTER),
+        CHANNEL_OUT_5POINT1 = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
+                CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT),
+        CHANNEL_OUT_7POINT1 = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
+                CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT |
+                CHANNEL_OUT_FRONT_LEFT_OF_CENTER | CHANNEL_OUT_FRONT_RIGHT_OF_CENTER),
+        CHANNEL_OUT_ALL = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
+                CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT |
+                CHANNEL_OUT_FRONT_LEFT_OF_CENTER | CHANNEL_OUT_FRONT_RIGHT_OF_CENTER | CHANNEL_OUT_BACK_CENTER),
+
+        // input channels
+        CHANNEL_IN_LEFT = 0x10000,
+        CHANNEL_IN_RIGHT = 0x20000,
+        CHANNEL_IN_FRONT = 0x40000,
+        CHANNEL_IN_BACK = 0x80000,
+        CHANNEL_IN_LEFT_PROCESSED = 0x100000,
+        CHANNEL_IN_RIGHT_PROCESSED = 0x200000,
+        CHANNEL_IN_FRONT_PROCESSED = 0x400000,
+        CHANNEL_IN_BACK_PROCESSED = 0x800000,
+        CHANNEL_IN_PRESSURE = 0x1000000,
+        CHANNEL_IN_X_AXIS = 0x2000000,
+        CHANNEL_IN_Y_AXIS = 0x4000000,
+        CHANNEL_IN_Z_AXIS = 0x8000000,
+        CHANNEL_IN_VOICE_UPLINK = 0x10000000,
+        CHANNEL_IN_VOICE_DNLINK = 0x20000000,
+        CHANNEL_IN_MONO = CHANNEL_IN_FRONT,
+        CHANNEL_IN_STEREO = (CHANNEL_IN_LEFT | CHANNEL_IN_RIGHT),
+        CHANNEL_IN_ALL = (CHANNEL_IN_LEFT | CHANNEL_IN_RIGHT | CHANNEL_IN_FRONT | CHANNEL_IN_BACK|
+                CHANNEL_IN_LEFT_PROCESSED | CHANNEL_IN_RIGHT_PROCESSED | CHANNEL_IN_FRONT_PROCESSED | CHANNEL_IN_BACK_PROCESSED|
+                CHANNEL_IN_PRESSURE | CHANNEL_IN_X_AXIS | CHANNEL_IN_Y_AXIS | CHANNEL_IN_Z_AXIS |
+                CHANNEL_IN_VOICE_UPLINK | CHANNEL_IN_VOICE_DNLINK)
     };
 
     enum audio_mode {
@@ -65,15 +159,6 @@
         NUM_MODES  // not a valid entry, denotes end-of-list
     };
 
-    enum audio_routes {
-        ROUTE_EARPIECE       = (1 << 0),
-        ROUTE_SPEAKER        = (1 << 1),
-        ROUTE_BLUETOOTH_SCO  = (1 << 2),
-        ROUTE_HEADSET        = (1 << 3),
-        ROUTE_BLUETOOTH_A2DP = (1 << 4),
-        ROUTE_ALL            = -1UL,
-    };
-
     enum audio_in_acoustics {
         AGC_ENABLE    = 0x0001,
         AGC_DISABLE   = 0,
@@ -87,36 +172,37 @@
      * only privileged processes can have access to them
      */
 
-    // routing helper functions
-    static status_t speakerphone(bool state);
-    static status_t isSpeakerphoneOn(bool* state);
-    static status_t bluetoothSco(bool state);
-    static status_t isBluetoothScoOn(bool* state);
+    // mute/unmute microphone
     static status_t muteMicrophone(bool state);
     static status_t isMicrophoneMuted(bool *state);
 
+    // set/get master volume
     static status_t setMasterVolume(float value);
-    static status_t setMasterMute(bool mute);
     static status_t getMasterVolume(float* volume);
+    // mute/unmute audio outputs
+    static status_t setMasterMute(bool mute);
     static status_t getMasterMute(bool* mute);
 
-    static status_t setStreamVolume(int stream, float value);
+    // set/get stream volume on specified output
+    static status_t setStreamVolume(int stream, float value, void *output);
+    static status_t getStreamVolume(int stream, float* volume, void *output);
+
+    // mute/unmute stream
     static status_t setStreamMute(int stream, bool mute);
-    static status_t getStreamVolume(int stream, float* volume);
     static status_t getStreamMute(int stream, bool* mute);
 
+    // set audio mode in audio hardware (see AudioSystem::audio_mode)
     static status_t setMode(int mode);
-    static status_t getMode(int* mode);
 
-    static status_t setRouting(int mode, uint32_t routes, uint32_t mask);
-    static status_t getRouting(int mode, uint32_t* routes);
-
+    // returns true if tracks are active on AudioSystem::MUSIC stream
     static status_t isMusicActive(bool *state);
 
-    // Temporary interface, do not use
-    // TODO: Replace with a more generic key:value get/set mechanism
-    static status_t setParameter(const char* key, const char* value);
-    
+    // set/get audio hardware parameters. The function accepts a list of parameters
+    // key value pairs in the form: key1=value1;key2=value2;...
+    // Some keys are reserved for standard parameters (See AudioParameter class).
+    static status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
+    static String8  getParameters(audio_io_handle_t ioHandle, const String8& keys);
+
     static void setErrorCallback(audio_error_callback cb);
 
     // helper function to obtain AudioFlinger service handle
@@ -130,47 +216,247 @@
     static status_t getOutputLatency(uint32_t* latency, int stream = DEFAULT);
 
     static bool routedToA2dpOutput(int streamType);
-    
-    static status_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount, 
+
+    static status_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount,
         size_t* buffSize);
 
+
+    //
+    // AudioPolicyService interface
+    //
+
+    enum audio_devices {
+        // output devices
+        DEVICE_OUT_EARPIECE = 0x1,
+        DEVICE_OUT_SPEAKER = 0x2,
+        DEVICE_OUT_WIRED_HEADSET = 0x4,
+        DEVICE_OUT_WIRED_HEADPHONE = 0x8,
+        DEVICE_OUT_BLUETOOTH_SCO = 0x10,
+        DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 0x20,
+        DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 0x40,
+        DEVICE_OUT_BLUETOOTH_A2DP = 0x80,
+        DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100,
+        DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 0x200,
+        DEVICE_OUT_AUX_DIGITAL = 0x400,
+        DEVICE_OUT_FM_HEADPHONE = 0x800,
+        DEVICE_OUT_FM_SPEAKER = 0x1000,
+        DEVICE_OUT_TTY = 0x2000,
+        DEVICE_OUT_DEFAULT = 0x8000,
+        DEVICE_OUT_ALL = (DEVICE_OUT_EARPIECE | DEVICE_OUT_SPEAKER | DEVICE_OUT_WIRED_HEADSET |
+                DEVICE_OUT_WIRED_HEADPHONE | DEVICE_OUT_BLUETOOTH_SCO | DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
+                DEVICE_OUT_BLUETOOTH_SCO_CARKIT | DEVICE_OUT_BLUETOOTH_A2DP | DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
+                DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER | DEVICE_OUT_AUX_DIGITAL | DEVICE_OUT_FM_HEADPHONE |
+                DEVICE_OUT_FM_SPEAKER | DEVICE_OUT_TTY | DEVICE_OUT_DEFAULT),
+
+        // input devices
+        DEVICE_IN_COMMUNICATION = 0x10000,
+        DEVICE_IN_AMBIENT = 0x20000,
+        DEVICE_IN_BUILTIN_MIC = 0x40000,
+        DEVICE_IN_BLUETOOTH_SCO_HEADSET = 0x80000,
+        DEVICE_IN_WIRED_HEADSET = 0x100000,
+        DEVICE_IN_AUX_DIGITAL = 0x200000,
+        DEVICE_IN_VOICE_CALL = 0x400000,
+        DEVICE_IN_DEFAULT = 0x80000000,
+
+        DEVICE_IN_ALL = (DEVICE_IN_COMMUNICATION | DEVICE_IN_AMBIENT | DEVICE_IN_BUILTIN_MIC |
+                DEVICE_IN_BLUETOOTH_SCO_HEADSET | DEVICE_IN_WIRED_HEADSET | DEVICE_IN_AUX_DIGITAL |
+                DEVICE_IN_VOICE_CALL| DEVICE_IN_DEFAULT)
+    };
+
+    // device connection states used for setDeviceConnectionState()
+    enum device_connection_state {
+        DEVICE_STATE_UNAVAILABLE,
+        DEVICE_STATE_AVAILABLE,
+        NUM_DEVICE_STATES
+    };
+
+    // request to open a direct output with getOutput() (by opposition to sharing an output with other AudioTracks)
+    enum output_flags {
+        OUTPUT_FLAG_INDIRECT = 0x0,
+        OUTPUT_FLAG_DIRECT = 0x1
+    };
+
+    // device categories used for setForceUse()
+    enum forced_config {
+        FORCE_NONE,
+        FORCE_SPEAKER,
+        FORCE_HEADPHONES,
+        FORCE_BT_SCO,
+        FORCE_BT_A2DP,
+        FORCE_WIRED_ACCESSORY,
+        NUM_FORCE_CONFIG,
+        FORCE_DEFAULT = FORCE_NONE
+    };
+
+    // usages used for setForceUse()
+    enum force_use {
+        FOR_COMMUNICATION,
+        FOR_MEDIA,
+        FOR_RECORD,
+        NUM_FORCE_USE
+    };
+
+    // types of io configuration change events received with ioConfigChanged()
+    enum io_config_event {
+        OUTPUT_OPENED,
+        OUTPUT_CLOSED,
+        OUTPUT_CONFIG_CHANGED,
+        INPUT_OPENED,
+        INPUT_CLOSED,
+        INPUT_CONFIG_CHANGED,
+        STREAM_CONFIG_CHANGED,
+        NUM_CONFIG_EVENTS
+    };
+
+    // audio output descritor used to cache output configurations in client process to avoid frequent calls
+    // through IAudioFlinger
+    class OutputDescriptor {
+    public:
+        OutputDescriptor()
+        : samplingRate(0), format(0), channels(0), frameCount(0), latency(0)  {}
+
+        uint32_t samplingRate;
+        int32_t format;
+        int32_t channels;
+        size_t frameCount;
+        uint32_t latency;
+    };
+
+    //
+    // IAudioPolicyService interface (see AudioPolicyInterface for method descriptions)
+    //
+    static status_t setDeviceConnectionState(audio_devices device, device_connection_state state, const char *device_address);
+    static device_connection_state getDeviceConnectionState(audio_devices device, const char *device_address);
+    static status_t setPhoneState(int state);
+    static status_t setRingerMode(uint32_t mode, uint32_t mask);
+    static status_t setForceUse(force_use usage, forced_config config);
+    static forced_config getForceUse(force_use usage);
+    static audio_io_handle_t getOutput(stream_type stream,
+                                        uint32_t samplingRate = 0,
+                                        uint32_t format = FORMAT_DEFAULT,
+                                        uint32_t channels = CHANNEL_OUT_STEREO,
+                                        output_flags flags = OUTPUT_FLAG_INDIRECT);
+    static status_t startOutput(audio_io_handle_t output, AudioSystem::stream_type stream);
+    static status_t stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream);
+    static void releaseOutput(audio_io_handle_t output);
+    static audio_io_handle_t getInput(int inputSource,
+                                    uint32_t samplingRate = 0,
+                                    uint32_t format = FORMAT_DEFAULT,
+                                    uint32_t channels = CHANNEL_IN_MONO,
+                                    audio_in_acoustics acoustics = (audio_in_acoustics)0);
+    static status_t startInput(audio_io_handle_t input);
+    static status_t stopInput(audio_io_handle_t input);
+    static void releaseInput(audio_io_handle_t input);
+    static status_t initStreamVolume(stream_type stream,
+                                      int indexMin,
+                                      int indexMax);
+    static status_t setStreamVolumeIndex(stream_type stream, int index);
+    static status_t getStreamVolumeIndex(stream_type stream, int *index);
+
+    static const sp<IAudioPolicyService>& get_audio_policy_service();
+
     // ----------------------------------------------------------------------------
 
+    static uint32_t popCount(uint32_t u);
+    static bool isOutputDevice(audio_devices device);
+    static bool isInputDevice(audio_devices device);
+    static bool isA2dpDevice(audio_devices device);
+    static bool isBluetoothScoDevice(audio_devices device);
+    static bool isLowVisibility(stream_type stream);
+    static bool isOutputChannel(uint32_t channel);
+    static bool isInputChannel(uint32_t channel);
+    static bool isValidFormat(uint32_t format);
+    static bool isLinearPCM(uint32_t format);
+
 private:
 
     class AudioFlingerClient: public IBinder::DeathRecipient, public BnAudioFlingerClient
     {
     public:
-        AudioFlingerClient() {      
+        AudioFlingerClient() {
         }
-        
+
         // DeathRecipient
         virtual void binderDied(const wp<IBinder>& who);
-        
+
         // IAudioFlingerClient
-        virtual void a2dpEnabledChanged(bool enabled);
-        
+
+        // indicate a change in the configuration of an output or input: keeps the cached
+        // values for output/input parameters upto date in client process
+        virtual void ioConfigChanged(int event, void *param1, void *param2);
     };
-    static int getOutput(int streamType);
+
+    class AudioPolicyServiceClient: public IBinder::DeathRecipient
+    {
+    public:
+        AudioPolicyServiceClient() {
+        }
+
+        // DeathRecipient
+        virtual void binderDied(const wp<IBinder>& who);
+    };
 
     static sp<AudioFlingerClient> gAudioFlingerClient;
-
+    static sp<AudioPolicyServiceClient> gAudioPolicyServiceClient;
     friend class AudioFlingerClient;
+    friend class AudioPolicyServiceClient;
 
     static Mutex gLock;
     static sp<IAudioFlinger> gAudioFlinger;
     static audio_error_callback gAudioErrorCallback;
-    static int gOutSamplingRate[NUM_AUDIO_OUTPUT_TYPES];
-    static int gOutFrameCount[NUM_AUDIO_OUTPUT_TYPES];
-    static uint32_t gOutLatency[NUM_AUDIO_OUTPUT_TYPES];
-    static bool gA2dpEnabled;
-    
+
     static size_t gInBuffSize;
     // previous parameters for recording buffer size queries
     static uint32_t gPrevInSamplingRate;
     static int gPrevInFormat;
     static int gPrevInChannelCount;
 
+    static sp<IAudioPolicyService> gAudioPolicyService;
+
+    // mapping between stream types and outputs
+    static DefaultKeyedVector<int, audio_io_handle_t> gStreamOutputMap;
+    // list of output descritor containing cached parameters (sampling rate, framecount, channel count...)
+    static DefaultKeyedVector<audio_io_handle_t, OutputDescriptor *> gOutputs;
+};
+
+class AudioParameter {
+
+public:
+    AudioParameter() {}
+    AudioParameter(const String8& keyValuePairs);
+    virtual ~AudioParameter();
+
+    // reserved parameter keys for changeing standard parameters with setParameters() function.
+    // Using these keys is mandatory for AudioFlinger to properly monitor audio output/input
+    // configuration changes and act accordingly.
+    //  keyRouting: to change audio routing, value is an int in AudioSystem::audio_devices
+    //  keySamplingRate: to change sampling rate routing, value is an int
+    //  keyFormat: to change audio format, value is an int in AudioSystem::audio_format
+    //  keyChannels: to change audio channel configuration, value is an int in AudioSystem::audio_channels
+    //  keyFrameCount: to change audio output frame count, value is an int
+    static const char *keyRouting;
+    static const char *keySamplingRate;
+    static const char *keyFormat;
+    static const char *keyChannels;
+    static const char *keyFrameCount;
+
+    String8 toString();
+
+    status_t add(const String8& key, const String8& value);
+    status_t addInt(const String8& key, const int value);
+    status_t addFloat(const String8& key, const float value);
+
+    status_t remove(const String8& key);
+
+    status_t get(const String8& key, String8& value);
+    status_t getInt(const String8& key, int& value);
+    status_t getFloat(const String8& key, float& value);
+
+    size_t size() { return mParameters.size(); }
+
+private:
+    String8 mKeyValuePairs;
+    KeyedVector <String8, String8> mParameters;
 };
 
 };  // namespace android
diff --git a/include/media/AudioTrack.h b/include/media/AudioTrack.h
index 7c86a65..981c2f6 100644
--- a/include/media/AudioTrack.h
+++ b/include/media/AudioTrack.h
@@ -26,8 +26,8 @@
 
 #include <utils/RefBase.h>
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
-#include <utils/IMemory.h>
+#include <binder/IInterface.h>
+#include <binder/IMemory.h>
 #include <utils/threads.h>
 
 
@@ -117,9 +117,9 @@
      * streamType:         Select the type of audio stream this track is attached to
      *                     (e.g. AudioSystem::MUSIC).
      * sampleRate:         Track sampling rate in Hz.
-     * format:             PCM sample format (e.g AudioSystem::PCM_16_BIT for signed
+     * format:             Audio format (e.g AudioSystem::PCM_16_BIT for signed
      *                     16 bits per sample).
-     * channelCount:       Number of PCM channels (e.g 2 for stereo).
+     * channels:           Channel mask: see AudioSystem::audio_channels.
      * frameCount:         Total size of track PCM buffer in frames. This defines the
      *                     latency of the track.
      * flags:              Reserved for future use.
@@ -133,7 +133,7 @@
                         AudioTrack( int streamType,
                                     uint32_t sampleRate  = 0,
                                     int format           = 0,
-                                    int channelCount     = 0,
+                                    int channels         = 0,
                                     int frameCount       = 0,
                                     uint32_t flags       = 0,
                                     callback_t cbf       = 0,
@@ -152,7 +152,7 @@
                         AudioTrack( int streamType,
                                     uint32_t sampleRate = 0,
                                     int format          = 0,
-                                    int channelCount    = 0,
+                                    int channels        = 0,
                                     const sp<IMemory>& sharedBuffer = 0,
                                     uint32_t flags      = 0,
                                     callback_t cbf      = 0,
@@ -169,13 +169,13 @@
      * Returned status (from utils/Errors.h) can be:
      *  - NO_ERROR: successful intialization
      *  - INVALID_OPERATION: AudioTrack is already intitialized
-     *  - BAD_VALUE: invalid parameter (channelCount, format, sampleRate...)
+     *  - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
      *  - NO_INIT: audio server or audio hardware not initialized
      * */
             status_t    set(int streamType      =-1,
                             uint32_t sampleRate = 0,
                             int format          = 0,
-                            int channelCount    = 0,
+                            int channels        = 0,
                             int frameCount      = 0,
                             uint32_t flags      = 0,
                             callback_t cbf      = 0,
@@ -330,6 +330,16 @@
      */
             status_t    reload();
 
+    /* returns a handle on the audio output used by this AudioTrack.
+     *
+     * Parameters:
+     *  none.
+     *
+     * Returned value:
+     *  handle on audio hardware output
+     */
+            audio_io_handle_t    getOutput();
+
     /* obtains a buffer of "frameCount" frames. The buffer must be
      * filled entirely. If the track is stopped, obtainBuffer() returns
      * STOPPED instead of NO_ERROR as long as there are buffers availlable,
@@ -387,7 +397,6 @@
     sp<AudioTrackThread>    mAudioTrackThread;
 
     float                   mVolume[2];
-    uint32_t                mSampleRate;
     uint32_t                mFrameCount;
 
     audio_track_cblk_t*     mCblk;
@@ -395,6 +404,7 @@
     uint8_t                 mFormat;
     uint8_t                 mChannelCount;
     uint8_t                 mMuted;
+    uint32_t                mChannels;
     status_t                mStatus;
     uint32_t                mLatency;
 
@@ -410,6 +420,7 @@
     bool                    mMarkerReached;
     uint32_t                mNewPosition;
     uint32_t                mUpdatePeriod;
+    uint32_t                mFlags;
 };
 
 
diff --git a/include/media/IAudioFlinger.h b/include/media/IAudioFlinger.h
index 3e59d85..26e6972 100644
--- a/include/media/IAudioFlinger.h
+++ b/include/media/IAudioFlinger.h
@@ -23,11 +23,11 @@
 
 #include <utils/RefBase.h>
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
+#include <binder/IInterface.h>
 #include <media/IAudioTrack.h>
 #include <media/IAudioRecord.h>
 #include <media/IAudioFlingerClient.h>
-
+#include <utils/String8.h>
 
 namespace android {
 
@@ -50,11 +50,12 @@
                                 int frameCount,
                                 uint32_t flags,
                                 const sp<IMemory>& sharedBuffer,
+                                void *output,
                                 status_t *status) = 0;
 
     virtual sp<IAudioRecord> openRecord(
                                 pid_t pid,
-                                int inputSource,
+                                void *input,
                                 uint32_t sampleRate,
                                 int format,
                                 int channelCount,
@@ -65,11 +66,11 @@
     /* query the audio hardware state. This state never changes,
      * and therefore can be cached.
      */
-    virtual     uint32_t    sampleRate(int output) const = 0;
-    virtual     int         channelCount(int output) const = 0;
-    virtual     int         format(int output) const = 0;
-    virtual     size_t      frameCount(int output) const = 0;
-    virtual     uint32_t    latency(int output) const = 0;
+    virtual     uint32_t    sampleRate(void *output) const = 0;
+    virtual     int         channelCount(void *output) const = 0;
+    virtual     int         format(void *output) const = 0;
+    virtual     size_t      frameCount(void *output) const = 0;
+    virtual     uint32_t    latency(void *output) const = 0;
 
     /* set/get the audio hardware state. This will probably be used by
      * the preference panel, mostly.
@@ -83,19 +84,14 @@
     /* set/get stream type state. This will probably be used by
      * the preference panel, mostly.
      */
-    virtual     status_t    setStreamVolume(int stream, float value) = 0;
+    virtual     status_t    setStreamVolume(int stream, float value, void *output) = 0;
     virtual     status_t    setStreamMute(int stream, bool muted) = 0;
 
-    virtual     float       streamVolume(int stream) const = 0;
+    virtual     float       streamVolume(int stream, void *output) const = 0;
     virtual     bool        streamMute(int stream) const = 0;
 
-    // set/get audio routing
-    virtual     status_t    setRouting(int mode, uint32_t routes, uint32_t mask) = 0;
-    virtual     uint32_t    getRouting(int mode) const = 0;
-
-    // set/get audio mode
+    // set audio mode
     virtual     status_t    setMode(int mode) = 0;
-    virtual     int         getMode() const = 0;
 
     // mic mute/state
     virtual     status_t    setMicMute(bool state) = 0;
@@ -104,22 +100,34 @@
     // is a music stream active?
     virtual     bool        isMusicActive() const = 0;
 
-    // pass a generic configuration parameter to libaudio
-    // Temporary interface, do not use
-    // TODO: Replace with a more generic key:value get/set mechanism
-    virtual     status_t  setParameter(const char* key, const char* value) = 0;
+    virtual     status_t    setParameters(void *ioHandle, const String8& keyValuePairs) = 0;
+    virtual     String8     getParameters(void *ioHandle, const String8& keys) = 0;
     
     // register a current process for audio output change notifications
     virtual void registerClient(const sp<IAudioFlingerClient>& client) = 0;
     
     // retrieve the audio recording buffer size
     virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount) = 0;
-    
-    // force AudioFlinger thread out of standby
-    virtual     void        wakeUp() = 0;
 
-    // is A2DP output enabled
-    virtual     bool        isA2dpEnabled() const = 0;
+    virtual void *openOutput(uint32_t *pDevices,
+                                    uint32_t *pSamplingRate,
+                                    uint32_t *pFormat,
+                                    uint32_t *pChannels,
+                                    uint32_t *pLatencyMs,
+                                    uint32_t flags) = 0;
+    virtual void *openDuplicateOutput(void *output1, void *output2) = 0;
+    virtual status_t closeOutput(void *output) = 0;
+    virtual status_t suspendOutput(void *output) = 0;
+    virtual status_t restoreOutput(void *output) = 0;
+
+    virtual void *openInput(uint32_t *pDevices,
+                                    uint32_t *pSamplingRate,
+                                    uint32_t *pFormat,
+                                    uint32_t *pChannels,
+                                    uint32_t acoustics) = 0;
+    virtual status_t closeInput(void *input) = 0;
+
+    virtual status_t setStreamOutput(uint32_t stream, void *output) = 0;
 };
 
 
diff --git a/include/media/IAudioFlingerClient.h b/include/media/IAudioFlingerClient.h
index c3deb0b..78142ce 100644
--- a/include/media/IAudioFlingerClient.h
+++ b/include/media/IAudioFlingerClient.h
@@ -19,8 +19,8 @@
 
 
 #include <utils/RefBase.h>
-#include <utils/IInterface.h>
-
+#include <binder/IInterface.h>
+#include <utils/KeyedVector.h>
 
 namespace android {
 
@@ -31,8 +31,8 @@
 public:
     DECLARE_META_INTERFACE(AudioFlingerClient);
 
-    // Notifies a change of audio output from/to hardware to/from A2DP.
-    virtual void a2dpEnabledChanged(bool enabled) = 0;
+    // Notifies a change of audio input/output configuration.
+    virtual void ioConfigChanged(int event, void *param1, void *param2) = 0;
 
 };
 
diff --git a/include/media/IAudioPolicyService.h b/include/media/IAudioPolicyService.h
new file mode 100644
index 0000000..4804bbd
--- /dev/null
+++ b/include/media/IAudioPolicyService.h
@@ -0,0 +1,90 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_IAUDIOPOLICYSERVICE_H
+#define ANDROID_IAUDIOPOLICYSERVICE_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <utils/RefBase.h>
+#include <utils/Errors.h>
+#include <binder/IInterface.h>
+#include <media/AudioSystem.h>
+
+
+namespace android {
+
+// ----------------------------------------------------------------------------
+
+class IAudioPolicyService : public IInterface
+{
+public:
+    DECLARE_META_INTERFACE(AudioPolicyService);
+
+    //
+    // IAudioPolicyService interface (see AudioPolicyInterface for method descriptions)
+    //
+    virtual status_t setDeviceConnectionState(AudioSystem::audio_devices device,
+                                              AudioSystem::device_connection_state state,
+                                              const char *device_address) = 0;
+    virtual AudioSystem::device_connection_state getDeviceConnectionState(AudioSystem::audio_devices device,
+                                                                          const char *device_address) = 0;
+    virtual status_t setPhoneState(int state) = 0;
+    virtual status_t setRingerMode(uint32_t mode, uint32_t mask) = 0;
+    virtual status_t setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config) = 0;
+    virtual AudioSystem::forced_config getForceUse(AudioSystem::force_use usage) = 0;
+    virtual audio_io_handle_t getOutput(AudioSystem::stream_type stream,
+                                        uint32_t samplingRate = 0,
+                                        uint32_t format = AudioSystem::FORMAT_DEFAULT,
+                                        uint32_t channels = 0,
+                                        AudioSystem::output_flags flags = AudioSystem::OUTPUT_FLAG_INDIRECT) = 0;
+    virtual status_t startOutput(audio_io_handle_t output, AudioSystem::stream_type stream) = 0;
+    virtual status_t stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream) = 0;
+    virtual void releaseOutput(audio_io_handle_t output) = 0;
+    virtual audio_io_handle_t getInput(int inputSource,
+                                    uint32_t samplingRate = 0,
+                                    uint32_t format = AudioSystem::FORMAT_DEFAULT,
+                                    uint32_t channels = 0,
+                                    AudioSystem::audio_in_acoustics acoustics = (AudioSystem::audio_in_acoustics)0) = 0;
+    virtual status_t startInput(audio_io_handle_t input) = 0;
+    virtual status_t stopInput(audio_io_handle_t input) = 0;
+    virtual void releaseInput(audio_io_handle_t input) = 0;
+    virtual status_t initStreamVolume(AudioSystem::stream_type stream,
+                                      int indexMin,
+                                      int indexMax) = 0;
+    virtual status_t setStreamVolumeIndex(AudioSystem::stream_type stream, int index) = 0;
+    virtual status_t getStreamVolumeIndex(AudioSystem::stream_type stream, int *index) = 0;
+};
+
+
+// ----------------------------------------------------------------------------
+
+class BnAudioPolicyService : public BnInterface<IAudioPolicyService>
+{
+public:
+    virtual status_t    onTransact( uint32_t code,
+                                    const Parcel& data,
+                                    Parcel* reply,
+                                    uint32_t flags = 0);
+};
+
+// ----------------------------------------------------------------------------
+
+}; // namespace android
+
+#endif // ANDROID_IAUDIOPOLICYSERVICE_H
diff --git a/include/media/IAudioRecord.h b/include/media/IAudioRecord.h
index 9d45d2d9..46735de 100644
--- a/include/media/IAudioRecord.h
+++ b/include/media/IAudioRecord.h
@@ -22,8 +22,8 @@
 
 #include <utils/RefBase.h>
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
-#include <utils/IMemory.h>
+#include <binder/IInterface.h>
+#include <binder/IMemory.h>
 
 
 namespace android {
diff --git a/include/media/IAudioTrack.h b/include/media/IAudioTrack.h
index 12f2111..de6426a 100644
--- a/include/media/IAudioTrack.h
+++ b/include/media/IAudioTrack.h
@@ -22,8 +22,8 @@
 
 #include <utils/RefBase.h>
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
-#include <utils/IMemory.h>
+#include <binder/IInterface.h>
+#include <binder/IMemory.h>
 
 
 namespace android {
diff --git a/include/media/IMediaMetadataRetriever.h b/include/media/IMediaMetadataRetriever.h
index c677e83..9baba8e 100644
--- a/include/media/IMediaMetadataRetriever.h
+++ b/include/media/IMediaMetadataRetriever.h
@@ -19,9 +19,9 @@
 #define ANDROID_IMEDIAMETADATARETRIEVER_H
 
 #include <utils/RefBase.h>
-#include <utils/IInterface.h>
-#include <utils/Parcel.h>
-#include <utils/IMemory.h>
+#include <binder/IInterface.h>
+#include <binder/Parcel.h>
+#include <binder/IMemory.h>
 
 namespace android {
 
diff --git a/include/media/IMediaPlayer.h b/include/media/IMediaPlayer.h
index a683e74..b6f654f 100644
--- a/include/media/IMediaPlayer.h
+++ b/include/media/IMediaPlayer.h
@@ -18,11 +18,12 @@
 #define ANDROID_IMEDIAPLAYER_H
 
 #include <utils/RefBase.h>
-#include <utils/IInterface.h>
-#include <utils/Parcel.h>
+#include <binder/IInterface.h>
+#include <binder/Parcel.h>
 
 namespace android {
 
+class Parcel;
 class ISurface;
 
 class IMediaPlayer: public IInterface
@@ -45,6 +46,36 @@
     virtual status_t        setAudioStreamType(int type) = 0;
     virtual status_t        setLooping(int loop) = 0;
     virtual status_t        setVolume(float leftVolume, float rightVolume) = 0;
+
+    // Invoke a generic method on the player by using opaque parcels
+    // for the request and reply.
+    // @param request Parcel that must start with the media player
+    // interface token.
+    // @param[out] reply Parcel to hold the reply data. Cannot be null.
+    // @return OK if the invocation was made successfully.
+    virtual status_t        invoke(const Parcel& request, Parcel *reply) = 0;
+
+    // Set a new metadata filter.
+    // @param filter A set of allow and drop rules serialized in a Parcel.
+    // @return OK if the invocation was made successfully.
+    virtual status_t        setMetadataFilter(const Parcel& filter) = 0;
+
+    // Retrieve a set of metadata.
+    // @param update_only Include only the metadata that have changed
+    //                    since the last invocation of getMetadata.
+    //                    The set is built using the unfiltered
+    //                    notifications the native player sent to the
+    //                    MediaPlayerService during that period of
+    //                    time. If false, all the metadatas are considered.
+    // @param apply_filter If true, once the metadata set has been built based
+    //                     on the value update_only, the current filter is
+    //                     applied.
+    // @param[out] metadata On exit contains a set (possibly empty) of metadata.
+    //                      Valid only if the call returned OK.
+    // @return OK if the invocation was made successfully.
+    virtual status_t        getMetadata(bool update_only,
+                                        bool apply_filter,
+                                        Parcel *metadata) = 0;
 };
 
 // ----------------------------------------------------------------------------
@@ -61,4 +92,3 @@
 }; // namespace android
 
 #endif // ANDROID_IMEDIAPLAYER_H
-
diff --git a/include/media/IMediaPlayerClient.h b/include/media/IMediaPlayerClient.h
index 5d32811..eee6c97 100644
--- a/include/media/IMediaPlayerClient.h
+++ b/include/media/IMediaPlayerClient.h
@@ -18,8 +18,8 @@
 #define ANDROID_IMEDIAPLAYERCLIENT_H
 
 #include <utils/RefBase.h>
-#include <utils/IInterface.h>
-#include <utils/Parcel.h>
+#include <binder/IInterface.h>
+#include <binder/Parcel.h>
 
 namespace android {
 
diff --git a/include/media/IMediaPlayerService.h b/include/media/IMediaPlayerService.h
index d1d96b1..39b5e57 100644
--- a/include/media/IMediaPlayerService.h
+++ b/include/media/IMediaPlayerService.h
@@ -17,9 +17,10 @@
 #ifndef ANDROID_IMEDIAPLAYERSERVICE_H
 #define ANDROID_IMEDIAPLAYERSERVICE_H
 
+#include <utils/Errors.h>  // for status_t
 #include <utils/RefBase.h>
-#include <utils/IInterface.h>
-#include <utils/Parcel.h>
+#include <binder/IInterface.h>
+#include <binder/Parcel.h>
 
 #include <media/IMediaPlayerClient.h>
 #include <media/IMediaPlayer.h>
@@ -28,6 +29,7 @@
 namespace android {
 
 class IMediaRecorder;
+class IOMX;
 
 class IMediaPlayerService: public IInterface
 {
@@ -36,11 +38,11 @@
 
     virtual sp<IMediaRecorder>  createMediaRecorder(pid_t pid) = 0;
     virtual sp<IMediaMetadataRetriever> createMetadataRetriever(pid_t pid) = 0;
-
     virtual sp<IMediaPlayer>    create(pid_t pid, const sp<IMediaPlayerClient>& client, const char* url) = 0;
     virtual sp<IMediaPlayer>    create(pid_t pid, const sp<IMediaPlayerClient>& client, int fd, int64_t offset, int64_t length) = 0;
     virtual sp<IMemory>         decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) = 0;
     virtual sp<IMemory>         decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) = 0;
+    virtual sp<IOMX>            createOMX() = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/media/IMediaRecorder.h b/include/media/IMediaRecorder.h
index 64d3a40..24ac82b 100644
--- a/include/media/IMediaRecorder.h
+++ b/include/media/IMediaRecorder.h
@@ -18,7 +18,7 @@
 #ifndef ANDROID_IMEDIARECORDER_H
 #define ANDROID_IMEDIARECORDER_H
 
-#include <utils/IInterface.h>
+#include <binder/IInterface.h>
 
 namespace android {
 
diff --git a/include/media/IOMX.h b/include/media/IOMX.h
new file mode 100644
index 0000000..5c61c50
--- /dev/null
+++ b/include/media/IOMX.h
@@ -0,0 +1,176 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_IOMX_H_
+
+#define ANDROID_IOMX_H_
+
+#include <binder/IInterface.h>
+#include <utils/List.h>
+#include <utils/String8.h>
+
+#include <OMX_Core.h>
+
+#define IOMX_USES_SOCKETS       0
+
+namespace android {
+
+class IMemory;
+class IOMXObserver;
+
+class IOMX : public IInterface {
+public:
+    DECLARE_META_INTERFACE(OMX);
+
+    typedef void *buffer_id;
+    typedef void *node_id;
+
+#if IOMX_USES_SOCKETS
+    // If successful, returns a socket descriptor used for further
+    // communication. Caller assumes ownership of "*sd".
+    virtual status_t connect(int *sd) = 0;
+#endif
+
+    virtual status_t list_nodes(List<String8> *list) = 0;
+
+    virtual status_t allocate_node(const char *name, node_id *node) = 0;
+    virtual status_t free_node(node_id node) = 0;
+
+    virtual status_t send_command(
+            node_id node, OMX_COMMANDTYPE cmd, OMX_S32 param) = 0;
+
+    virtual status_t get_parameter(
+            node_id node, OMX_INDEXTYPE index,
+            void *params, size_t size) = 0;
+
+    virtual status_t set_parameter(
+            node_id node, OMX_INDEXTYPE index,
+            const void *params, size_t size) = 0;
+
+    virtual status_t use_buffer(
+            node_id node, OMX_U32 port_index, const sp<IMemory> &params,
+            buffer_id *buffer) = 0;
+
+    virtual status_t allocate_buffer(
+            node_id node, OMX_U32 port_index, size_t size,
+            buffer_id *buffer) = 0;
+
+    virtual status_t allocate_buffer_with_backup(
+            node_id node, OMX_U32 port_index, const sp<IMemory> &params,
+            buffer_id *buffer) = 0;
+
+    virtual status_t free_buffer(
+            node_id node, OMX_U32 port_index, buffer_id buffer) = 0;
+
+#if !IOMX_USES_SOCKETS
+    virtual status_t observe_node(
+            node_id node, const sp<IOMXObserver> &observer) = 0;
+
+    virtual void fill_buffer(node_id node, buffer_id buffer) = 0;
+
+    virtual void empty_buffer(
+            node_id node,
+            buffer_id buffer,
+            OMX_U32 range_offset, OMX_U32 range_length,
+            OMX_U32 flags, OMX_TICKS timestamp) = 0;
+#endif
+};
+
+struct omx_message {
+    enum {
+        EVENT,
+        EMPTY_BUFFER_DONE,
+        FILL_BUFFER_DONE,
+
+#if IOMX_USES_SOCKETS
+        EMPTY_BUFFER,
+        FILL_BUFFER,
+        SEND_COMMAND,
+        DISCONNECT,
+        DISCONNECTED,
+#endif
+
+        // reserved for OMXDecoder use.
+        START,
+        INITIAL_FILL_BUFFER,
+
+        // reserved for OMXObserver use.
+        QUIT_OBSERVER,
+    } type;
+
+    union {
+        // if type == EVENT
+        struct {
+            IOMX::node_id node;
+            OMX_EVENTTYPE event;
+            OMX_U32 data1;
+            OMX_U32 data2;
+        } event_data;
+
+        // if type == EMPTY_BUFFER_DONE || type == FILL_BUFFER
+        //    || type == INITIAL_FILL_BUFFER
+        struct {
+            IOMX::node_id node;
+            IOMX::buffer_id buffer;
+        } buffer_data;
+
+        // if type == EMPTY_BUFFER || type == FILL_BUFFER_DONE
+        struct {
+            IOMX::node_id node;
+            IOMX::buffer_id buffer;
+            OMX_U32 range_offset;
+            OMX_U32 range_length;
+            OMX_U32 flags;
+            OMX_TICKS timestamp;
+            OMX_PTR platform_private;  // ignored if type == EMPTY_BUFFER
+        } extended_buffer_data;
+
+        // if type == SEND_COMMAND
+        struct {
+            IOMX::node_id node;
+            OMX_COMMANDTYPE cmd;
+            OMX_S32 param;
+        } send_command_data;
+
+    } u;
+};
+
+class IOMXObserver : public IInterface {
+public:
+    DECLARE_META_INTERFACE(OMXObserver);
+
+    virtual void on_message(const omx_message &msg) = 0;
+};
+
+////////////////////////////////////////////////////////////////////////////////
+
+class BnOMX : public BnInterface<IOMX> {
+public:
+    virtual status_t onTransact(
+            uint32_t code, const Parcel &data, Parcel *reply,
+            uint32_t flags = 0);
+};
+
+class BnOMXObserver : public BnInterface<IOMXObserver> {
+public:
+    virtual status_t onTransact(
+            uint32_t code, const Parcel &data, Parcel *reply,
+            uint32_t flags = 0);
+};
+
+}  // namespace android
+
+#endif  // ANDROID_IOMX_H_
diff --git a/include/media/MediaPlayerInterface.h b/include/media/MediaPlayerInterface.h
index 7bf555a..f723cfd 100644
--- a/include/media/MediaPlayerInterface.h
+++ b/include/media/MediaPlayerInterface.h
@@ -19,20 +19,32 @@
 
 #ifdef __cplusplus
 
+#include <sys/types.h>
 #include <ui/ISurface.h>
 #include <utils/RefBase.h>
+#include <utils/Errors.h>
 
 #include <media/mediaplayer.h>
 #include <media/AudioSystem.h>
+#include <media/Metadata.h>
 
 namespace android {
 
+class Parcel;
+template<typename T> class SortedVector;
+
 enum player_type {
     PV_PLAYER = 1,
     SONIVOX_PLAYER = 2,
-    VORBIS_PLAYER = 3
+    VORBIS_PLAYER = 3,
+    STAGEFRIGHT_PLAYER = 4,
+    // Test players are available only in the 'test' and 'eng' builds.
+    // The shared library with the test player is passed passed as an
+    // argument to the 'test:' url in the setDataSource call.
+    TEST_PLAYER = 5,
 };
 
+
 #define DEFAULT_AUDIOSINK_BUFFERCOUNT 4
 #define DEFAULT_AUDIOSINK_BUFFERSIZE 1200
 #define DEFAULT_AUDIOSINK_SAMPLERATE 44100
@@ -45,10 +57,12 @@
 class MediaPlayerBase : public RefBase
 {
 public:
-
     // AudioSink: abstraction layer for audio output
     class AudioSink : public RefBase {
     public:
+        typedef void (*AudioCallback)(
+                AudioSink *audioSink, void *buffer, size_t size, void *cookie);
+
         virtual             ~AudioSink() {}
         virtual bool        ready() const = 0; // audio output is open and ready
         virtual bool        realtime() const = 0; // audio output is real-time output
@@ -58,7 +72,17 @@
         virtual ssize_t     frameSize() const = 0;
         virtual uint32_t    latency() const = 0;
         virtual float       msecsPerFrame() const = 0;
-        virtual status_t    open(uint32_t sampleRate, int channelCount, int format=AudioSystem::PCM_16_BIT, int bufferCount=DEFAULT_AUDIOSINK_BUFFERCOUNT) = 0;
+
+        // If no callback is specified, use the "write" API below to submit
+        // audio data. Otherwise return a full buffer of audio data on each
+        // callback.
+        virtual status_t    open(
+                uint32_t sampleRate, int channelCount,
+                int format=AudioSystem::PCM_16_BIT,
+                int bufferCount=DEFAULT_AUDIOSINK_BUFFERCOUNT,
+                AudioCallback cb = NULL,
+                void *cookie = NULL) = 0;
+
         virtual void        start() = 0;
         virtual ssize_t     write(const void* buffer, size_t size) = 0;
         virtual void        stop() = 0;
@@ -88,6 +112,26 @@
     virtual player_type playerType() = 0;
     virtual void        setNotifyCallback(void* cookie, notify_callback_f notifyFunc) {
                             mCookie = cookie; mNotify = notifyFunc; }
+    // Invoke a generic method on the player by using opaque parcels
+    // for the request and reply.
+    //
+    // @param request Parcel that is positioned at the start of the
+    //                data sent by the java layer.
+    // @param[out] reply Parcel to hold the reply data. Cannot be null.
+    // @return OK if the call was successful.
+    virtual status_t    invoke(const Parcel& request, Parcel *reply) = 0;
+
+    // The Client in the MetadataPlayerService calls this method on
+    // the native player to retrieve all or a subset of metadata.
+    //
+    // @param ids SortedList of metadata ID to be fetch. If empty, all
+    //            the known metadata should be returned.
+    // @param[inout] records Parcel where the player appends its metadata.
+    // @return OK if the call was successful.
+    virtual status_t    getMetadata(const media::Metadata::Filter& ids,
+                                    Parcel *records) {
+        return INVALID_OPERATION;
+    };
 
 protected:
     virtual void        sendEvent(int msg, int ext1=0, int ext2=0) { if (mNotify) mNotify(mCookie, msg, ext1, ext2); }
diff --git a/include/media/Metadata.h b/include/media/Metadata.h
new file mode 100644
index 0000000..241868a
--- /dev/null
+++ b/include/media/Metadata.h
@@ -0,0 +1,133 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_MEDIA_METADATA_H__
+#define ANDROID_MEDIA_METADATA_H__
+
+#include <sys/types.h>
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+#include <utils/SortedVector.h>
+
+namespace android {
+class Parcel;
+
+namespace media {
+
+// Metadata is a class to build/serialize a set of metadata in a Parcel.
+//
+// This class should be kept in sync with android/media/Metadata.java.
+// It provides all the metadata ids available and methods to build the
+// header, add records and adjust the set size header field.
+//
+// Typical Usage:
+// ==============
+//  Parcel p;
+//  media::Metadata data(&p);
+//
+//  data.appendHeader();
+//  data.appendBool(Metadata::kPauseAvailable, true);
+//   ... more append ...
+//  data.updateLength();
+//
+
+class Metadata {
+  public:
+    typedef int32_t Type;
+    typedef SortedVector<Type> Filter;
+
+    static const Type kAny = 0;
+
+    // Keep in sync with android/media/Metadata.java
+    static const Type kTitle = 1;           // String
+    static const Type kComment = 2;         // String
+    static const Type kCopyright = 3;       // String
+    static const Type kAlbum = 4;           // String
+    static const Type kArtist = 5;          // String
+    static const Type kAuthor = 6;          // String
+    static const Type kComposer = 7;        // String
+    static const Type kGenre = 8;           // String
+    static const Type kDate = 9;            // Date
+    static const Type kDuration = 10;       // Integer(millisec)
+    static const Type kCdTrackNum = 11;     // Integer 1-based
+    static const Type kCdTrackMax = 12;     // Integer
+    static const Type kRating = 13;         // String
+    static const Type kAlbumArt = 14;       // byte[]
+    static const Type kVideoFrame = 15;     // Bitmap
+    static const Type kCaption = 16;        // TimedText
+
+    static const Type kBitRate = 17;       // Integer, Aggregate rate of
+    // all the streams in bps.
+
+    static const Type kAudioBitRate = 18; // Integer, bps
+    static const Type kVideoBitRate = 19; // Integer, bps
+    static const Type kAudioSampleRate = 20; // Integer, Hz
+    static const Type kVideoframeRate = 21;  // Integer, Hz
+
+    // See RFC2046 and RFC4281.
+    static const Type kMimeType = 22;      // String
+    static const Type kAudioCodec = 23;    // String
+    static const Type kVideoCodec = 24;    // String
+
+    static const Type kVideoHeight = 25;   // Integer
+    static const Type kVideoWidth = 26;    // Integer
+    static const Type kNumTracks = 27;     // Integer
+    static const Type kDrmCrippled = 28;   // Boolean
+
+    // Playback capabilities.
+    static const Type kPauseAvailable = 29;        // Boolean
+    static const Type kSeekBackwardAvailable = 30; // Boolean
+    static const Type kSeekForwardAvailable = 31;  // Boolean
+
+    // @param p[inout] The parcel to append the metadata records
+    // to. The global metadata header should have been set already.
+    explicit Metadata(Parcel *p);
+    ~Metadata();
+
+    // Rewind the underlying parcel, undoing all the changes.
+    void resetParcel();
+
+    // Append the size and 'META' marker.
+    bool appendHeader();
+
+    // Once all the records have been added, call this to update the
+    // lenght field in the header.
+    void updateLength();
+
+    // append* are methods to append metadata.
+    // @param key Is the metadata Id.
+    // @param val Is the value of the metadata.
+    // @return true if successful, false otherwise.
+    // TODO: add more as needed to handle other types.
+    bool appendBool(Type key, bool val);
+    bool appendInt32(Type key, int32_t val);
+
+  private:
+    Metadata(const Metadata&);
+    Metadata& operator=(const Metadata&);
+
+
+    // Checks the key is valid and not already present.
+    bool checkKey(Type key);
+
+    Parcel *mData;
+    size_t mBegin;
+};
+
+}  // namespace android::media
+}  // namespace android
+
+#endif  // ANDROID_MEDIA_METADATA_H__
diff --git a/include/media/PVPlayer.h b/include/media/PVPlayer.h
index 8122df6..8a66152 100644
--- a/include/media/PVPlayer.h
+++ b/include/media/PVPlayer.h
@@ -19,6 +19,7 @@
 
 #include <utils/Errors.h>
 #include <media/MediaPlayerInterface.h>
+#include <media/Metadata.h>
 
 #define MAX_OPENCORE_INSTANCES 25
 
@@ -52,6 +53,10 @@
     virtual status_t    reset();
     virtual status_t    setLooping(int loop);
     virtual player_type playerType() { return PV_PLAYER; }
+    virtual status_t    invoke(const Parcel& request, Parcel *reply);
+    virtual status_t    getMetadata(
+        const SortedVector<media::Metadata::Type>& ids,
+        Parcel *records);
 
     // make available to PlayerDriver
     void        sendEvent(int msg, int ext1=0, int ext2=0) { MediaPlayerBase::sendEvent(msg, ext1, ext2); }
@@ -62,6 +67,7 @@
     static void         run_set_video_surface(status_t s, void *cookie, bool cancelled);
     static void         run_set_audio_output(status_t s, void *cookie, bool cancelled);
     static void         run_prepare(status_t s, void *cookie, bool cancelled);
+    static void         check_for_live_streaming(status_t s, void *cookie, bool cancelled);
 
     PlayerDriver*               mPlayerDriver;
     char *                      mDataSourcePath;
diff --git a/include/media/mediametadataretriever.h b/include/media/mediametadataretriever.h
index f2719d3..3db8a0f 100644
--- a/include/media/mediametadataretriever.h
+++ b/include/media/mediametadataretriever.h
@@ -20,7 +20,7 @@
 
 #include <utils/Errors.h>  // for status_t
 #include <utils/threads.h>
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 #include <media/IMediaMetadataRetriever.h>
 
 namespace android {
diff --git a/include/media/mediaplayer.h b/include/media/mediaplayer.h
index 513ffe1..26b054bd 100644
--- a/include/media/mediaplayer.h
+++ b/include/media/mediaplayer.h
@@ -17,7 +17,7 @@
 #ifndef ANDROID_MEDIAPLAYER_H
 #define ANDROID_MEDIAPLAYER_H
 
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 #include <ui/Surface.h>
 #include <media/IMediaPlayerClient.h>
 #include <media/IMediaPlayer.h>
@@ -97,6 +97,8 @@
     MEDIA_INFO_BAD_INTERLEAVING = 800,
     // The media is not seekable (e.g live stream).
     MEDIA_INFO_NOT_SEEKABLE = 801,
+    // New media metadata is available.
+    MEDIA_INFO_METADATA_UPDATE = 802,
 };
 
 
@@ -151,7 +153,9 @@
             void            notify(int msg, int ext1, int ext2);
     static  sp<IMemory>     decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
     static  sp<IMemory>     decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
-
+            status_t        invoke(const Parcel& request, Parcel *reply);
+            status_t        setMetadataFilter(const Parcel& filter);
+            status_t        getMetadata(bool update_only, bool apply_filter, Parcel *metadata);
 private:
             void            clear_l();
             status_t        seekTo_l(int msec);
diff --git a/include/media/mediarecorder.h b/include/media/mediarecorder.h
index 9b54ca9..ad27903 100644
--- a/include/media/mediarecorder.h
+++ b/include/media/mediarecorder.h
@@ -18,7 +18,10 @@
 #ifndef ANDROID_MEDIARECORDER_H
 #define ANDROID_MEDIARECORDER_H
 
-#include <utils.h>
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 #include <media/IMediaPlayerClient.h>
 
 namespace android {
diff --git a/include/media/mediascanner.h b/include/media/mediascanner.h
index fbef1db..7749566 100644
--- a/include/media/mediascanner.h
+++ b/include/media/mediascanner.h
@@ -17,7 +17,10 @@
 #ifndef MEDIASCANNER_H
 #define MEDIASCANNER_H
 
-#include <utils.h>
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 #include <pthread.h>
 
 namespace android {
diff --git a/include/media/stagefright/AudioPlayer.h b/include/media/stagefright/AudioPlayer.h
new file mode 100644
index 0000000..0f2e528
--- /dev/null
+++ b/include/media/stagefright/AudioPlayer.h
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+
+#ifndef AUDIO_PLAYER_H_
+
+#define AUDIO_PLAYER_H_
+
+#include <media/MediaPlayerInterface.h>
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/TimeSource.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class MediaSource;
+class AudioTrack;
+
+class AudioPlayer : public TimeSource {
+public:
+    AudioPlayer(const sp<MediaPlayerBase::AudioSink> &audioSink);
+    ~AudioPlayer();
+
+    // Caller retains ownership of "source".
+    void setSource(MediaSource *source);
+
+    // Return time in us.
+    virtual int64_t getRealTimeUs();
+
+    void start();
+
+    void pause();
+    void resume();
+
+    void stop();
+
+    // Returns the timestamp of the last buffer played (in us).
+    int64_t getMediaTimeUs();
+
+    // Returns true iff a mapping is established, i.e. the AudioPlayer
+    // has played at least one frame of audio.
+    bool getMediaTimeMapping(int64_t *realtime_us, int64_t *mediatime_us);
+
+    status_t seekTo(int64_t time_us);
+
+private:
+    MediaSource *mSource;
+    AudioTrack *mAudioTrack;
+
+    MediaBuffer *mInputBuffer;
+
+    int mSampleRate;
+    int64_t mLatencyUs;
+    size_t mFrameSize;
+
+    Mutex mLock;
+    int64_t mNumFramesPlayed;
+
+    int64_t mPositionTimeMediaUs;
+    int64_t mPositionTimeRealUs;
+
+    bool mSeeking;
+    int64_t mSeekTimeUs;
+
+    bool mStarted;
+
+    sp<MediaPlayerBase::AudioSink> mAudioSink;
+
+    static void AudioCallback(int event, void *user, void *info);
+    void AudioCallback(int event, void *info);
+
+    static void AudioSinkCallback(
+            MediaPlayerBase::AudioSink *audioSink,
+            void *data, size_t size, void *me);
+
+    void fillBuffer(void *data, size_t size);
+
+    int64_t getRealTimeUsLocked() const;
+
+    AudioPlayer(const AudioPlayer &);
+    AudioPlayer &operator=(const AudioPlayer &);
+};
+
+}  // namespace android
+
+#endif  // AUDIO_PLAYER_H_
diff --git a/include/media/stagefright/AudioSource.h b/include/media/stagefright/AudioSource.h
new file mode 100644
index 0000000..e129958
--- /dev/null
+++ b/include/media/stagefright/AudioSource.h
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+
+#ifndef AUDIO_SOURCE_H_
+
+#define AUDIO_SOURCE_H_
+
+#include <media/stagefright/MediaSource.h>
+
+namespace android {
+
+class AudioRecord;
+
+class AudioSource {
+public:
+    AudioSource(int inputSource);
+    virtual ~AudioSource();
+
+    status_t initCheck() const;
+
+    virtual status_t start(MetaData *params = NULL);
+    virtual status_t stop();
+    virtual sp<MetaData> getFormat();
+
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options = NULL);
+
+private:
+    AudioRecord *mRecord;
+    status_t mInitCheck;
+
+    AudioSource(const AudioSource &);
+    AudioSource &operator=(const AudioSource &);
+};
+
+}  // namespace android
+
+#endif  // AUDIO_SOURCE_H_
diff --git a/include/media/stagefright/CachingDataSource.h b/include/media/stagefright/CachingDataSource.h
new file mode 100644
index 0000000..e275cb4
--- /dev/null
+++ b/include/media/stagefright/CachingDataSource.h
@@ -0,0 +1,60 @@
+/*
+ * 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.
+ */
+
+#ifndef CACHING_DATASOURCE_H_
+
+#define CACHING_DATASOURCE_H_
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaErrors.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class CachingDataSource : public DataSource {
+public:
+    // Assumes ownership of "source".
+    CachingDataSource(DataSource *source, size_t pageSize, int numPages);
+    virtual ~CachingDataSource();
+
+    status_t InitCheck() const;
+
+    virtual ssize_t read_at(off_t offset, void *data, size_t size);
+
+private:
+    struct Page {
+        Page *mPrev, *mNext;
+        off_t mOffset;
+        size_t mLength;
+        void *mData;
+    };
+
+    DataSource *mSource;
+    void *mData;
+    size_t mPageSize;
+    Page *mFirst, *mLast;
+
+    Page *allocate_page();
+
+    Mutex mLock;
+
+    CachingDataSource(const CachingDataSource &);
+    CachingDataSource &operator=(const CachingDataSource &);
+};
+
+}  // namespace android
+
+#endif  // CACHING_DATASOURCE_H_
diff --git a/include/media/stagefright/CameraSource.h b/include/media/stagefright/CameraSource.h
new file mode 100644
index 0000000..7042e1a
--- /dev/null
+++ b/include/media/stagefright/CameraSource.h
@@ -0,0 +1,72 @@
+/*
+ * 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.
+ */
+
+#ifndef CAMERA_SOURCE_H_
+
+#define CAMERA_SOURCE_H_
+
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaSource.h>
+#include <utils/List.h>
+#include <utils/RefBase.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class ICamera;
+class ICameraClient;
+class IMemory;
+
+class CameraSource : public MediaSource,
+                     public MediaBufferObserver {
+public:
+    static CameraSource *Create();
+
+    virtual ~CameraSource();
+
+    virtual status_t start(MetaData *params = NULL);
+    virtual status_t stop();
+
+    virtual sp<MetaData> getFormat();
+
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options = NULL);
+
+    virtual void notifyCallback(int32_t msgType, int32_t ext1, int32_t ext2);
+    virtual void dataCallback(int32_t msgType, const sp<IMemory>& data);
+
+    virtual void signalBufferReturned(MediaBuffer *buffer);
+
+private:
+    CameraSource(const sp<ICamera> &camera, const sp<ICameraClient> &client);
+
+    sp<ICamera> mCamera;
+    sp<ICameraClient> mCameraClient;
+
+    Mutex mLock;
+    Condition mFrameAvailableCondition;
+    List<sp<IMemory> > mFrames;
+
+    int mNumFrames;
+    bool mStarted;
+
+    CameraSource(const CameraSource &);
+    CameraSource &operator=(const CameraSource &);
+};
+
+}  // namespace android
+
+#endif  // CAMERA_SOURCE_H_
diff --git a/include/media/stagefright/DataSource.h b/include/media/stagefright/DataSource.h
new file mode 100644
index 0000000..31eea27
--- /dev/null
+++ b/include/media/stagefright/DataSource.h
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+#ifndef DATA_SOURCE_H_
+
+#define DATA_SOURCE_H_
+
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/List.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class String8;
+
+class DataSource {
+public:
+    DataSource() {}
+    virtual ~DataSource() {}
+
+    virtual ssize_t read_at(off_t offset, void *data, size_t size) = 0;
+
+    // May return ERROR_UNSUPPORTED.
+    virtual status_t getSize(off_t *size);
+
+    ////////////////////////////////////////////////////////////////////////////
+
+    bool sniff(String8 *mimeType, float *confidence);
+
+    typedef bool (*SnifferFunc)(
+            DataSource *source, String8 *mimeType, float *confidence);
+
+    static void RegisterSniffer(SnifferFunc func);
+    static void RegisterDefaultSniffers();
+
+private:
+    static Mutex gSnifferMutex;
+    static List<SnifferFunc> gSniffers;
+
+    DataSource(const DataSource &);
+    DataSource &operator=(const DataSource &);
+};
+
+}  // namespace android
+
+#endif  // DATA_SOURCE_H_
diff --git a/include/media/stagefright/ESDS.h b/include/media/stagefright/ESDS.h
new file mode 100644
index 0000000..01bcd18
--- /dev/null
+++ b/include/media/stagefright/ESDS.h
@@ -0,0 +1,64 @@
+/*
+ * 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.
+ */
+
+#ifndef ESDS_H_
+
+#define ESDS_H_
+
+#include <stdint.h>
+
+#include <media/stagefright/MediaErrors.h>
+
+namespace android {
+
+class ESDS {
+public:
+    ESDS(const void *data, size_t size);
+    ~ESDS();
+
+    status_t InitCheck() const;
+
+    status_t getCodecSpecificInfo(const void **data, size_t *size) const;
+
+private:
+    enum {
+        kTag_ESDescriptor            = 0x03,
+        kTag_DecoderConfigDescriptor = 0x04,
+        kTag_DecoderSpecificInfo     = 0x05
+    };
+
+    uint8_t *mData;
+    size_t mSize;
+
+    status_t mInitCheck;
+
+    size_t mDecoderSpecificOffset;
+    size_t mDecoderSpecificLength;
+
+    status_t skipDescriptorHeader(
+            size_t offset, size_t size,
+            uint8_t *tag, size_t *data_offset, size_t *data_size) const;
+
+    status_t parse();
+    status_t parseESDescriptor(size_t offset, size_t size);
+    status_t parseDecoderConfigDescriptor(size_t offset, size_t size);
+
+    ESDS(const ESDS &);
+    ESDS &operator=(const ESDS &);
+};
+
+}  // namespace android
+#endif  // ESDS_H_
diff --git a/include/media/stagefright/FileSource.h b/include/media/stagefright/FileSource.h
new file mode 100644
index 0000000..ccbe0ef
--- /dev/null
+++ b/include/media/stagefright/FileSource.h
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+#ifndef FILE_SOURCE_H_
+
+#define FILE_SOURCE_H_
+
+#include <stdio.h>
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaErrors.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class FileSource : public DataSource {
+public:
+    FileSource(const char *filename);
+    virtual ~FileSource();
+
+    status_t InitCheck() const;
+
+    virtual ssize_t read_at(off_t offset, void *data, size_t size);
+
+private:
+    FILE *mFile;
+    Mutex mLock;
+
+    FileSource(const FileSource &);
+    FileSource &operator=(const FileSource &);
+};
+
+}  // namespace android
+
+#endif  // FILE_SOURCE_H_
+
diff --git a/include/media/stagefright/HTTPDataSource.h b/include/media/stagefright/HTTPDataSource.h
new file mode 100644
index 0000000..0587c7c
--- /dev/null
+++ b/include/media/stagefright/HTTPDataSource.h
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+
+#ifndef HTTP_DATASOURCE_H_
+
+#define HTTP_DATASOURCE_H_
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/HTTPStream.h>
+
+namespace android {
+
+class HTTPDataSource : public DataSource {
+public:
+    HTTPDataSource(const char *host, int port, const char *path);
+    HTTPDataSource(const char *uri);
+
+    virtual ~HTTPDataSource();
+
+    // XXXandih
+    status_t InitCheck() const { return OK; }
+
+    virtual ssize_t read_at(off_t offset, void *data, size_t size);
+
+private:
+    enum {
+        kBufferSize = 64 * 1024
+    };
+
+    HTTPStream mHttp;
+    char *mHost;
+    int mPort;
+    char *mPath;
+
+    void *mBuffer;
+    size_t mBufferLength;
+    off_t mBufferOffset;
+
+    HTTPDataSource(const HTTPDataSource &);
+    HTTPDataSource &operator=(const HTTPDataSource &);
+};
+
+}  // namespace android
+
+#endif  // HTTP_DATASOURCE_H_
+
diff --git a/include/media/stagefright/HTTPStream.h b/include/media/stagefright/HTTPStream.h
new file mode 100644
index 0000000..3d0d67a
--- /dev/null
+++ b/include/media/stagefright/HTTPStream.h
@@ -0,0 +1,74 @@
+/*
+ * 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.
+ */
+
+#ifndef HTTP_STREAM_H_
+
+#define HTTP_STREAM_H_
+
+#include <sys/types.h>
+
+#include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/string.h>
+#include <utils/KeyedVector.h>
+
+namespace android {
+
+class HTTPStream {
+public:
+    HTTPStream();
+    ~HTTPStream();
+
+    status_t connect(const char *server, int port = 80);
+    status_t disconnect();
+
+    status_t send(const char *data, size_t size);
+
+    // Assumes data is a '\0' terminated string.
+    status_t send(const char *data);
+
+    // Receive up to "size" bytes of data.
+    ssize_t receive(void *data, size_t size);
+
+    status_t receive_header(int *http_status);
+
+    // The header key used to retrieve the status line.
+    static const char *kStatusKey;
+
+    bool find_header_value(
+            const string &key, string *value) const;
+
+private:
+    enum State {
+        READY,
+        CONNECTED
+    };
+
+    State mState;
+    int mSocket;
+
+    KeyedVector<string, string> mHeaders;
+
+    // Receive a line of data terminated by CRLF, line will be '\0' terminated
+    // _excluding_ the termianting CRLF.
+    status_t receive_line(char *line, size_t size);
+
+    HTTPStream(const HTTPStream &);
+    HTTPStream &operator=(const HTTPStream &);
+};
+
+}  // namespace android
+
+#endif  // HTTP_STREAM_H_
diff --git a/include/media/stagefright/MP3Extractor.h b/include/media/stagefright/MP3Extractor.h
new file mode 100644
index 0000000..09cfb70
--- /dev/null
+++ b/include/media/stagefright/MP3Extractor.h
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+
+#ifndef MP3_EXTRACTOR_H_
+
+#define MP3_EXTRACTOR_H_
+
+#include <media/stagefright/MediaExtractor.h>
+
+namespace android {
+
+class DataSource;
+class String8;
+
+class MP3Extractor : public MediaExtractor {
+public:
+    // Extractor assumes ownership of "source".
+    MP3Extractor(DataSource *source);
+
+    ~MP3Extractor();
+
+    status_t countTracks(int *num_tracks);
+    status_t getTrack(int index, MediaSource **source);
+    sp<MetaData> getTrackMetaData(int index);
+
+private:
+    DataSource *mDataSource;
+    off_t mFirstFramePos;
+    sp<MetaData> mMeta;
+    uint32_t mFixedHeader;
+
+    MP3Extractor(const MP3Extractor &);
+    MP3Extractor &operator=(const MP3Extractor &);
+};
+
+bool SniffMP3(DataSource *source, String8 *mimeType, float *confidence);
+
+}  // namespace android
+
+#endif  // MP3_EXTRACTOR_H_
diff --git a/include/media/stagefright/MPEG4Extractor.h b/include/media/stagefright/MPEG4Extractor.h
new file mode 100644
index 0000000..51a7e82
--- /dev/null
+++ b/include/media/stagefright/MPEG4Extractor.h
@@ -0,0 +1,65 @@
+/*
+ * 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.
+ */
+
+#ifndef MPEG4_EXTRACTOR_H_
+
+#define MPEG4_EXTRACTOR_H_
+
+#include <media/stagefright/MediaExtractor.h>
+
+namespace android {
+
+class DataSource;
+class SampleTable;
+class String8;
+
+class MPEG4Extractor : public MediaExtractor {
+public:
+    // Extractor assumes ownership of "source".
+    MPEG4Extractor(DataSource *source);
+    ~MPEG4Extractor();
+
+    status_t countTracks(int *num_tracks);
+    status_t getTrack(int index, MediaSource **source);
+    sp<MetaData> getTrackMetaData(int index);
+
+private:
+    struct Track {
+        Track *next;
+        sp<MetaData> meta;
+        uint32_t timescale;
+        SampleTable *sampleTable;
+    };
+
+    DataSource *mDataSource;
+    bool mHaveMetadata;
+
+    Track *mFirstTrack, *mLastTrack;
+
+    uint32_t mHandlerType;
+
+    status_t readMetaData();
+    status_t parseChunk(off_t *offset, int depth);
+
+    MPEG4Extractor(const MPEG4Extractor &);
+    MPEG4Extractor &operator=(const MPEG4Extractor &);
+};
+
+bool SniffMPEG4(DataSource *source, String8 *mimeType, float *confidence);
+
+}  // namespace android
+
+#endif  // MPEG4_EXTRACTOR_H_
diff --git a/include/media/stagefright/MPEG4Writer.h b/include/media/stagefright/MPEG4Writer.h
new file mode 100644
index 0000000..40d6127
--- /dev/null
+++ b/include/media/stagefright/MPEG4Writer.h
@@ -0,0 +1,73 @@
+/*
+ * 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.
+ */
+
+#ifndef MPEG4_WRITER_H_
+
+#define MPEG4_WRITER_H_
+
+#include <stdio.h>
+
+#include <utils/List.h>
+#include <utils/RefBase.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class MediaBuffer;
+class MediaSource;
+class MetaData;
+
+class MPEG4Writer {
+public:
+    MPEG4Writer(const char *filename);
+    ~MPEG4Writer();
+
+    // Caller retains ownership of both meta and source.
+    void addSource(const sp<MetaData> &meta, MediaSource *source);
+    void start();
+    void stop();
+
+    void beginBox(const char *fourcc);
+    void writeInt8(int8_t x);
+    void writeInt16(int16_t x);
+    void writeInt32(int32_t x);
+    void writeInt64(int64_t x);
+    void writeCString(const char *s);
+    void writeFourcc(const char *fourcc);
+    void write(const void *data, size_t size);
+    void endBox();
+
+private:
+    class Track;
+
+    FILE *mFile;
+    off_t mOffset;
+    off_t mMdatOffset;
+    Mutex mLock;
+
+    List<Track *> mTracks;
+
+    List<off_t> mBoxes;
+
+    off_t addSample(MediaBuffer *buffer);
+
+    MPEG4Writer(const MPEG4Writer &);
+    MPEG4Writer &operator=(const MPEG4Writer &);
+};
+
+}  // namespace android
+
+#endif  // MPEG4_WRITER_H_
diff --git a/include/media/stagefright/MediaBuffer.h b/include/media/stagefright/MediaBuffer.h
new file mode 100644
index 0000000..c72ed66
--- /dev/null
+++ b/include/media/stagefright/MediaBuffer.h
@@ -0,0 +1,113 @@
+/*
+ * 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.
+ */
+
+#ifndef MEDIA_BUFFER_H_
+
+#define MEDIA_BUFFER_H_
+
+#include <pthread.h>
+
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+
+namespace android {
+
+class MediaBuffer;
+class MediaBufferObserver;
+class MetaData;
+
+class MediaBufferObserver {
+public:
+    MediaBufferObserver() {}
+    virtual ~MediaBufferObserver() {}
+
+    virtual void signalBufferReturned(MediaBuffer *buffer) = 0;
+
+private:
+    MediaBufferObserver(const MediaBufferObserver &);
+    MediaBufferObserver &operator=(const MediaBufferObserver &);
+};
+
+class MediaBuffer {
+public:
+    // The underlying data remains the responsibility of the caller!
+    MediaBuffer(void *data, size_t size);
+
+    MediaBuffer(size_t size);
+
+    // Decrements the reference count and returns the buffer to its
+    // associated MediaBufferGroup if the reference count drops to 0.
+    void release();
+
+    // Increments the reference count.
+    void add_ref();
+
+    void *data() const;
+    size_t size() const;
+
+    size_t range_offset() const;
+    size_t range_length() const;
+
+    void set_range(size_t offset, size_t length);
+
+    sp<MetaData> meta_data();
+
+    // Clears meta data and resets the range to the full extent.
+    void reset();
+
+    void setObserver(MediaBufferObserver *group);
+
+    // Returns a clone of this MediaBuffer increasing its reference count.
+    // The clone references the same data but has its own range and
+    // MetaData.
+    MediaBuffer *clone();
+
+protected:
+    virtual ~MediaBuffer();
+
+private:
+    friend class MediaBufferGroup;
+    friend class OMXDecoder;
+
+    // For use by OMXDecoder, reference count must be 1, drop reference
+    // count to 0 without signalling the observer.
+    void claim();
+
+    MediaBufferObserver *mObserver;
+    MediaBuffer *mNextBuffer;
+    int mRefCount;
+
+    void *mData;
+    size_t mSize, mRangeOffset, mRangeLength;
+
+    bool mOwnsData;
+
+    sp<MetaData> mMetaData;
+
+    MediaBuffer *mOriginal;
+
+    void setNextBuffer(MediaBuffer *buffer);
+    MediaBuffer *nextBuffer();
+
+    int refcount() const;
+
+    MediaBuffer(const MediaBuffer &);
+    MediaBuffer &operator=(const MediaBuffer &);
+};
+
+}  // namespace android
+
+#endif  // MEDIA_BUFFER_H_
diff --git a/include/media/stagefright/MediaBufferGroup.h b/include/media/stagefright/MediaBufferGroup.h
new file mode 100644
index 0000000..e95a9c2
--- /dev/null
+++ b/include/media/stagefright/MediaBufferGroup.h
@@ -0,0 +1,57 @@
+/*
+ * 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.
+ */
+
+#ifndef MEDIA_BUFFER_GROUP_H_
+
+#define MEDIA_BUFFER_GROUP_H_
+
+#include <utils/Errors.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class MediaBuffer;
+class MetaData;
+
+class MediaBufferGroup : public MediaBufferObserver {
+public:
+    MediaBufferGroup();
+    ~MediaBufferGroup();
+
+    void add_buffer(MediaBuffer *buffer);
+
+    // Blocks until a buffer is available and returns it to the caller,
+    // the returned buffer will have a reference count of 1.
+    status_t acquire_buffer(MediaBuffer **buffer);
+
+protected:
+    virtual void signalBufferReturned(MediaBuffer *buffer);
+
+private:
+    friend class MediaBuffer;
+
+    Mutex mLock;
+    Condition mCondition;
+
+    MediaBuffer *mFirstBuffer, *mLastBuffer;
+
+    MediaBufferGroup(const MediaBufferGroup &);
+    MediaBufferGroup &operator=(const MediaBufferGroup &);
+};
+
+}  // namespace android
+
+#endif  // MEDIA_BUFFER_GROUP_H_
diff --git a/include/media/stagefright/MediaErrors.h b/include/media/stagefright/MediaErrors.h
new file mode 100644
index 0000000..2bb0ed6
--- /dev/null
+++ b/include/media/stagefright/MediaErrors.h
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+#ifndef MEDIA_ERRORS_H_
+
+#define MEDIA_ERRORS_H_
+
+#include <utils/Errors.h>
+
+namespace android {
+
+enum {
+    MEDIA_ERROR_BASE        = -1000,
+
+    ERROR_ALREADY_CONNECTED = MEDIA_ERROR_BASE,
+    ERROR_NOT_CONNECTED     = MEDIA_ERROR_BASE - 1,
+    ERROR_UNKNOWN_HOST      = MEDIA_ERROR_BASE - 2,
+    ERROR_CANNOT_CONNECT    = MEDIA_ERROR_BASE - 3,
+    ERROR_IO                = MEDIA_ERROR_BASE - 4,
+    ERROR_CONNECTION_LOST   = MEDIA_ERROR_BASE - 5,
+    ERROR_MALFORMED         = MEDIA_ERROR_BASE - 7,
+    ERROR_OUT_OF_RANGE      = MEDIA_ERROR_BASE - 8,
+    ERROR_BUFFER_TOO_SMALL  = MEDIA_ERROR_BASE - 9,
+    ERROR_UNSUPPORTED       = MEDIA_ERROR_BASE - 10,
+    ERROR_END_OF_STREAM     = MEDIA_ERROR_BASE - 11,
+};
+
+}  // namespace android
+
+#endif  // MEDIA_ERRORS_H_
diff --git a/include/media/stagefright/MediaExtractor.h b/include/media/stagefright/MediaExtractor.h
new file mode 100644
index 0000000..38f8e5b
--- /dev/null
+++ b/include/media/stagefright/MediaExtractor.h
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+#ifndef MEDIA_EXTRACTOR_H_
+
+#define MEDIA_EXTRACTOR_H_
+
+#include <utils/RefBase.h>
+
+namespace android {
+
+class DataSource;
+class MediaSource;
+class MetaData;
+
+class MediaExtractor {
+public:
+    static MediaExtractor *Create(DataSource *source, const char *mime = NULL);
+
+    virtual ~MediaExtractor() {}
+
+    virtual status_t countTracks(int *num_tracks) = 0;
+    virtual status_t getTrack(int index, MediaSource **source) = 0;
+    virtual sp<MetaData> getTrackMetaData(int index) = 0;
+
+protected:
+    MediaExtractor() {}
+
+private:
+    MediaExtractor(const MediaExtractor &);
+    MediaExtractor &operator=(const MediaExtractor &);
+};
+
+}  // namespace android
+
+#endif  // MEDIA_EXTRACTOR_H_
diff --git a/include/media/stagefright/MediaPlayerImpl.h b/include/media/stagefright/MediaPlayerImpl.h
new file mode 100644
index 0000000..c48400c
--- /dev/null
+++ b/include/media/stagefright/MediaPlayerImpl.h
@@ -0,0 +1,132 @@
+/*
+ * 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.
+ */
+
+#ifndef MEDIA_PLAYER_IMPL_H_
+
+#define MEDIA_PLAYER_IMPL_H_
+
+#include <pthread.h>
+
+#include <media/MediaPlayerInterface.h>
+#include <media/stagefright/OMXClient.h>
+#include <utils/RefBase.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class AudioPlayer;
+class ISurface;
+class MediaExtractor;
+class MediaBuffer;
+class MediaSource;
+class MemoryHeapPmem;
+class MetaData;
+class OMXDecoder;
+class Surface;
+class TimeSource;
+class VideoRenderer;
+
+class MediaPlayerImpl {
+public:
+    MediaPlayerImpl(const char *uri);
+
+    status_t initCheck() const;
+
+    // Assumes ownership of "fd".
+    MediaPlayerImpl(int fd, int64_t offset, int64_t length);
+
+    ~MediaPlayerImpl();
+
+    void play();
+    void pause();
+    bool isPlaying() const;
+
+    void setSurface(const sp<Surface> &surface);
+    void setISurface(const sp<ISurface> &isurface);
+
+    void setAudioSink(const sp<MediaPlayerBase::AudioSink> &audioSink);
+
+    int32_t getWidth() const { return mVideoWidth; }
+    int32_t getHeight() const { return mVideoHeight; }
+
+    int64_t getDuration();
+    int64_t getPosition();
+    status_t seekTo(int64_t time);
+
+private:
+    status_t mInitCheck;
+
+    OMXClient mClient;
+
+    MediaExtractor *mExtractor;
+
+    TimeSource *mTimeSource;
+
+    MediaSource *mAudioSource;
+    OMXDecoder *mAudioDecoder;
+    AudioPlayer *mAudioPlayer;
+
+    MediaSource *mVideoSource;
+    MediaSource *mVideoDecoder;
+    int32_t mVideoWidth, mVideoHeight;
+    int64_t mVideoPosition;
+
+    int64_t mDuration;
+
+    bool mPlaying;
+    bool mPaused;
+
+    int64_t mTimeSourceDeltaUs;
+
+    sp<Surface> mSurface;
+    sp<ISurface> mISurface;
+    VideoRenderer *mRenderer;
+
+    sp<MediaPlayerBase::AudioSink> mAudioSink;
+
+    Mutex mLock;
+    pthread_t mVideoThread;
+
+    bool mSeeking;
+    int64_t mSeekTimeUs;
+
+    size_t mFrameSize;
+    bool mUseSoftwareColorConversion;
+
+    void init();
+
+    static void *VideoWrapper(void *me);
+    void videoEntry();
+
+    void setAudioSource(MediaSource *source);
+    void setVideoSource(MediaSource *source);
+
+    MediaSource *makeShoutcastSource(const char *path);
+
+    void displayOrDiscardFrame(MediaBuffer *buffer, int64_t pts_us);
+    void populateISurface();
+    void depopulateISurface();
+    void sendFrameToISurface(MediaBuffer *buffer);
+
+    void stop();
+
+    MediaPlayerImpl(const MediaPlayerImpl &);
+    MediaPlayerImpl &operator=(const MediaPlayerImpl &);
+};
+
+}  // namespace android
+
+#endif  // MEDIA_PLAYER_IMPL_H_
diff --git a/include/media/stagefright/MediaSource.h b/include/media/stagefright/MediaSource.h
new file mode 100644
index 0000000..eb07f68
--- /dev/null
+++ b/include/media/stagefright/MediaSource.h
@@ -0,0 +1,91 @@
+/*
+ * 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.
+ */
+
+#ifndef MEDIA_SOURCE_H_
+
+#define MEDIA_SOURCE_H_
+
+#include <sys/types.h>
+
+#include <utils/RefBase.h>
+
+namespace android {
+
+class MediaBuffer;
+class MetaData;
+
+struct MediaSource {
+    MediaSource();
+    virtual ~MediaSource();
+
+    // To be called before any other methods on this object, except
+    // getFormat().
+    virtual status_t start(MetaData *params = NULL) = 0;
+
+    // Any blocking read call returns immediately with a result of NO_INIT.
+    // It is an error to call any methods other than start after this call
+    // returns. Any buffers the object may be holding onto at the time of
+    // the stop() call are released.
+    // Also, it is imperative that any buffers output by this object and
+    // held onto by callers be released before a call to stop() !!!
+    virtual status_t stop() = 0;
+
+    // Returns the format of the data output by this media source.
+    virtual sp<MetaData> getFormat() = 0;
+
+    struct ReadOptions;
+
+    // Returns a new buffer of data. Call blocks until a
+    // buffer is available, an error is encountered of the end of the stream
+    // is reached.
+    // End of stream is signalled by a result of ERROR_END_OF_STREAM.
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options = NULL) = 0;
+
+    // Options that modify read() behaviour. The default is to
+    // a) not request a seek
+    // b) not be late, i.e. lateness_us = 0
+    struct ReadOptions {
+        ReadOptions();
+
+        // Reset everything back to defaults.
+        void reset();
+
+        void setSeekTo(int64_t time_us);
+        void clearSeekTo();
+        bool getSeekTo(int64_t *time_us) const;
+
+        void setLateBy(int64_t lateness_us);
+        int64_t getLateBy() const;
+
+    private:
+        enum Options {
+            kSeekTo_Option      = 1,
+        };
+
+        uint32_t mOptions;
+        int64_t mSeekTimeUs;
+        int64_t mLatenessUs;
+    };
+
+private:
+    MediaSource(const MediaSource &);
+    MediaSource &operator=(const MediaSource &);
+};
+
+}  // namespace android
+
+#endif  // MEDIA_SOURCE_H_
diff --git a/include/media/stagefright/MetaData.h b/include/media/stagefright/MetaData.h
new file mode 100644
index 0000000..04805dab
--- /dev/null
+++ b/include/media/stagefright/MetaData.h
@@ -0,0 +1,132 @@
+/*
+ * 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.
+ */
+
+#ifndef META_DATA_H_
+
+#define META_DATA_H_
+
+#include <sys/types.h>
+
+#include <stdint.h>
+
+#include <utils/RefBase.h>
+#include <utils/KeyedVector.h>
+
+namespace android {
+
+enum {
+    kKeyMIMEType         = 'mime',
+    kKeyWidth            = 'widt',
+    kKeyHeight           = 'heig',
+    kKeyChannelCount     = '#chn',
+    kKeySampleRate       = 'srte',
+    kKeyBitRate          = 'brte',
+    kKeyESDS             = 'esds',
+    kKeyAVCC             = 'avcc',
+    kKeyTimeUnits        = '#tim',
+    kKeyTimeScale        = 'scal',
+    kKeyNeedsNALFraming  = 'NALf',
+    kKeyIsSyncFrame      = 'sync',
+    kKeyDuration         = 'dura',
+    kKeyColorFormat      = 'colf',
+    kKeyPlatformPrivate  = 'priv',
+    kKeyDecoderComponent = 'decC',
+};
+
+enum {
+    kTypeESDS        = 'esds',
+    kTypeAVCC        = 'avcc',
+};
+
+class MetaData : public RefBase {
+public:
+    MetaData();
+    MetaData(const MetaData &from);
+
+    enum Type {
+        TYPE_NONE     = 'none',
+        TYPE_C_STRING = 'cstr',
+        TYPE_INT32    = 'in32',
+        TYPE_FLOAT    = 'floa',
+        TYPE_POINTER  = 'ptr ',
+    };
+
+    void clear();
+    bool remove(uint32_t key);
+
+    bool setCString(uint32_t key, const char *value);
+    bool setInt32(uint32_t key, int32_t value);
+    bool setFloat(uint32_t key, float value);
+    bool setPointer(uint32_t key, void *value);
+
+    bool findCString(uint32_t key, const char **value);
+    bool findInt32(uint32_t key, int32_t *value);
+    bool findFloat(uint32_t key, float *value);
+    bool findPointer(uint32_t key, void **value);
+
+    bool setData(uint32_t key, uint32_t type, const void *data, size_t size);
+
+    bool findData(uint32_t key, uint32_t *type,
+                  const void **data, size_t *size) const;
+
+protected:
+    virtual ~MetaData();
+
+private:
+    struct typed_data {
+        typed_data();
+        ~typed_data();
+
+        typed_data(const MetaData::typed_data &);
+        typed_data &operator=(const MetaData::typed_data &);
+
+        void clear();
+        void setData(uint32_t type, const void *data, size_t size);
+        void getData(uint32_t *type, const void **data, size_t *size) const;
+
+    private:
+        uint32_t mType;
+        size_t mSize;
+
+        union {
+            void *ext_data;
+            float reservoir;
+        } u;
+
+        bool usesReservoir() const {
+            return mSize <= sizeof(u.reservoir);
+        }
+
+        void allocateStorage(size_t size);
+        void freeStorage();
+
+        void *storage() {
+            return usesReservoir() ? &u.reservoir : u.ext_data;
+        }
+
+        const void *storage() const {
+            return usesReservoir() ? &u.reservoir : u.ext_data;
+        }
+    };
+
+    KeyedVector<uint32_t, typed_data> mItems;
+
+    // MetaData &operator=(const MetaData &);
+};
+
+}  // namespace android
+
+#endif  // META_DATA_H_
diff --git a/include/media/stagefright/MmapSource.h b/include/media/stagefright/MmapSource.h
new file mode 100644
index 0000000..a8bd57f
--- /dev/null
+++ b/include/media/stagefright/MmapSource.h
@@ -0,0 +1,52 @@
+/*
+ * 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.
+ */
+
+#ifndef MMAP_SOURCE_H_
+
+#define MMAP_SOURCE_H_
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaErrors.h>
+
+namespace android {
+
+class MmapSource : public DataSource {
+public:
+    MmapSource(const char *filename);
+
+    // Assumes ownership of "fd".
+    MmapSource(int fd, int64_t offset, int64_t length);
+
+    virtual ~MmapSource();
+
+    status_t InitCheck() const;
+
+    virtual ssize_t read_at(off_t offset, void *data, size_t size);
+    virtual status_t getSize(off_t *size);
+
+private:
+    int mFd;
+    void *mBase;
+    size_t mSize;
+
+    MmapSource(const MmapSource &);
+    MmapSource &operator=(const MmapSource &);
+};
+
+}  // namespace android
+
+#endif  // MMAP_SOURCE_H_
+
diff --git a/include/media/stagefright/OMXClient.h b/include/media/stagefright/OMXClient.h
new file mode 100644
index 0000000..454c38b
--- /dev/null
+++ b/include/media/stagefright/OMXClient.h
@@ -0,0 +1,124 @@
+/*
+ * 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.
+ */
+
+#ifndef OMX_CLIENT_H_
+
+#define OMX_CLIENT_H_
+
+#include <media/IOMX.h>
+
+#include <utils/KeyedVector.h>
+#include <utils/List.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class OMXObserver {
+public:
+    OMXObserver();
+    virtual ~OMXObserver();
+
+    void postMessage(const omx_message &msg);
+
+protected:
+    virtual void onOMXMessage(const omx_message &msg) = 0;
+
+private:
+    friend class OMXClient;
+
+    pthread_t mThread;
+    Mutex mLock;
+    Condition mQueueNotEmpty;
+    List<omx_message> mQueue;
+
+    void start();
+    void stop();
+
+    static void *ThreadWrapper(void *me);
+    void threadEntry();
+
+    OMXObserver(const OMXObserver &);
+    OMXObserver &operator=(const OMXObserver &);
+};
+
+class OMXClient;
+
+class OMXClientReflector : public BnOMXObserver {
+public:
+    OMXClientReflector(OMXClient *client);
+
+    virtual void on_message(const omx_message &msg);
+    void reset();
+
+private:
+    OMXClient *mClient;
+
+    OMXClientReflector(const OMXClientReflector &);
+    OMXClientReflector &operator=(const OMXClientReflector &);
+};
+
+class OMXClient {
+public:
+    friend class OMXClientReflector;
+
+    OMXClient();
+    ~OMXClient();
+
+    status_t connect();
+    void disconnect();
+
+    sp<IOMX> interface() {
+        return mOMX;
+    }
+
+    status_t registerObserver(IOMX::node_id node, OMXObserver *observer);
+    void unregisterObserver(IOMX::node_id node);
+
+    status_t fillBuffer(IOMX::node_id node, IOMX::buffer_id buffer);
+
+    status_t emptyBuffer(
+            IOMX::node_id node, IOMX::buffer_id buffer,
+            OMX_U32 range_offset, OMX_U32 range_length,
+            OMX_U32 flags, OMX_TICKS timestamp);
+
+    status_t send_command(
+            IOMX::node_id node, OMX_COMMANDTYPE cmd, OMX_S32 param);
+
+private:
+    sp<IOMX> mOMX;
+
+    int mSock;
+    Mutex mLock;
+    pthread_t mThread;
+
+    KeyedVector<IOMX::node_id, OMXObserver *> mObservers;
+
+    sp<OMXClientReflector> mReflector;
+
+#if IOMX_USES_SOCKETS
+    static void *ThreadWrapper(void *me);
+    void threadEntry();
+#endif
+
+    bool onOMXMessage(const omx_message &msg);
+
+    OMXClient(const OMXClient &);
+    OMXClient &operator=(const OMXClient &);
+};
+
+}  // namespace android
+
+#endif  // OMX_CLIENT_H_
diff --git a/include/media/stagefright/OMXDecoder.h b/include/media/stagefright/OMXDecoder.h
new file mode 100644
index 0000000..0859457
--- /dev/null
+++ b/include/media/stagefright/OMXDecoder.h
@@ -0,0 +1,158 @@
+/*
+ * 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.
+ */
+
+#ifndef OMX_DECODER_H_
+
+#define OMX_DECODER_H_
+
+#include <binder/MemoryDealer.h>
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/OMXClient.h>
+#include <utils/KeyedVector.h>
+#include <utils/List.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class OMXMediaBuffer;
+
+class OMXDecoder : public MediaSource,
+                   public OMXObserver,
+                   public MediaBufferObserver {
+public:
+    static OMXDecoder *Create(
+            OMXClient *client, const sp<MetaData> &data);
+
+    static OMXDecoder *CreateEncoder(
+            OMXClient *client, const sp<MetaData> &data);
+
+    virtual ~OMXDecoder();
+
+    // Caller retains ownership of "source".
+    void setSource(MediaSource *source);
+
+    virtual status_t start(MetaData *params = NULL);
+    virtual status_t stop();
+
+    virtual sp<MetaData> getFormat();
+
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options = NULL);
+
+    void addCodecSpecificData(const void *data, size_t size);
+
+    // from OMXObserver
+    virtual void onOMXMessage(const omx_message &msg);
+
+    // from MediaBufferObserver
+    virtual void signalBufferReturned(MediaBuffer *buffer);
+
+private:
+    enum {
+        kPortIndexInput  = 0,
+        kPortIndexOutput = 1
+    };
+
+    enum PortStatus {
+        kPortStatusActive   = 0,
+        kPortStatusDisabled = 1,
+        kPortStatusShutdown = 2,
+        kPortStatusFlushing = 3
+    };
+
+    OMXClient *mClient;
+    sp<IOMX> mOMX;
+    IOMX::node_id mNode;
+    char *mComponentName;
+    bool mIsMP3;
+
+    MediaSource *mSource;
+    sp<MetaData> mOutputFormat;
+
+    Mutex mLock;
+    Condition mOutputBufferAvailable;
+
+    List<MediaBuffer *> mOutputBuffers;
+
+    struct CodecSpecificData {
+        void *data;
+        size_t size;
+    };
+
+    List<CodecSpecificData> mCodecSpecificData;
+    List<CodecSpecificData>::iterator mCodecSpecificDataIterator;
+
+    volatile OMX_STATETYPE mState;
+    OMX_U32 mPortStatusMask;
+    bool mShutdownInitiated;
+
+    typedef List<IOMX::buffer_id> BufferList;
+    Vector<BufferList> mBuffers;
+
+    KeyedVector<IOMX::buffer_id, sp<IMemory> > mBufferMap;
+    KeyedVector<IOMX::buffer_id, OMXMediaBuffer *> mMediaBufferMap;
+
+    sp<MemoryDealer> mDealer;
+
+    bool mSeeking;
+    int64_t mSeekTimeUs;
+
+    bool mStarted;
+    status_t mErrorCondition;
+    bool mReachedEndOfInput;
+
+    OMXDecoder(OMXClient *client, IOMX::node_id node,
+               const char *mime, const char *codec);
+
+    void setPortStatus(OMX_U32 port_index, PortStatus status);
+    PortStatus getPortStatus(OMX_U32 port_index) const;
+
+    void allocateBuffers(OMX_U32 port_index);
+
+    void setAMRFormat();
+    void setAACFormat();
+    void setVideoOutputFormat(OMX_U32 width, OMX_U32 height);
+    void setup();
+    void dumpPortDefinition(OMX_U32 port_index);
+
+    void onStart();
+    void onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2);
+    void onEventCmdComplete(OMX_COMMANDTYPE type, OMX_U32 data);
+    void onEventPortSettingsChanged(OMX_U32 port_index);
+    void onStateChanged(OMX_STATETYPE to);
+    void onEmptyBufferDone(IOMX::buffer_id buffer);
+    void onFillBufferDone(const omx_message &msg);
+
+    void onRealEmptyBufferDone(IOMX::buffer_id buffer);
+    void onRealFillBufferDone(const omx_message &msg);
+
+    void initiateShutdown();
+
+    void freeInputBuffer(IOMX::buffer_id buffer);
+    void freeOutputBuffer(IOMX::buffer_id buffer);
+
+    void postStart();
+    void postEmptyBufferDone(IOMX::buffer_id buffer);
+    void postInitialFillBuffer(IOMX::buffer_id buffer);
+
+    OMXDecoder(const OMXDecoder &);
+    OMXDecoder &operator=(const OMXDecoder &);
+};
+
+}  // namespace android
+
+#endif  // OMX_DECODER_H_
diff --git a/include/media/stagefright/QComHardwareRenderer.h b/include/media/stagefright/QComHardwareRenderer.h
new file mode 100644
index 0000000..8292dd5
--- /dev/null
+++ b/include/media/stagefright/QComHardwareRenderer.h
@@ -0,0 +1,57 @@
+/*
+ * 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.
+ */
+
+#ifndef QCOM_HARDWARE_RENDERER_H_
+
+#define QCOM_HARDWARE_RENDERER_H_
+
+#include <media/stagefright/VideoRenderer.h>
+#include <utils/RefBase.h>
+
+namespace android {
+
+class ISurface;
+class MemoryHeapPmem;
+
+class QComHardwareRenderer : public VideoRenderer {
+public:
+    QComHardwareRenderer(
+            const sp<ISurface> &surface,
+            size_t displayWidth, size_t displayHeight,
+            size_t decodedWidth, size_t decodedHeight);
+
+    virtual ~QComHardwareRenderer();
+
+    virtual void render(
+            const void *data, size_t size, void *platformPrivate);
+
+private:
+    sp<ISurface> mISurface;
+    size_t mDisplayWidth, mDisplayHeight;
+    size_t mDecodedWidth, mDecodedHeight;
+    size_t mFrameSize;
+    sp<MemoryHeapPmem> mMemoryHeap;
+
+    bool getOffset(void *platformPrivate, size_t *offset);
+    void publishBuffers(uint32_t pmem_fd);
+
+    QComHardwareRenderer(const QComHardwareRenderer &);
+    QComHardwareRenderer &operator=(const QComHardwareRenderer &);
+};
+
+}  // namespace android
+
+#endif  // QCOM_HARDWARE_RENDERER_H_
diff --git a/include/media/stagefright/SampleTable.h b/include/media/stagefright/SampleTable.h
new file mode 100644
index 0000000..712da10
--- /dev/null
+++ b/include/media/stagefright/SampleTable.h
@@ -0,0 +1,107 @@
+/*
+ * 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.
+ */
+
+#ifndef SAMPLE_TABLE_H_
+
+#define SAMPLE_TABLE_H_
+
+#include <sys/types.h>
+#include <stdint.h>
+
+#include <media/stagefright/MediaErrors.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class DataSource;
+
+class SampleTable {
+public:
+    // Caller retains ownership of "source".
+    SampleTable(DataSource *source);
+    ~SampleTable();
+
+    // type can be 'stco' or 'co64'.
+    status_t setChunkOffsetParams(
+            uint32_t type, off_t data_offset, off_t data_size);
+
+    status_t setSampleToChunkParams(off_t data_offset, off_t data_size);
+
+    // type can be 'stsz' or 'stz2'.
+    status_t setSampleSizeParams(
+            uint32_t type, off_t data_offset, off_t data_size);
+
+    status_t setTimeToSampleParams(off_t data_offset, off_t data_size);
+
+    status_t setSyncSampleParams(off_t data_offset, off_t data_size);
+
+    ////////////////////////////////////////////////////////////////////////////
+
+    uint32_t countChunkOffsets() const;
+    status_t getChunkOffset(uint32_t chunk_index, off_t *offset);
+
+    status_t getChunkForSample(
+            uint32_t sample_index, uint32_t *chunk_index,
+            uint32_t *chunk_relative_sample_index, uint32_t *desc_index);
+
+    uint32_t countSamples() const;
+    status_t getSampleSize(uint32_t sample_index, size_t *sample_size);
+
+    status_t getSampleOffsetAndSize(
+            uint32_t sample_index, off_t *offset, size_t *size);
+
+    status_t getMaxSampleSize(size_t *size);
+
+    status_t getDecodingTime(uint32_t sample_index, uint32_t *time);
+
+    enum {
+        kSyncSample_Flag = 1
+    };
+    status_t findClosestSample(
+            uint32_t req_time, uint32_t *sample_index, uint32_t flags);
+
+    status_t findClosestSyncSample(
+            uint32_t start_sample_index, uint32_t *sample_index);
+
+private:
+    DataSource *mDataSource;
+    Mutex mLock;
+
+    off_t mChunkOffsetOffset;
+    uint32_t mChunkOffsetType;
+    uint32_t mNumChunkOffsets;
+
+    off_t mSampleToChunkOffset;
+    uint32_t mNumSampleToChunkOffsets;
+
+    off_t mSampleSizeOffset;
+    uint32_t mSampleSizeFieldSize;
+    uint32_t mDefaultSampleSize;
+    uint32_t mNumSampleSizes;
+
+    uint32_t mTimeToSampleCount;
+    uint32_t *mTimeToSample;
+
+    off_t mSyncSampleOffset;
+    uint32_t mNumSyncSamples;
+
+    SampleTable(const SampleTable &);
+    SampleTable &operator=(const SampleTable &);
+};
+
+}  // namespace android
+
+#endif  // SAMPLE_TABLE_H_
diff --git a/include/media/stagefright/ShoutcastSource.h b/include/media/stagefright/ShoutcastSource.h
new file mode 100644
index 0000000..352857a
--- /dev/null
+++ b/include/media/stagefright/ShoutcastSource.h
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+
+#ifndef SHOUTCAST_SOURCE_H_
+
+#define SHOUTCAST_SOURCE_H_
+
+#include <sys/types.h>
+
+#include <media/stagefright/MediaSource.h>
+
+namespace android {
+
+class HTTPStream;
+class MediaBufferGroup;
+
+class ShoutcastSource : public MediaSource {
+public:
+    // Assumes ownership of "http".
+    ShoutcastSource(HTTPStream *http);
+    virtual ~ShoutcastSource();
+
+    virtual status_t start(MetaData *params = NULL);
+    virtual status_t stop();
+
+    virtual sp<MetaData> getFormat();
+
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options = NULL);
+
+private:
+    HTTPStream *mHttp;
+    size_t mMetaDataOffset;
+    size_t mBytesUntilMetaData;
+
+    MediaBufferGroup *mGroup;
+    bool mStarted;
+
+    ShoutcastSource(const ShoutcastSource &);
+    ShoutcastSource &operator= (const ShoutcastSource &);
+};
+
+}  // namespace android
+
+#endif  // SHOUTCAST_SOURCE_H_
+
diff --git a/include/media/stagefright/SoftwareRenderer.h b/include/media/stagefright/SoftwareRenderer.h
new file mode 100644
index 0000000..705b914
--- /dev/null
+++ b/include/media/stagefright/SoftwareRenderer.h
@@ -0,0 +1,55 @@
+/*
+ * 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.
+ */
+
+#ifndef SOFTWARE_RENDERER_H_
+
+#define SOFTWARE_RENDERER_H_
+
+#include <media/stagefright/VideoRenderer.h>
+#include <utils/RefBase.h>
+
+namespace android {
+
+class ISurface;
+class MemoryHeapBase;
+
+class SoftwareRenderer : public VideoRenderer {
+public:
+    SoftwareRenderer(
+            const sp<ISurface> &surface,
+            size_t displayWidth, size_t displayHeight,
+            size_t decodedWidth, size_t decodedHeight);
+
+    virtual ~SoftwareRenderer();
+
+    virtual void render(
+            const void *data, size_t size, void *platformPrivate);
+
+private:
+    sp<ISurface> mISurface;
+    size_t mDisplayWidth, mDisplayHeight;
+    size_t mDecodedWidth, mDecodedHeight;
+    size_t mFrameSize;
+    sp<MemoryHeapBase> mMemoryHeap;
+    int mIndex;
+
+    SoftwareRenderer(const SoftwareRenderer &);
+    SoftwareRenderer &operator=(const SoftwareRenderer &);
+};
+
+}  // namespace android
+
+#endif  // SOFTWARE_RENDERER_H_
diff --git a/include/media/stagefright/SurfaceRenderer.h b/include/media/stagefright/SurfaceRenderer.h
new file mode 100644
index 0000000..298ab50
--- /dev/null
+++ b/include/media/stagefright/SurfaceRenderer.h
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+
+#ifndef SURFACE_RENDERER_H_
+
+#define SURFACE_RENDERER_H_
+
+#include <media/stagefright/VideoRenderer.h>
+#include <utils/RefBase.h>
+
+namespace android {
+
+class Surface;
+
+class SurfaceRenderer : public VideoRenderer {
+public:
+    SurfaceRenderer(
+            const sp<Surface> &surface,
+            size_t displayWidth, size_t displayHeight,
+            size_t decodedWidth, size_t decodedHeight);
+
+    virtual ~SurfaceRenderer();
+
+    virtual void render(
+            const void *data, size_t size, void *platformPrivate);
+
+private:
+    sp<Surface> mSurface;
+    size_t mDisplayWidth, mDisplayHeight;
+    size_t mDecodedWidth, mDecodedHeight;
+
+    SurfaceRenderer(const SurfaceRenderer &);
+    SurfaceRenderer &operator=(const SurfaceRenderer &);
+};
+
+}  // namespace android
+
+#endif  // SURFACE_RENDERER_H_
diff --git a/include/media/stagefright/TimeSource.h b/include/media/stagefright/TimeSource.h
new file mode 100644
index 0000000..443673d
--- /dev/null
+++ b/include/media/stagefright/TimeSource.h
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+
+#ifndef TIME_SOURCE_H_
+
+#define TIME_SOURCE_H_
+
+#include <stdint.h>
+
+namespace android {
+
+class TimeSource {
+public:
+    TimeSource() {}
+    virtual ~TimeSource() {}
+
+    virtual int64_t getRealTimeUs() = 0;
+
+private:
+    TimeSource(const TimeSource &);
+    TimeSource &operator=(const TimeSource &);
+};
+
+class SystemTimeSource : public TimeSource {
+public:
+    SystemTimeSource();
+
+    virtual int64_t getRealTimeUs();
+
+private:
+    static int64_t GetSystemTimeUs();
+
+    int64_t mStartTimeUs;
+};
+
+}  // namespace android
+
+#endif  // TIME_SOURCE_H_
diff --git a/include/media/stagefright/TimedEventQueue.h b/include/media/stagefright/TimedEventQueue.h
new file mode 100644
index 0000000..a264421
--- /dev/null
+++ b/include/media/stagefright/TimedEventQueue.h
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+
+#ifndef TIMED_EVENT_QUEUE_H_
+
+#define TIMED_EVENT_QUEUE_H_
+
+#include <pthread.h>
+
+#include <utils/List.h>
+#include <utils/RefBase.h>
+#include <utils/threads.h>
+
+namespace android {
+
+struct TimedEventQueue {
+
+    struct Event : public RefBase {
+        Event() {}
+        virtual ~Event() {}
+
+    protected:
+        virtual void fire(TimedEventQueue *queue, int64_t now_us) = 0;
+
+    private:
+        friend class TimedEventQueue;
+
+        Event(const Event &);
+        Event &operator=(const Event &);
+    };
+
+    TimedEventQueue();
+    ~TimedEventQueue();
+
+    // Start executing the event loop.
+    void start();
+
+    // Stop executing the event loop, if flush is false, any pending
+    // events are discarded, otherwise the queue will stop (and this call
+    // return) once all pending events have been handled.
+    void stop(bool flush = false);
+
+    // Posts an event to the front of the queue (after all events that
+    // have previously been posted to the front but before timed events).
+    void postEvent(const sp<Event> &event);
+
+    void postEventToBack(const sp<Event> &event);
+
+    // It is an error to post an event with a negative delay.
+    void postEventWithDelay(const sp<Event> &event, int64_t delay_us);
+
+    // If the event is to be posted at a time that has already passed,
+    // it will fire as soon as possible.
+    void postTimedEvent(const sp<Event> &event, int64_t realtime_us);
+
+    // Returns true iff event is currently in the queue and has been
+    // successfully cancelled. In this case the event will have been
+    // removed from the queue and won't fire.
+    bool cancelEvent(const sp<Event> &event);
+
+    static int64_t getRealTimeUs();
+
+private:
+    struct QueueItem {
+        sp<Event> event;
+        int64_t realtime_us;
+    };
+
+    struct StopEvent : public TimedEventQueue::Event {
+        virtual void fire(TimedEventQueue *queue, int64_t now_us) {
+            queue->mStopped = true;
+        }
+    };
+
+    pthread_t mThread;
+    List<QueueItem> mQueue;
+    Mutex mLock;
+    Condition mQueueNotEmptyCondition;
+    Condition mQueueHeadChangedCondition;
+
+    bool mRunning;
+    bool mStopped;
+
+    static void *ThreadWrapper(void *me);
+    void threadEntry();
+
+    TimedEventQueue(const TimedEventQueue &);
+    TimedEventQueue &operator=(const TimedEventQueue &);
+};
+
+}  // namespace android
+
+#endif  // TIMED_EVENT_QUEUE_H_
diff --git a/include/media/stagefright/Utils.h b/include/media/stagefright/Utils.h
new file mode 100644
index 0000000..30c7f11
--- /dev/null
+++ b/include/media/stagefright/Utils.h
@@ -0,0 +1,37 @@
+/*
+ * 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.
+ */
+
+#ifndef UTILS_H_
+
+#define UTILS_H_
+
+#include <stdint.h>
+
+namespace android {
+
+#define FOURCC(c1, c2, c3, c4) \
+    (c1 << 24 | c2 << 16 | c3 << 8 | c4)
+
+uint16_t U16_AT(const uint8_t *ptr);
+uint32_t U32_AT(const uint8_t *ptr);
+uint64_t U64_AT(const uint8_t *ptr);
+
+uint64_t ntoh64(uint64_t x);
+uint64_t hton64(uint64_t x);
+
+}  // namespace android
+
+#endif  // UTILS_H_
diff --git a/include/media/stagefright/VideoRenderer.h b/include/media/stagefright/VideoRenderer.h
new file mode 100644
index 0000000..f80b277
--- /dev/null
+++ b/include/media/stagefright/VideoRenderer.h
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+#ifndef VIDEO_RENDERER_H_
+
+#define VIDEO_RENDERER_H_
+
+#include <sys/types.h>
+
+namespace android {
+
+class VideoRenderer {
+public:
+    virtual ~VideoRenderer() {}
+
+    virtual void render(
+            const void *data, size_t size, void *platformPrivate) = 0;
+
+protected:
+    VideoRenderer() {}
+
+    VideoRenderer(const VideoRenderer &);
+    VideoRenderer &operator=(const VideoRenderer &);
+};
+
+}  // namespace android
+
+#endif  // VIDEO_RENDERER_H_
diff --git a/include/media/stagefright/string.h b/include/media/stagefright/string.h
new file mode 100644
index 0000000..5dc7116
--- /dev/null
+++ b/include/media/stagefright/string.h
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ */
+
+#ifndef STRING_H_
+
+#define STRING_H_
+
+#include <utils/String8.h>
+
+namespace android {
+
+class string {
+public:
+    typedef size_t size_type;
+    static size_type npos;
+
+    string();
+    string(const char *s);
+    string(const char *s, size_t length);
+    string(const string &from, size_type start, size_type length = npos);
+
+    const char *c_str() const;
+    size_type size() const;
+
+    void clear();
+    void erase(size_type from, size_type length);
+
+    size_type find(char c) const;
+
+    bool operator<(const string &other) const;
+    bool operator==(const string &other) const;
+
+    string &operator+=(char c);
+
+private:
+    String8 mString;
+};
+
+}  // namespace android
+
+#endif  // STRING_H_
diff --git a/include/private/binder/Static.h b/include/private/binder/Static.h
new file mode 100644
index 0000000..5b0f9fc
--- /dev/null
+++ b/include/private/binder/Static.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2008 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.
+ */
+
+// All static variables go here, to control initialization and
+// destruction order in the library.
+
+#include <utils/threads.h>
+
+#include <binder/IBinder.h>
+#include <binder/IMemory.h>
+#include <binder/ProcessState.h>
+#include <binder/IPermissionController.h>
+#include <binder/IServiceManager.h>
+
+namespace android {
+
+// For ProcessState.cpp
+extern Mutex gProcessMutex;
+extern sp<ProcessState> gProcess;
+
+// For ServiceManager.cpp
+extern Mutex gDefaultServiceManagerLock;
+extern sp<IServiceManager> gDefaultServiceManager;
+extern sp<IPermissionController> gPermissionController;
+
+}   // namespace android
diff --git a/include/private/utils/binder_module.h b/include/private/binder/binder_module.h
similarity index 100%
rename from include/private/utils/binder_module.h
rename to include/private/binder/binder_module.h
diff --git a/include/private/media/AudioTrackShared.h b/include/private/media/AudioTrackShared.h
index 496a739..8e2db20 100644
--- a/include/private/media/AudioTrackShared.h
+++ b/include/private/media/AudioTrackShared.h
@@ -55,17 +55,18 @@
                     uint32_t    volumeLR;
                 };
                 uint32_t    sampleRate;
+                // NOTE: audio_track_cblk_t::frameSize is not equal to AudioTrack::frameSize() for
+                // 8 bit PCM data: in this case,  mCblk->frameSize is based on a sample size of
+                // 16 bit because data is converted to 16 bit before being stored in buffer
+                uint32_t    frameSize;
                 uint8_t     channels;
                 uint8_t     flowControlFlag; // underrun (out) or overrrun (in) indication
                 uint8_t     out;        // out equals 1 for AudioTrack and 0 for AudioRecord
-                uint8_t     forceReady; 
+                uint8_t     forceReady;
                 uint16_t    bufferTimeoutMs; // Maximum cumulated timeout before restarting audioflinger
                 uint16_t    waitTimeMs;      // Cumulated wait time
-                // Padding ensuring that data buffer starts on a cache line boundary (32 bytes). 
-                // See AudioFlinger::TrackBase constructor
-                int32_t     Padding[1];
-                // Cache line boundary
-                
+                // Cache line boundary (32 bytes)
+
                             audio_track_cblk_t();
                 uint32_t    stepUser(uint32_t frameCount);
                 bool        stepServer(uint32_t frameCount);
diff --git a/include/private/opengles/gl_context.h b/include/private/opengles/gl_context.h
index a85f275..523aed0 100644
--- a/include/private/opengles/gl_context.h
+++ b/include/private/opengles/gl_context.h
@@ -26,6 +26,8 @@
 #endif
 
 #include <private/pixelflinger/ggl_context.h>
+#include <hardware/copybit.h>
+#include <hardware/gralloc.h>
 
 #include <GLES/gl.h>
 #include <GLES/glext.h>
@@ -39,7 +41,7 @@
 class EGLBufferObjectManager;
 
 namespace gl {
- 
+
 struct ogles_context_t;
 struct matrixx_t;
 struct transform_t;
@@ -96,7 +98,7 @@
 
 struct vertex_t {
     enum {
-        // these constant matter for our clipping 
+        // these constant matter for our clipping
         CLIP_L          = 0x0001,   // clipping flags
         CLIP_R          = 0x0002,
         CLIP_B          = 0x0004,
@@ -106,7 +108,7 @@
 
         EYE             = 0x0040,
         RESERVED        = 0x0080,
-        
+
         USER_CLIP_0     = 0x0100,   // user clipping flags
         USER_CLIP_1     = 0x0200,
         USER_CLIP_2     = 0x0400,
@@ -121,7 +123,7 @@
         USER_CLIP_ALL   = 0x3F00,
         CLIP_ALL        = 0x3F3F,
     };
-    
+
     // the fields below are arranged to minimize d-cache usage
     // we group together, by cache-line, the fields most likely to be used
 
@@ -130,7 +132,7 @@
     vec4_t          eye;
     };
     vec4_t          clip;
-    
+
     uint32_t        flags;
     size_t          index;  // cache tag, and vertex index
     GLfixed         fog;
@@ -142,7 +144,7 @@
     vec4_t          color;
     vec4_t          texture[GGL_TEXTURE_UNIT_COUNT];
     uint32_t        reserved1[4];
-    
+
     inline void clear() {
         flags = index = locked = mru = 0;
     }
@@ -199,7 +201,7 @@
     GLenum          indicesType;
     buffer_t const* array_buffer;
     buffer_t const* element_array_buffer;
-    
+
     void (*compileElements)(ogles_context_t*, vertex_t*, GLint, GLsizei);
     void (*compileElement)(ogles_context_t*, vertex_t*, GLint);
 
@@ -410,7 +412,7 @@
     matrixx_t       matrix;
     uint32_t        flags;
     uint32_t        ops;
-    
+
     union {
         struct {
             void (*point2)(transform_t const* t, vec4_t*, vec4_t const*);
@@ -509,17 +511,17 @@
     GLint       x;
     GLint       y;
     GLsizei     w;
-    GLsizei     h; 
+    GLsizei     h;
     struct {
         GLint       x;
         GLint       y;
-    } surfaceport;  
+    } surfaceport;
     struct {
         GLint       x;
         GLint       y;
         GLsizei     w;
-        GLsizei     h; 
-    } scissor;  
+        GLsizei     h;
+    } scissor;
 };
 
 // ----------------------------------------------------------------------------
@@ -594,6 +596,14 @@
     void (*renderTriangle)(GL, vertex_t*, vertex_t*, vertex_t*);
 };
 
+struct copybits_context_t {
+    // A handle to the blit engine, if it exists, else NULL.
+    copybit_device_t*       blitEngine;
+    int32_t                 minScale;
+    int32_t                 maxScale;
+    buffer_handle_t         drawSurfaceBuffer;
+};
+
 struct ogles_context_t {
     context_t               rasterizer;
     array_machine_t         arrays         __attribute__((aligned(32)));
@@ -617,6 +627,14 @@
     uint32_t                transformTextures : 1;
     EGLSurfaceManager*      surfaceManager;
     EGLBufferObjectManager* bufferObjectManager;
+
+    // copybits is only used if LIBAGL_USE_GRALLOC_COPYBITS is
+    // defined, but it is always present because ogles_context_t is a public
+    // struct that is used by clients of libagl. We want the size and offsets
+    // to stay the same, whether or not LIBAGL_USE_GRALLOC_COPYBITS is defined.
+
+    copybits_context_t      copybits;
+
     GLenum                  error;
 
     static inline ogles_context_t* get() {
diff --git a/include/private/ui/RegionHelper.h b/include/private/ui/RegionHelper.h
new file mode 100644
index 0000000..926fddb
--- /dev/null
+++ b/include/private/ui/RegionHelper.h
@@ -0,0 +1,281 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_UI_PRIVATE_REGION_HELPER_H
+#define ANDROID_UI_PRIVATE_REGION_HELPER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+namespace android {
+// ----------------------------------------------------------------------------
+
+template<typename RECT>
+class region_operator
+{
+    typedef typename RECT::value_type TYPE;    
+    static const TYPE max_value = 0x7FFFFFF;
+
+public:
+    /* 
+     * Common boolean operations:
+     * value is computed as 0b101 op 0b110
+     *    other boolean operation are possible, simply compute
+     *    their corresponding value with the above formulae and use
+     *    it when instantiating a region_operator.
+     */
+    static const uint32_t LHS = 0x5;  // 0b101
+    static const uint32_t RHS = 0x6;  // 0b110
+    enum {
+        op_nand = LHS & ~RHS,
+        op_and  = LHS &  RHS,
+        op_or   = LHS |  RHS,
+        op_xor  = LHS ^  RHS
+    };
+
+    struct region {
+        RECT const* rects;
+        size_t count;
+        TYPE dx;
+        TYPE dy;
+        inline region(const region& rhs) 
+            : rects(rhs.rects), count(rhs.count), dx(rhs.dx), dy(rhs.dy) { }
+        inline region(RECT const* r, size_t c) 
+            : rects(r), count(c), dx(), dy() { }
+        inline region(RECT const* r, size_t c, TYPE dx, TYPE dy) 
+            : rects(r), count(c), dx(dx), dy(dy) { }
+    };
+
+    class region_rasterizer {
+        friend class region_operator;
+        virtual void operator()(const RECT& rect) = 0;
+    public:
+        virtual ~region_rasterizer() { };
+    };
+    
+    inline region_operator(int op, const region& lhs, const region& rhs) 
+        : op_mask(op), spanner(lhs, rhs) 
+    {
+    }
+
+    void operator()(region_rasterizer& rasterizer) {
+        RECT current;
+        do {
+            SpannerInner spannerInner(spanner.lhs, spanner.rhs);
+            int inside = spanner.next(current.top, current.bottom);
+            spannerInner.prepare(inside);
+            do {
+                TYPE left, right;
+                int inside = spannerInner.next(current.left, current.right);
+                if ((op_mask >> inside) & 1) {
+                    if (current.left < current.right && 
+                            current.top < current.bottom) {
+                        rasterizer(current);
+                    }
+                }
+            } while(!spannerInner.isDone());            
+        } while(!spanner.isDone());
+    }
+
+private:    
+    uint32_t op_mask;
+
+    class SpannerBase
+    {
+    public:
+        enum {
+            lhs_before_rhs   = 0,
+            lhs_after_rhs    = 1,
+            lhs_coincide_rhs = 2
+        };
+
+    protected:
+        TYPE lhs_head;
+        TYPE lhs_tail;
+        TYPE rhs_head;
+        TYPE rhs_tail;
+
+        inline int next(TYPE& head, TYPE& tail,
+                bool& more_lhs, bool& more_rhs) 
+        {
+            int inside;
+            more_lhs = false;
+            more_rhs = false;
+            if (lhs_head < rhs_head) {
+                inside = lhs_before_rhs;
+                head = lhs_head;
+                if (lhs_tail <= rhs_head) {
+                    tail = lhs_tail;
+                    more_lhs = true;
+                } else {
+                    lhs_head = rhs_head;
+                    tail = rhs_head;
+                }
+            } else if (rhs_head < lhs_head) {
+                inside = lhs_after_rhs;
+                head = rhs_head;
+                if (rhs_tail <= lhs_head) {
+                    tail = rhs_tail;
+                    more_rhs = true;
+                } else {
+                    rhs_head = lhs_head;
+                    tail = lhs_head;
+                }
+            } else {
+                inside = lhs_coincide_rhs;
+                head = lhs_head;
+                if (lhs_tail <= rhs_tail) {
+                    tail = rhs_head = lhs_tail;
+                    more_lhs = true;
+                }
+                if (rhs_tail <= lhs_tail) {
+                    tail = lhs_head = rhs_tail;
+                    more_rhs = true;
+                }
+            }
+            return inside;
+        }
+    };
+
+    class Spanner : protected SpannerBase 
+    {
+        friend class region_operator;
+        region lhs;
+        region rhs;
+
+    public:
+        inline Spanner(const region& lhs, const region& rhs)
+            : lhs(lhs), rhs(rhs) 
+        {
+            SpannerBase::lhs_head = lhs.rects->top      + lhs.dy;
+            SpannerBase::lhs_tail = lhs.rects->bottom   + lhs.dy;
+            SpannerBase::rhs_head = rhs.rects->top      + rhs.dy;
+            SpannerBase::rhs_tail = rhs.rects->bottom   + rhs.dy;
+        }
+
+        inline bool isDone() const {
+            return !rhs.count && !lhs.count;
+        }
+
+        inline int next(TYPE& top, TYPE& bottom) 
+        {
+            bool more_lhs = false;
+            bool more_rhs = false;
+            int inside = SpannerBase::next(top, bottom, more_lhs, more_rhs);
+            if (more_lhs) {
+                advance(lhs, SpannerBase::lhs_head, SpannerBase::lhs_tail);
+            }
+            if (more_rhs) {
+                advance(rhs, SpannerBase::rhs_head, SpannerBase::rhs_tail);
+            }
+            return inside;
+        }
+
+    private:
+        static inline 
+        void advance(region& reg, TYPE& aTop, TYPE& aBottom) {
+            // got to next span
+            size_t count = reg.count;
+            RECT const * rects = reg.rects;
+            RECT const * const end = rects + count;
+            const int top = rects->top;
+            while (rects != end && rects->top == top) {
+                rects++;
+                count--;
+            }
+            if (rects != end) {
+                aTop    = rects->top    + reg.dy;
+                aBottom = rects->bottom + reg.dy;
+            } else {
+                aTop    = max_value;
+                aBottom = max_value;
+            }
+            reg.rects = rects;
+            reg.count = count;
+        }
+    };
+
+    class SpannerInner : protected SpannerBase 
+    {
+        region lhs;
+        region rhs;
+        
+    public:
+        inline SpannerInner(const region& lhs, const region& rhs)
+            : lhs(lhs), rhs(rhs) 
+        {
+        }
+
+        inline void prepare(int inside) {
+            SpannerBase::lhs_head = lhs.rects->left  + lhs.dx;
+            SpannerBase::lhs_tail = lhs.rects->right + lhs.dx;
+            SpannerBase::rhs_head = rhs.rects->left  + rhs.dx;
+            SpannerBase::rhs_tail = rhs.rects->right + rhs.dx;
+            if (inside == SpannerBase::lhs_before_rhs) {
+                SpannerBase::rhs_head = max_value;
+                SpannerBase::rhs_tail = max_value;
+            } else if (inside == SpannerBase::lhs_after_rhs) {
+                SpannerBase::lhs_head = max_value;
+                SpannerBase::lhs_tail = max_value;
+            } else {
+                // use both spans
+            }
+        }
+
+        inline bool isDone() const {
+            return SpannerBase::lhs_head == max_value && 
+                   SpannerBase::rhs_head == max_value;
+        }
+
+        inline int next(TYPE& left, TYPE& right) 
+        {
+            bool more_lhs = false;
+            bool more_rhs = false;
+            int inside = SpannerBase::next(left, right, more_lhs, more_rhs);
+            if (more_lhs) {
+                advance(lhs, SpannerBase::lhs_head, SpannerBase::lhs_tail);
+            }
+            if (more_rhs) {
+                advance(rhs, SpannerBase::rhs_head, SpannerBase::rhs_tail);
+            }
+            return inside;
+        }
+
+    private:
+        static inline 
+        void advance(region& reg, TYPE& left, TYPE& right) {
+            if (reg.rects && reg.count) {
+                const int cur_span_top = reg.rects->top;
+                reg.rects++;
+                reg.count--;
+                if (!reg.count || reg.rects->top != cur_span_top) {
+                    left  = max_value;
+                    right = max_value;
+                } else {
+                    left  = reg.rects->left  + reg.dx;
+                    right = reg.rects->right + reg.dx;
+                }
+            }
+        }
+    };
+
+    Spanner spanner;
+};
+
+// ----------------------------------------------------------------------------
+};
+
+#endif /* ANDROID_UI_PRIVATE_REGION_HELPER_H */
diff --git a/include/private/ui/SharedState.h b/include/private/ui/SharedState.h
index 546d0ad..c9f6b5e 100644
--- a/include/private/ui/SharedState.h
+++ b/include/private/ui/SharedState.h
@@ -20,6 +20,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
+#include <utils/Debug.h>
 #include <utils/threads.h>
 
 namespace android {
@@ -32,16 +33,12 @@
 
 struct surface_info_t { // 4 longs, 16 bytes
     enum {
-        eBufferDirty    = 0x01
+        eBufferDirty    = 0x01,
+        eNeedNewBuffer  = 0x02
     };
-    uint16_t    w;
-    uint16_t    h;
-    uint16_t    stride;
-    uint16_t    bpr;
-    uint16_t    reserved;
-    uint8_t     format;
+    uint8_t     reserved[11];
     uint8_t     flags;
-    ssize_t     bits_offset;
+    status_t    status;
 };
 
 // ---------------------------------------------------------------------------
@@ -101,6 +98,8 @@
 
 struct per_client_cblk_t   // 4KB max
 {
+    per_client_cblk_t() : lock(Mutex::SHARED) { }
+
                 Mutex           lock;
                 Condition       cv;
                 layer_cblk_t    layers[NUM_LAYERS_MAX] __attribute__((aligned(32)));
@@ -110,8 +109,6 @@
         INSPECT  = 0x00000002
     };
 
-    per_client_cblk_t();
-
     // these functions are used by the clients
     status_t validate(size_t i) const;
     int32_t lock_layer(size_t i, uint32_t flags);
@@ -138,30 +135,19 @@
 
 struct surface_flinger_cblk_t   // 4KB max
 {
-    surface_flinger_cblk_t();
-    
     uint8_t         connected;
     uint8_t         reserved[3];
     uint32_t        pad[7];
- 
     display_cblk_t  displays[NUM_DISPLAY_MAX];
 };
 
 // ---------------------------------------------------------------------------
 
-template<bool> struct CTA;
-template<> struct CTA<true> { };
+COMPILE_TIME_ASSERT(sizeof(layer_cblk_t) == 128)
+COMPILE_TIME_ASSERT(sizeof(per_client_cblk_t) <= 4096)
+COMPILE_TIME_ASSERT(sizeof(surface_flinger_cblk_t) <= 4096)
 
-// compile-time assertions. just to avoid catastrophes.
-inline void compile_time_asserts() {
-    CTA<sizeof(layer_cblk_t) == 128> sizeof__layer_cblk_t__eq_128;
-    (void)sizeof__layer_cblk_t__eq_128; // we don't want a warning
-    CTA<sizeof(per_client_cblk_t) <= 4096> sizeof__per_client_cblk_t__le_4096;
-    (void)sizeof__per_client_cblk_t__le_4096;  // we don't want a warning
-    CTA<sizeof(surface_flinger_cblk_t) <= 4096> sizeof__surface_flinger_cblk_t__le_4096;
-    (void)sizeof__surface_flinger_cblk_t__le_4096;  // we don't want a warning
-}
-
+// ---------------------------------------------------------------------------
 }; // namespace android
 
 #endif // ANDROID_UI_SHARED_STATE_H
diff --git a/include/private/ui/SurfaceBuffer.h b/include/private/ui/SurfaceBuffer.h
new file mode 100644
index 0000000..bf68406
--- /dev/null
+++ b/include/private/ui/SurfaceBuffer.h
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_UI_PRIVATE_SURFACE_BUFFER_H
+#define ANDROID_UI_PRIVATE_SURFACE_BUFFER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/RefBase.h>
+
+#include <private/ui/android_natives_priv.h>
+
+namespace android {
+
+// ---------------------------------------------------------------------------
+
+class BufferMapper;
+class Parcel;
+class Rect;
+class Surface;
+class SurfaceBuffer;
+
+// ---------------------------------------------------------------------------
+
+class SurfaceBuffer 
+    : public EGLNativeBase<
+        android_native_buffer_t, 
+        SurfaceBuffer, 
+        LightRefBase<SurfaceBuffer> >
+{
+public:
+    status_t lock(uint32_t usage, void** vaddr);
+    status_t lock(uint32_t usage, const Rect& rect, void** vaddr);
+    status_t unlock();
+
+protected:
+            SurfaceBuffer();
+            SurfaceBuffer(const Parcel& reply);
+    virtual ~SurfaceBuffer();
+    bool mOwner;
+
+    inline const BufferMapper& getBufferMapper() const { return mBufferMapper; }
+    inline BufferMapper& getBufferMapper() { return mBufferMapper; }
+    
+private:
+    friend class Surface;
+    friend class BpSurface;
+    friend class BnSurface;
+    friend class LightRefBase<SurfaceBuffer>;    
+
+    SurfaceBuffer& operator = (const SurfaceBuffer& rhs);
+    const SurfaceBuffer& operator = (const SurfaceBuffer& rhs) const;
+
+    static status_t writeToParcel(Parcel* reply, 
+            android_native_buffer_t const* buffer);
+    
+    BufferMapper& mBufferMapper;
+};
+
+}; // namespace android
+
+#endif // ANDROID_UI_PRIVATE_SURFACE_BUFFER_H
+
diff --git a/include/private/ui/SurfaceFlingerSynchro.h b/include/private/ui/SurfaceFlingerSynchro.h
index ff91b61..7386d33 100644
--- a/include/private/ui/SurfaceFlingerSynchro.h
+++ b/include/private/ui/SurfaceFlingerSynchro.h
@@ -21,7 +21,6 @@
 #include <stdint.h>
 #include <sys/types.h>
 #include <utils/Errors.h>
-#include <utils/threads.h>
 #include <ui/ISurfaceComposer.h>
 
 namespace android {
@@ -31,7 +30,6 @@
 class SurfaceFlingerSynchro
 {
 public:
-
                 // client constructor
                 SurfaceFlingerSynchro(const sp<ISurfaceComposer>& flinger);
                 ~SurfaceFlingerSynchro();
@@ -40,34 +38,8 @@
     status_t    signal();
     
 private:
-    class Barrier {
-    public:
-        Barrier();
-        ~Barrier();
-        void open();
-        void close();
-        void waitAndClose();
-        status_t waitAndClose(nsecs_t timeout);
-    private:
-        enum { OPENED, CLOSED };
-        mutable     Mutex       lock;
-        mutable     Condition   cv;
-        volatile    int         state;
-    };
-
     friend class SurfaceFlinger;
-
-                // server constructor
-                SurfaceFlingerSynchro();
-                
-    void        open();
-    
-                // wait until there is some work to do
-    status_t    wait();
-    status_t    wait(nsecs_t timeout);
-    
     sp<ISurfaceComposer> mSurfaceComposer;
-    Barrier              mBarrier;
 };
 
 }; // namespace android
diff --git a/include/private/ui/android_natives_priv.h b/include/private/ui/android_natives_priv.h
new file mode 100644
index 0000000..ee843e9
--- /dev/null
+++ b/include/private/ui/android_natives_priv.h
@@ -0,0 +1,62 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_ANDROID_NATIVES_PRIV_H
+#define ANDROID_ANDROID_NATIVES_PRIV_H
+
+#include <ui/egl/android_natives.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*****************************************************************************/
+
+struct android_native_buffer_t
+{
+#ifdef __cplusplus
+    android_native_buffer_t() { 
+        common.magic = ANDROID_NATIVE_BUFFER_MAGIC;
+        common.version = sizeof(android_native_buffer_t);
+        memset(common.reserved, 0, sizeof(common.reserved));
+    }
+#endif
+
+    struct android_native_base_t common;
+
+    int width;
+    int height;
+    int stride;
+    int format;
+    int usage;
+    
+    void* reserved[2];
+
+    buffer_handle_t handle;
+
+    void* reserved_proc[8];
+};
+
+
+/*****************************************************************************/
+
+#ifdef __cplusplus
+}
+#endif
+
+/*****************************************************************************/
+
+#endif /* ANDROID_ANDROID_NATIVES_PRIV_H */
diff --git a/include/private/utils/Static.h b/include/private/utils/Static.h
index f1439b7..d95ae0d 100644
--- a/include/private/utils/Static.h
+++ b/include/private/utils/Static.h
@@ -20,14 +20,6 @@
 #include <utils/threads.h>
 #include <utils/KeyedVector.h>
 
-#ifndef LIBUTILS_NATIVE
-#include <utils/IBinder.h>
-#include <utils/IMemory.h>
-#include <utils/ProcessState.h>
-#include <utils/IPermissionController.h>
-#include <utils/IServiceManager.h>
-#endif
-
 namespace android {
 // For TextStream.cpp
 extern Vector<int32_t> gTextBuffers;
@@ -40,19 +32,4 @@
 extern void initialize_string16();
 extern void terminate_string16();
 
-
-
-#ifndef LIBUTILS_NATIVE
-
-// For ProcessState.cpp
-extern Mutex gProcessMutex;
-extern sp<ProcessState> gProcess;
-
-// For ServiceManager.cpp
-extern Mutex gDefaultServiceManagerLock;
-extern sp<IServiceManager> gDefaultServiceManager;
-extern sp<IPermissionController> gPermissionController;
-
-#endif
-
 }   // namespace android
diff --git a/include/private/utils/futex_synchro.h b/include/private/utils/futex_synchro.h
deleted file mode 100644
index ac2ab19..0000000
--- a/include/private/utils/futex_synchro.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2008 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 _FUTEX_SYNCHRO_H
-#define _FUTEX_SYNCHRO_H
-
-#ifndef HAVE_FUTEX
-#error "HAVE_FUTEX not defined"
-#endif
-
-#define FUTEX_WAIT_INFINITE (0)
-
-typedef struct futex_mutex_t futex_mutex_t;
-
-struct futex_mutex_t 
-{
-    volatile int value;
-};
-
-typedef struct futex_cond_t futex_cond_t;
-
-struct futex_cond_t 
-{
-    volatile int value;
-};
-
-
-#if __cplusplus
-extern "C" {
-#endif
-
-void futex_mutex_init(futex_mutex_t *m);
-int futex_mutex_lock(futex_mutex_t *m, unsigned msec);
-void futex_mutex_unlock(futex_mutex_t *m);
-int futex_mutex_trylock(futex_mutex_t *m);
-
-void futex_cond_init(futex_cond_t *c);
-int futex_cond_wait(futex_cond_t *c, futex_mutex_t *m, unsigned msec);
-void futex_cond_signal(futex_cond_t *c);
-void futex_cond_broadcast(futex_cond_t *c);
-
-#if __cplusplus
-} // extern "C"
-#endif
-
-#endif // _FUTEX_SYNCHRO_H
-
diff --git a/include/tts/TtsEngine.h b/include/tts/TtsEngine.h
index 21cb73b..28b0d2f 100644
--- a/include/tts/TtsEngine.h
+++ b/include/tts/TtsEngine.h
@@ -43,7 +43,7 @@
 // @param [inout] void *&       - The userdata pointer set in the original
 //                                 synth call
 // @param [in]    uint32_t      - Track sampling rate in Hz
-// @param [in]    audio_format  - The AudioSystem::audio_format enum
+// @param [in]    uint32_t      - The audio format
 // @param [in]    int           - The number of channels
 // @param [inout] int8_t *&     - A buffer of audio data only valid during the
 //                                execution of the callback
@@ -54,7 +54,7 @@
 //         TTS_CALLBACK_CONTINUE to indicate the synthesis must continue if
 //            there is more data to produce.
 typedef tts_callback_status (synthDoneCB_t)(void *&, uint32_t,
-        AudioSystem::audio_format, int, int8_t *&, size_t&, tts_synth_status);
+        uint32_t, int, int8_t *&, size_t&, tts_synth_status);
 
 class TtsEngine;
 extern "C" TtsEngine* getTtsEngine();
@@ -80,6 +80,8 @@
 class TtsEngine
 {
 public:
+    virtual ~TtsEngine() {}
+
     // Initialize the TTS engine and returns whether initialization succeeded.
     // @param synthDoneCBPtr synthesis callback function pointer
     // @return TTS_SUCCESS, or TTS_FAILURE
diff --git a/include/ui/BufferMapper.h b/include/ui/BufferMapper.h
new file mode 100644
index 0000000..5f084be
--- /dev/null
+++ b/include/ui/BufferMapper.h
@@ -0,0 +1,64 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_UI_BUFFER_MAPPER_H
+#define ANDROID_UI_BUFFER_MAPPER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Singleton.h>
+
+#include <hardware/gralloc.h>
+
+
+struct gralloc_module_t;
+
+namespace android {
+
+// ---------------------------------------------------------------------------
+
+class Rect;
+
+class BufferMapper : public Singleton<BufferMapper>
+{
+public:
+    static inline BufferMapper& get() { return getInstance(); }
+
+    status_t registerBuffer(buffer_handle_t handle);
+
+    status_t unregisterBuffer(buffer_handle_t handle);
+    
+    status_t lock(buffer_handle_t handle,
+            int usage, const Rect& bounds, void** vaddr);
+
+    status_t unlock(buffer_handle_t handle);
+    
+    // dumps information about the mapping of this handle
+    void dump(buffer_handle_t handle);
+
+private:
+    friend class Singleton<BufferMapper>;
+    BufferMapper();
+    gralloc_module_t const *mAllocMod;
+};
+
+// ---------------------------------------------------------------------------
+
+}; // namespace android
+
+#endif // ANDROID_UI_BUFFER_MAPPER_H
+
diff --git a/include/ui/CameraHardwareInterface.h b/include/ui/CameraHardwareInterface.h
index 822b4a8..c703f5e 100644
--- a/include/ui/CameraHardwareInterface.h
+++ b/include/ui/CameraHardwareInterface.h
@@ -17,7 +17,7 @@
 #ifndef ANDROID_HARDWARE_CAMERA_HARDWARE_INTERFACE_H
 #define ANDROID_HARDWARE_CAMERA_HARDWARE_INTERFACE_H
 
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 #include <utils/RefBase.h>
 #include <ui/CameraParameters.h>
 #include <ui/Overlay.h>
diff --git a/include/ui/EGLDisplaySurface.h b/include/ui/EGLDisplaySurface.h
deleted file mode 100644
index a8b5853..0000000
--- a/include/ui/EGLDisplaySurface.h
+++ /dev/null
@@ -1,86 +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.
- */
-
-#ifndef ANDROID_EGL_DISPLAY_SURFACE_H
-#define ANDROID_EGL_DISPLAY_SURFACE_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Timers.h>
-
-#include <ui/EGLNativeSurface.h>
-
-#include <pixelflinger/pixelflinger.h>
-#include <linux/fb.h>
-
-#include <EGL/egl.h>
-
-struct copybit_device_t;
-struct copybit_image_t;
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-class Region;
-class Rect;
-
-class EGLDisplaySurface : public EGLNativeSurface<EGLDisplaySurface>
-{
-public:
-    EGLDisplaySurface();
-    ~EGLDisplaySurface();
-    
-    int32_t getPageFlipCount() const;
-    void    copyFrontToBack(const Region& copyback);
-    void    copyFrontToImage(const copybit_image_t& dst);
-    void    copyBackToImage(const copybit_image_t& dst);
-    
-    void        setSwapRectangle(int l, int t, int w, int h);
-
-private:
-    static void         hook_incRef(NativeWindowType window);
-    static void         hook_decRef(NativeWindowType window);
-    static uint32_t     hook_swapBuffers(NativeWindowType window);
-     
-            uint32_t    swapBuffers();
-
-            status_t    mapFrameBuffer();
-
-            enum {
-                PAGE_FLIP = 0x00000001
-            };
-    GGLSurface          mFb[2];
-    int                 mIndex;
-    uint32_t            mFlags;
-    size_t              mSize;
-    fb_var_screeninfo   mInfo;
-    fb_fix_screeninfo   mFinfo;
-    int32_t             mPageFlipCount;
-    nsecs_t             mTime;
-    int32_t             mSwapCount;
-    nsecs_t             mSleep;
-    uint32_t            mFeatureFlags;
-    copybit_device_t*   mBlitEngine;
-};
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_EGL_DISPLAY_SURFACE_H
-
diff --git a/include/ui/EGLNativeWindowSurface.h b/include/ui/EGLNativeWindowSurface.h
deleted file mode 100644
index 3494234..0000000
--- a/include/ui/EGLNativeWindowSurface.h
+++ /dev/null
@@ -1,59 +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.
- */
-
-#ifndef ANDROID_EGL_NATIVE_WINDOW_SURFACE_H
-#define ANDROID_EGL_NATIVE_WINDOW_SURFACE_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <ui/EGLNativeSurface.h>
-#include <EGL/egl.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-class Surface;
-
-class EGLNativeWindowSurface : public EGLNativeSurface<EGLNativeWindowSurface>
-{
-public:
-    EGLNativeWindowSurface(const sp<Surface>& surface);
-    ~EGLNativeWindowSurface();
-
-    void        setSwapRectangle(int l, int t, int w, int h);
-
-private:
-    static void         hook_incRef(NativeWindowType window);
-    static void         hook_decRef(NativeWindowType window);
-    static uint32_t     hook_swapBuffers(NativeWindowType window);
-    static void         hook_connect(NativeWindowType window);
-    static void         hook_disconnect(NativeWindowType window);
-
-            uint32_t    swapBuffers();
-            void        connect();
-            void        disconnect();
-            
-            sp<Surface> mSurface;
-            bool        mConnected;
-};
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_EGL_NATIVE_WINDOW_SURFACE_H
-
diff --git a/include/ui/EventHub.h b/include/ui/EventHub.h
index 3848d8c..d62fd7d 100644
--- a/include/ui/EventHub.h
+++ b/include/ui/EventHub.h
@@ -20,7 +20,10 @@
 
 #include <utils/String8.h>
 #include <utils/threads.h>
-#include <utils.h>
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 
 #include <linux/input.h>
 
@@ -70,6 +73,13 @@
     int getKeycodeState(int key) const;
     int getKeycodeState(int32_t deviceId, int key) const;
     
+    status_t scancodeToKeycode(int32_t deviceId, int scancode,
+            int32_t* outKeycode, uint32_t* outFlags) const;
+
+    // exclude a particular device from opening
+    // this can be used to ignore input devices for sensors
+    void addExcludedDevice(const char* deviceName);
+
     // special type codes when devices are added/removed.
     enum {
         DEVICE_ADDED = 0x10000000,
@@ -82,10 +92,9 @@
     virtual bool getEvent(int32_t* outDeviceId, int32_t* outType,
             int32_t* outScancode, int32_t* outKeycode, uint32_t *outFlags,
             int32_t* outValue, nsecs_t* outWhen);
-    
+
 protected:
     virtual ~EventHub();
-    virtual void onFirstRef();
     
 private:
     bool openPlatformInput(void);
@@ -118,7 +127,7 @@
     mutable Mutex   mLock;
     
     bool            mHaveFirstKeyboard;
-    int32_t         mFirstKeyboardId; // the API is that the build in keyboard is id 0, so map it
+    int32_t         mFirstKeyboardId; // the API is that the built-in keyboard is id 0, so map it
     
     struct device_ent {
         device_t* device;
@@ -133,7 +142,10 @@
     device_t        **mDevices;
     struct pollfd   *mFDs;
     int             mFDCount;
-    
+
+    bool            mOpened;
+    List<String8>   mExcludedDevices;
+
     // device ids that report particular switches.
 #ifdef EV_SW
     int32_t         mSwitches[SW_MAX+1];
diff --git a/include/ui/FramebufferNativeWindow.h b/include/ui/FramebufferNativeWindow.h
new file mode 100644
index 0000000..e72357a
--- /dev/null
+++ b/include/ui/FramebufferNativeWindow.h
@@ -0,0 +1,85 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_FRAMEBUFFER_NATIVE_WINDOW_H
+#define ANDROID_FRAMEBUFFER_NATIVE_WINDOW_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <EGL/egl.h>
+
+#include <utils/threads.h>
+#include <ui/Rect.h>
+
+#include <pixelflinger/pixelflinger.h>
+
+#include <ui/egl/android_natives.h>
+
+
+extern "C" EGLNativeWindowType android_createDisplaySurface(void);
+
+// ---------------------------------------------------------------------------
+namespace android {
+// ---------------------------------------------------------------------------
+
+class Surface;
+class NativeBuffer;
+
+// ---------------------------------------------------------------------------
+
+class FramebufferNativeWindow 
+    : public EGLNativeBase<
+        android_native_window_t, 
+        FramebufferNativeWindow, 
+        LightRefBase<FramebufferNativeWindow> >
+{
+public:
+    FramebufferNativeWindow(); 
+
+    framebuffer_device_t const * getDevice() const { return fbDev; } 
+
+    bool isUpdateOnDemand() const { return mUpdateOnDemand; }
+    status_t setUpdateRectangle(const Rect& updateRect);
+    
+private:
+    friend class LightRefBase<FramebufferNativeWindow>;    
+    ~FramebufferNativeWindow(); // this class cannot be overloaded
+    static int setSwapInterval(android_native_window_t* window, int interval);
+    static int dequeueBuffer(android_native_window_t* window, android_native_buffer_t** buffer);
+    static int lockBuffer(android_native_window_t* window, android_native_buffer_t* buffer);
+    static int queueBuffer(android_native_window_t* window, android_native_buffer_t* buffer);
+    
+    framebuffer_device_t* fbDev;
+    alloc_device_t* grDev;
+
+    sp<NativeBuffer> buffers[2];
+    sp<NativeBuffer> front;
+    
+    mutable Mutex mutex;
+    Condition mCondition;
+    int32_t mNumBuffers;
+    int32_t mNumFreeBuffers;
+    int32_t mBufferHead;
+    bool mUpdateOnDemand;
+};
+    
+// ---------------------------------------------------------------------------
+}; // namespace android
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_FRAMEBUFFER_NATIVE_WINDOW_H
+
diff --git a/include/ui/ICamera.h b/include/ui/ICamera.h
index 241fb63..1df7914 100644
--- a/include/ui/ICamera.h
+++ b/include/ui/ICamera.h
@@ -18,10 +18,10 @@
 #define ANDROID_HARDWARE_ICAMERA_H
 
 #include <utils/RefBase.h>
-#include <utils/IInterface.h>
-#include <utils/Parcel.h>
+#include <binder/IInterface.h>
+#include <binder/Parcel.h>
 #include <ui/ISurface.h>
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 #include <utils/String8.h>
 #include <ui/Camera.h>
 
diff --git a/include/ui/ICameraClient.h b/include/ui/ICameraClient.h
index 1001c71..236d0f6 100644
--- a/include/ui/ICameraClient.h
+++ b/include/ui/ICameraClient.h
@@ -18,9 +18,9 @@
 #define ANDROID_HARDWARE_ICAMERA_APP_H
 
 #include <utils/RefBase.h>
-#include <utils/IInterface.h>
-#include <utils/Parcel.h>
-#include <utils/IMemory.h>
+#include <binder/IInterface.h>
+#include <binder/Parcel.h>
+#include <binder/IMemory.h>
 #include <utils/Timers.h>
 
 namespace android {
diff --git a/include/ui/ICameraService.h b/include/ui/ICameraService.h
index c652c51..061681a 100644
--- a/include/ui/ICameraService.h
+++ b/include/ui/ICameraService.h
@@ -18,8 +18,8 @@
 #define ANDROID_HARDWARE_ICAMERASERVICE_H
 
 #include <utils/RefBase.h>
-#include <utils/IInterface.h>
-#include <utils/Parcel.h>
+#include <binder/IInterface.h>
+#include <binder/Parcel.h>
 
 #include <ui/ICameraClient.h>
 #include <ui/ICamera.h>
diff --git a/include/ui/IOverlay.h b/include/ui/IOverlay.h
index 699b1b0..af3add1 100644
--- a/include/ui/IOverlay.h
+++ b/include/ui/IOverlay.h
@@ -21,7 +21,7 @@
 #include <sys/types.h>
 
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
+#include <binder/IInterface.h>
 #include <utils/RefBase.h>
 #include <ui/PixelFormat.h>
 
diff --git a/include/ui/ISurface.h b/include/ui/ISurface.h
index 87b320f..adba45a 100644
--- a/include/ui/ISurface.h
+++ b/include/ui/ISurface.h
@@ -21,11 +21,12 @@
 #include <sys/types.h>
 
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
+#include <binder/IInterface.h>
 #include <utils/RefBase.h>
 #include <ui/PixelFormat.h>
 
 #include <hardware/hardware.h>
+#include <hardware/gralloc.h>
 
 namespace android {
 
@@ -33,6 +34,7 @@
 
 class IMemoryHeap;
 class OverlayRef;
+class SurfaceBuffer;
 
 class ISurface : public IInterface
 {
@@ -42,11 +44,13 @@
         UNREGISTER_BUFFERS,
         POST_BUFFER, // one-way transaction
         CREATE_OVERLAY,
+        GET_BUFFER,
     };
 
 public: 
     DECLARE_META_INTERFACE(Surface);
 
+    virtual sp<SurfaceBuffer> getBuffer() = 0; 
     
     class BufferHeap {
     public:
@@ -78,9 +82,7 @@
     };
     
     virtual status_t registerBuffers(const BufferHeap& buffers) = 0;
-
     virtual void postBuffer(ssize_t offset) = 0; // one-way
-
     virtual void unregisterBuffers() = 0;
     
     virtual sp<OverlayRef> createOverlay(
diff --git a/include/ui/ISurfaceComposer.h b/include/ui/ISurfaceComposer.h
index 5c64b22..1788265 100644
--- a/include/ui/ISurfaceComposer.h
+++ b/include/ui/ISurfaceComposer.h
@@ -22,7 +22,7 @@
 
 #include <utils/RefBase.h>
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
+#include <binder/IInterface.h>
 
 #include <ui/PixelFormat.h>
 #include <ui/ISurfaceFlingerClient.h>
@@ -32,7 +32,6 @@
 // ----------------------------------------------------------------------------
 
 class DisplayInfo;
-class IGPUCallback;
 
 class ISurfaceComposer : public IInterface
 {
@@ -63,7 +62,6 @@
         eTransparentRegionChanged   = 0x00000020,
         eVisibilityChanged          = 0x00000040,
         eFreezeTintChanged          = 0x00000080,
-        eDestroyed                  = 0x00000100
     };
 
     enum {
@@ -94,7 +92,7 @@
     virtual sp<ISurfaceFlingerClient> createConnection() = 0;
 
     /* retrieve the control block */
-    virtual sp<IMemory> getCblk() const = 0;
+    virtual sp<IMemoryHeap> getCblk() const = 0;
 
     /* open/close transactions. recquires ACCESS_SURFACE_FLINGER permission */
     virtual void openGlobalTransaction() = 0;
@@ -112,37 +110,12 @@
      */
     virtual void bootFinished() = 0;
 
-    /* get access to the GPU. Access is relinquished when releasing regs */
-    struct gpu_info_t {
-        struct gpu_region_t {
-            sp<IMemory> region;
-            size_t reserved;
-        };
-        sp<IMemory>             regs;
-        size_t                  count;
-        gpu_region_t            regions[2];
-    };
-    virtual status_t requestGPU(
-            const sp<IGPUCallback>& callback,
-            gpu_info_t* gpu) = 0;
-
-    /* take the gpu back from any apps using it. They'll get a
-     * EGL_CONTEXT_LOST error */
-    virtual status_t revokeGPU() = 0;
-
     /* Signal surfaceflinger that there might be some work to do
      * This is an ASYNCHRONOUS call.
      */
     virtual void signal() const = 0;
 };
 
-class IGPUCallback : public IInterface
-{
-public:
-    DECLARE_META_INTERFACE(GPUCallback);
-    virtual void gpuLost() = 0; //one-way
-};
-
 // ----------------------------------------------------------------------------
 
 class BnSurfaceComposer : public BnInterface<ISurfaceComposer>
@@ -159,8 +132,6 @@
         SET_ORIENTATION,
         FREEZE_DISPLAY,
         UNFREEZE_DISPLAY,
-        REQUEST_GPU,
-        REVOKE_GPU,
         SIGNAL
     };
 
@@ -170,15 +141,6 @@
                                     uint32_t flags = 0);
 };
 
-class BnGPUCallback : public BnInterface<IGPUCallback>
-{
-public:
-    virtual status_t    onTransact( uint32_t code,
-                                    const Parcel& data,
-                                    Parcel* reply,
-                                    uint32_t flags = 0);
-};
-
 // ----------------------------------------------------------------------------
 
 }; // namespace android
diff --git a/include/ui/ISurfaceFlingerClient.h b/include/ui/ISurfaceFlingerClient.h
index 5b9361d..932a70a 100644
--- a/include/ui/ISurfaceFlingerClient.h
+++ b/include/ui/ISurfaceFlingerClient.h
@@ -21,7 +21,7 @@
 #include <sys/types.h>
 
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
+#include <binder/IInterface.h>
 #include <utils/RefBase.h>
 
 #include <ui/ISurface.h>
@@ -52,12 +52,11 @@
     struct surface_data_t {
         int32_t             token;
         int32_t             identity;
-        sp<IMemoryHeap>     heap[2];
         status_t readFromParcel(const Parcel& parcel);
         status_t writeToParcel(Parcel* parcel) const;
     };
     
-    virtual void getControlBlocks(sp<IMemory>* ctl) const = 0;
+    virtual sp<IMemoryHeap> getControlBlock() const = 0;
 
     virtual sp<ISurface> createSurface( surface_data_t* data,
                                         int pid, 
diff --git a/include/ui/Overlay.h b/include/ui/Overlay.h
index 66514b4..acc9bea 100644
--- a/include/ui/Overlay.h
+++ b/include/ui/Overlay.h
@@ -21,7 +21,7 @@
 #include <sys/types.h>
 
 #include <utils/Errors.h>
-#include <utils/IInterface.h>
+#include <binder/IInterface.h>
 #include <utils/RefBase.h>
 #include <utils/threads.h>
 
@@ -82,6 +82,10 @@
     /* release the overlay buffer and post it */
     status_t queueBuffer(overlay_buffer_t buffer);
 
+    status_t setCrop(uint32_t x, uint32_t y, uint32_t w, uint32_t h) ;
+
+    status_t getCrop(uint32_t* x, uint32_t* y, uint32_t* w, uint32_t* h) ;
+
     /* returns the address of a given buffer if supported, NULL otherwise. */
     void* getBufferAddress(overlay_buffer_t buffer);
 
diff --git a/include/ui/PixelFormat.h b/include/ui/PixelFormat.h
index 14af823..6d87321 100644
--- a/include/ui/PixelFormat.h
+++ b/include/ui/PixelFormat.h
@@ -84,6 +84,13 @@
 
 struct PixelFormatInfo
 {
+    enum {
+        INDEX_ALPHA   = 0,
+        INDEX_RED     = 1,
+        INDEX_GREEN   = 2,
+        INDEX_BLUE    = 3
+    };
+    
     enum { // components
         ALPHA               = 1,
         RGB                 = 2,
@@ -95,20 +102,33 @@
         Y_CB_CR_I           = 8,
     };
 
+    struct szinfo {
+        uint8_t h;
+        uint8_t l;
+    };
+    
     inline PixelFormatInfo() : version(sizeof(PixelFormatInfo)) { }
     size_t getScanlineSize(unsigned int width) const;
+    size_t getSize(size_t ci) const { 
+        return (ci <= 3) ? (cinfo[ci].h - cinfo[ci].l) : 0;
+    }
     size_t      version;
     PixelFormat format;
     size_t      bytesPerPixel;
     size_t      bitsPerPixel;
-    uint8_t     h_alpha;
-    uint8_t     l_alpha;
-    uint8_t     h_red;
-    uint8_t     l_red;
-    uint8_t     h_green;
-    uint8_t     l_green;
-    uint8_t     h_blue;
-    uint8_t     l_blue;
+    union {
+        szinfo      cinfo[4];
+        struct {
+            uint8_t     h_alpha;
+            uint8_t     l_alpha;    
+            uint8_t     h_red;
+            uint8_t     l_red;
+            uint8_t     h_green;
+            uint8_t     l_green;
+            uint8_t     h_blue;
+            uint8_t     l_blue;
+        };
+    };
     uint8_t     components;
     uint8_t     reserved0[3];
     uint32_t    reserved1;
diff --git a/include/ui/Rect.h b/include/ui/Rect.h
index da72944..a213c09 100644
--- a/include/ui/Rect.h
+++ b/include/ui/Rect.h
@@ -30,6 +30,8 @@
     int right;
     int bottom;
 
+    typedef int value_type;
+
     // we don't provide copy-ctor and operator= on purpose
     // because we want the compiler generated versions
 
@@ -46,7 +48,11 @@
     }
 
     void makeInvalid();
-    
+
+    inline void clear() {
+        left = top = right = bottom = 0;
+    }
+
     // a valid rectangle has a non negative width and height
     inline bool isValid() const {
         return (width()>=0) && (height()>=0);
diff --git a/include/ui/Region.h b/include/ui/Region.h
index 7689673..2bcad5b 100644
--- a/include/ui/Region.h
+++ b/include/ui/Region.h
@@ -21,14 +21,12 @@
 #include <sys/types.h>
 
 #include <utils/Vector.h>
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 
 #include <ui/Rect.h>
 
 #include <hardware/copybit.h>
 
-#include <core/SkRegion.h>
-
 namespace android {
 // ---------------------------------------------------------------------------
 
@@ -40,7 +38,6 @@
 public:
                         Region();
                         Region(const Region& rhs);
-    explicit            Region(const SkRegion& rhs);
     explicit            Region(const Rect& rhs);
     explicit            Region(const Parcel& parcel);
     explicit            Region(const void* buffer);
@@ -48,65 +45,78 @@
                         
         Region& operator = (const Region& rhs);
 
-    inline  bool        isEmpty() const     { return mRegion.isEmpty(); }
-    inline  bool        isRect() const      { return mRegion.isRect(); }
+    inline  bool        isEmpty() const     { return mBounds.isEmpty();  }
+    inline  bool        isRect() const      { return mStorage.isEmpty(); }
 
-            Rect        bounds() const;
+    inline  Rect        getBounds() const   { return mBounds; }
+    inline  Rect        bounds() const      { return getBounds(); }
 
-            const SkRegion& toSkRegion() const;
-
+            // the region becomes its bounds
+            Region&     makeBoundsSelf();
+    
             void        clear();
             void        set(const Rect& r);
+            void        set(uint32_t w, uint32_t h);
         
             Region&     orSelf(const Rect& rhs);
             Region&     andSelf(const Rect& rhs);
+            Region&     subtractSelf(const Rect& rhs);
 
             // boolean operators, applied on this
             Region&     orSelf(const Region& rhs);
             Region&     andSelf(const Region& rhs);
             Region&     subtractSelf(const Region& rhs);
 
+            // boolean operators
+    const   Region      merge(const Rect& rhs) const;
+    const   Region      intersect(const Rect& rhs) const;
+    const   Region      subtract(const Rect& rhs) const;
+
+            // boolean operators
+    const   Region      merge(const Region& rhs) const;
+    const   Region      intersect(const Region& rhs) const;
+    const   Region      subtract(const Region& rhs) const;
+
             // these translate rhs first
             Region&     translateSelf(int dx, int dy);
             Region&     orSelf(const Region& rhs, int dx, int dy);
             Region&     andSelf(const Region& rhs, int dx, int dy);
             Region&     subtractSelf(const Region& rhs, int dx, int dy);
 
-            // boolean operators
-            Region      merge(const Region& rhs) const;
-            Region      intersect(const Region& rhs) const;
-            Region      subtract(const Region& rhs) const;
-
             // these translate rhs first
-            Region      translate(int dx, int dy) const;
-            Region      merge(const Region& rhs, int dx, int dy) const;
-            Region      intersect(const Region& rhs, int dx, int dy) const;
-            Region      subtract(const Region& rhs, int dx, int dy) const;
+    const   Region      translate(int dx, int dy) const;
+    const   Region      merge(const Region& rhs, int dx, int dy) const;
+    const   Region      intersect(const Region& rhs, int dx, int dy) const;
+    const   Region      subtract(const Region& rhs, int dx, int dy) const;
 
     // convenience operators overloads
-    inline  Region      operator | (const Region& rhs) const;
-    inline  Region      operator & (const Region& rhs) const;
-    inline  Region      operator - (const Region& rhs) const;
-    inline  Region      operator + (const Point& pt) const;
+    inline  const Region      operator | (const Region& rhs) const;
+    inline  const Region      operator & (const Region& rhs) const;
+    inline  const Region      operator - (const Region& rhs) const;
+    inline  const Region      operator + (const Point& pt) const;
 
     inline  Region&     operator |= (const Region& rhs);
     inline  Region&     operator &= (const Region& rhs);
     inline  Region&     operator -= (const Region& rhs);
     inline  Region&     operator += (const Point& pt);
 
-    class iterator {
-        SkRegion::Iterator  mIt;
-    public:
-        iterator(const Region& r);
-        inline operator bool () const { return !done(); }
-        int iterate(Rect* rect);
-    private:
-        inline bool done() const {
-            return const_cast<SkRegion::Iterator&>(mIt).done();
-        }
-    };
+    
+    /* various ways to access the rectangle list */
+    
+    typedef Rect const* const_iterator;
+    
+            const_iterator begin() const;
+            const_iterator end() const;
 
-            size_t      rects(Vector<Rect>& rectList) const;
+    /* no user serviceable parts here... */
+            
+            size_t      getRects(Vector<Rect>& rectList) const;
+            Rect const* getArray(size_t* count) const;
+
+            
+            // add a rectangle to the internal list. This rectangle must
+            // be sorted in Y and X and must not make the region invalid.
+            void        addRectUnchecked(int l, int t, int r, int b);
 
             // flatten/unflatten a region to/from a Parcel
             status_t    write(Parcel& parcel) const;
@@ -123,20 +133,46 @@
     void        dump(const char* what, uint32_t flags=0) const;
 
 private:
-    SkRegion    mRegion;
+    class rasterizer;
+    friend class rasterizer;
+    
+    Region& operationSelf(const Rect& r, int op);
+    Region& operationSelf(const Region& r, int op);
+    Region& operationSelf(const Region& r, int dx, int dy, int op);
+    const Region operation(const Rect& rhs, int op) const;
+    const Region operation(const Region& rhs, int op) const;
+    const Region operation(const Region& rhs, int dx, int dy, int op) const;
+
+    static void boolean_operation(int op, Region& dst,
+            const Region& lhs, const Region& rhs, int dx, int dy);
+    static void boolean_operation(int op, Region& dst,
+            const Region& lhs, const Rect& rhs, int dx, int dy);
+
+    static void boolean_operation(int op, Region& dst,
+            const Region& lhs, const Region& rhs);
+    static void boolean_operation(int op, Region& dst,
+            const Region& lhs, const Rect& rhs);
+
+    static void translate(Region& reg, int dx, int dy);
+    static void translate(Region& dst, const Region& reg, int dx, int dy);
+
+    static bool validate(const Region& reg, const char* name);
+    
+    Rect            mBounds;
+    Vector<Rect>    mStorage;
 };
 
 
-Region Region::operator | (const Region& rhs) const {
+const Region Region::operator | (const Region& rhs) const {
     return merge(rhs);
 }
-Region Region::operator & (const Region& rhs) const {
+const Region Region::operator & (const Region& rhs) const {
     return intersect(rhs);
 }
-Region Region::operator - (const Region& rhs) const {
+const Region Region::operator - (const Region& rhs) const {
     return subtract(rhs);
 }
-Region Region::operator + (const Point& pt) const {
+const Region Region::operator + (const Point& pt) const {
     return translate(pt.x, pt.y);
 }
 
@@ -157,16 +193,23 @@
 // ---------------------------------------------------------------------------
 
 struct region_iterator : public copybit_region_t {
-    region_iterator(const Region& region) : i(region) {
+    region_iterator(const Region& region)
+        : b(region.begin()), e(region.end()) {
         this->next = iterate;
     }
 private:
     static int iterate(copybit_region_t const * self, copybit_rect_t* rect) {
-        return static_cast<const region_iterator*>(self)
-        ->i.iterate(reinterpret_cast<Rect*>(rect));
+        region_iterator const* me = static_cast<region_iterator const*>(self);
+        if (me->b != me->e) {
+            *reinterpret_cast<Rect*>(rect) = *me->b++;
+            return 1;
+        }
+        return 0;
     }
-    mutable Region::iterator i;
+    mutable Region::const_iterator b;
+    Region::const_iterator const e;
 };
+
 // ---------------------------------------------------------------------------
 }; // namespace android
 
diff --git a/include/ui/Surface.h b/include/ui/Surface.h
index 33953a9..8c4f63d 100644
--- a/include/ui/Surface.h
+++ b/include/ui/Surface.h
@@ -28,48 +28,40 @@
 #include <ui/Region.h>
 #include <ui/ISurfaceFlingerClient.h>
 
+#include <ui/egl/android_natives.h>
+
 namespace android {
 
 // ---------------------------------------------------------------------------
 
+class BufferMapper;
 class Rect;
+class Surface;
 class SurfaceComposerClient;
+struct per_client_cblk_t;
+struct layer_cblk_t;
 
-class Surface : public RefBase
+// ---------------------------------------------------------------------------
+
+class SurfaceControl : public RefBase
 {
-
 public:
-    struct SurfaceInfo {
-        uint32_t    w;
-        uint32_t    h;
-        uint32_t    bpr;
-        PixelFormat format;
-        void*       bits;
-        void*       base;
-        uint32_t    reserved[2];
-    };
-
-    bool        isValid() const { return this && mToken>=0 && mClient!=0; }
+    static bool isValid(const sp<SurfaceControl>& surface) {
+        return (surface != 0) && surface->isValid();
+    }
+    bool isValid() {
+        return mToken>=0 && mClient!=0;
+    }
+    static bool isSameSurface(
+            const sp<SurfaceControl>& lhs, const sp<SurfaceControl>& rhs);
+        
     SurfaceID   ID() const      { return mToken; }
-
-    status_t    lock(SurfaceInfo* info, bool blocking = true);
-    status_t    lock(SurfaceInfo* info, Region* dirty, bool blocking = true);
-    status_t    unlockAndPost();
-    status_t    unlock();
-
-    void*       heapBase(int i) const;
     uint32_t    getFlags() const { return mFlags; }
+    uint32_t    getIdentity() const { return mIdentity; }
 
-    // setSwapRectangle() is mainly used by EGL
-    void        setSwapRectangle(const Rect& r);
-    const Rect& swapRectangle() const;
-    status_t    nextBuffer(SurfaceInfo* info);
-
-    sp<Surface>         dup() const;
-    static sp<Surface>  readFromParcel(Parcel* parcel);
-    static status_t     writeToParcel(const sp<Surface>& surface, Parcel* parcel);
-    static bool         isSameSurface(const sp<Surface>& lhs, const sp<Surface>& rhs);
-
+    // release surface data from java
+    void        clear();
+    
     status_t    setLayer(int32_t layer);
     status_t    setPosition(int32_t x, int32_t y);
     status_t    setSize(uint32_t w, uint32_t h);
@@ -83,8 +75,17 @@
     status_t    setMatrix(float dsdx, float dtdx, float dsdy, float dtdy);
     status_t    setFreezeTint(uint32_t tint);
 
-    uint32_t    getIdentity() const { return mIdentity; }
+    static status_t writeSurfaceToParcel(
+            const sp<SurfaceControl>& control, Parcel* parcel);
+
+    sp<Surface> getSurface() const;
+
 private:
+    // can't be copied
+    SurfaceControl& operator = (SurfaceControl& rhs);
+    SurfaceControl(const SurfaceControl& rhs);
+
+    
     friend class SurfaceComposerClient;
 
     // camera and camcorder need access to the ISurface binder interface for preview
@@ -92,43 +93,130 @@
     friend class MediaRecorder;
     // mediaplayer needs access to ISurface for display
     friend class MediaPlayer;
+    // for testing
+    friend class Test;
+    const sp<ISurface>& getISurface() const { return mSurface; }
+    
+
+    friend class Surface;
+
+    SurfaceControl(
+            const sp<SurfaceComposerClient>& client,
+            const sp<ISurface>& surface,
+            const ISurfaceFlingerClient::surface_data_t& data,
+            uint32_t w, uint32_t h, PixelFormat format, uint32_t flags);
+
+    ~SurfaceControl();
+
+    status_t validate(per_client_cblk_t const* cblk) const;
+    void destroy();
+    
+    sp<SurfaceComposerClient>   mClient;
+    sp<ISurface>                mSurface;
+    SurfaceID                   mToken;
+    uint32_t                    mIdentity;
+    PixelFormat                 mFormat;
+    uint32_t                    mFlags;
+    mutable Mutex               mLock;
+    
+    mutable sp<Surface>         mSurfaceData;
+};
+    
+// ---------------------------------------------------------------------------
+
+class Surface 
+    : public EGLNativeBase<android_native_window_t, Surface, RefBase>
+{
+public:
+    struct SurfaceInfo {
+        uint32_t    w;
+        uint32_t    h;
+        uint32_t    s;
+        uint32_t    usage;
+        PixelFormat format;
+        void*       bits;
+        uint32_t    reserved[2];
+    };
+
+    Surface(const Parcel& data);
+
+    static bool isValid(const sp<Surface>& surface) {
+        return (surface != 0) && surface->isValid();
+    }
+    bool isValid() {
+        return mToken>=0 && mClient!=0;
+    }
+    static bool isSameSurface(
+            const sp<Surface>& lhs, const sp<Surface>& rhs);
+    SurfaceID   ID() const      { return mToken; }
+    uint32_t    getFlags() const { return mFlags; }
+    uint32_t    getIdentity() const { return mIdentity; }
+
+
+    status_t    lock(SurfaceInfo* info, bool blocking = true);
+    status_t    lock(SurfaceInfo* info, Region* dirty, bool blocking = true);
+    status_t    unlockAndPost();
+
+    // setSwapRectangle() is intended to be used by GL ES clients
+    void        setSwapRectangle(const Rect& r);
+
+private:
+    // can't be copied
+    Surface& operator = (Surface& rhs);
+    Surface(const Surface& rhs);
+
+    Surface(const sp<SurfaceControl>& control);
+    void init();
+     ~Surface();
+  
+    friend class SurfaceComposerClient;
+    friend class SurfaceControl;
+
+    // camera and camcorder need access to the ISurface binder interface for preview
+    friend class Camera;
+    friend class MediaRecorder;
+    // mediaplayer needs access to ISurface for display
+    friend class MediaPlayer;
     friend class Test;
     const sp<ISurface>& getISurface() const { return mSurface; }
 
-    // can't be copied
-    Surface& operator = (Surface& rhs);
-    Surface(const Surface& rhs);
+    status_t getBufferLocked(int index);
+   
+           status_t validate(per_client_cblk_t const* cblk) const;
+    static void _send_dirty_region(layer_cblk_t* lcblk, const Region& dirty);
 
-    Surface(const sp<SurfaceComposerClient>& client,
-            const sp<ISurface>& surface,
-            const ISurfaceFlingerClient::surface_data_t& data,
-            uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
-            bool owner = true);
+    inline const BufferMapper& getBufferMapper() const { return mBufferMapper; }
+    inline BufferMapper& getBufferMapper() { return mBufferMapper; }
+    
+    static int setSwapInterval(android_native_window_t* window, int interval);
+    static int dequeueBuffer(android_native_window_t* window, android_native_buffer_t** buffer);
+    static int lockBuffer(android_native_window_t* window, android_native_buffer_t* buffer);
+    static int queueBuffer(android_native_window_t* window, android_native_buffer_t* buffer);
 
-    Surface(Surface const* rhs);
+    int dequeueBuffer(android_native_buffer_t** buffer);
+    int lockBuffer(android_native_buffer_t* buffer);
+    int queueBuffer(android_native_buffer_t* buffer);
 
-    ~Surface();
+    status_t dequeueBuffer(sp<SurfaceBuffer>* buffer);
+    status_t lockBuffer(const sp<SurfaceBuffer>& buffer);
+    status_t queueBuffer(const sp<SurfaceBuffer>& buffer);
 
-    Region dirtyRegion() const;
-    void setDirtyRegion(const Region& region) const;
-
-    // this locks protects calls to lockSurface() / unlockSurface()
-    // and is called by SurfaceComposerClient.
-    Mutex& getLock() const { return mSurfaceLock; }
-
+    
+    alloc_device_t*             mAllocDevice;
     sp<SurfaceComposerClient>   mClient;
     sp<ISurface>                mSurface;
-    sp<IMemoryHeap>             mHeap[2];
+    sp<SurfaceBuffer>           mBuffers[2];
+    sp<SurfaceBuffer>           mLockedBuffer;
     SurfaceID                   mToken;
     uint32_t                    mIdentity;
     PixelFormat                 mFormat;
     uint32_t                    mFlags;
-    const bool                  mOwner;
-    mutable void*               mSurfaceHeapBase[2];
     mutable Region              mDirtyRegion;
-    mutable Rect                mSwapRectangle;
+    mutable Region              mOldDirtyRegion;
     mutable uint8_t             mBackbufferIndex;
     mutable Mutex               mSurfaceLock;
+    Rect                        mSwapRectangle;
+    BufferMapper&               mBufferMapper;
 };
 
 }; // namespace android
diff --git a/include/ui/SurfaceComposerClient.h b/include/ui/SurfaceComposerClient.h
index 76a3b55..286f885 100644
--- a/include/ui/SurfaceComposerClient.h
+++ b/include/ui/SurfaceComposerClient.h
@@ -62,7 +62,7 @@
     // surface creation / destruction
 
     //! Create a surface
-    sp<Surface>   createSurface(
+    sp<SurfaceControl> createSurface(
             int pid,            //!< pid of the process the surfacec is for
             DisplayID display,  //!< Display to create this surface on
             uint32_t w,         //!< width in pixel
@@ -111,51 +111,35 @@
 
 private:
     friend class Surface;
+    friend class SurfaceControl;
     
     SurfaceComposerClient(const sp<ISurfaceComposer>& sm, 
             const sp<IBinder>& conn);
 
-    status_t    hide(Surface* surface);
-    status_t    show(Surface* surface, int32_t layer = -1);
-    status_t    freeze(Surface* surface);
-    status_t    unfreeze(Surface* surface);
-    status_t    setFlags(Surface* surface, uint32_t flags, uint32_t mask);
-    status_t    setTransparentRegionHint(Surface* surface, const Region& transparent);
-    status_t    setLayer(Surface* surface, int32_t layer);
-    status_t    setAlpha(Surface* surface, float alpha=1.0f);
-    status_t    setFreezeTint(Surface* surface, uint32_t tint);
-    status_t    setMatrix(Surface* surface, float dsdx, float dtdx, float dsdy, float dtdy);
-    status_t    setPosition(Surface* surface, int32_t x, int32_t y);
-    status_t    setSize(Surface* surface, uint32_t w, uint32_t h);
+    status_t    hide(SurfaceID id);
+    status_t    show(SurfaceID id, int32_t layer = -1);
+    status_t    freeze(SurfaceID id);
+    status_t    unfreeze(SurfaceID id);
+    status_t    setFlags(SurfaceID id, uint32_t flags, uint32_t mask);
+    status_t    setTransparentRegionHint(SurfaceID id, const Region& transparent);
+    status_t    setLayer(SurfaceID id, int32_t layer);
+    status_t    setAlpha(SurfaceID id, float alpha=1.0f);
+    status_t    setFreezeTint(SurfaceID id, uint32_t tint);
+    status_t    setMatrix(SurfaceID id, float dsdx, float dtdx, float dsdy, float dtdy);
+    status_t    setPosition(SurfaceID id, int32_t x, int32_t y);
+    status_t    setSize(SurfaceID id, uint32_t w, uint32_t h);
     
-    //! Unlock the surface, and specify the dirty region if any
-    status_t    unlockAndPostSurface(Surface* surface);
-    status_t    unlockSurface(Surface* surface);
-
-    status_t    lockSurface(Surface* surface,
-                            Surface::SurfaceInfo* info,
-                            Region* dirty,
-                            bool blocking = true);
-
-    status_t    nextBuffer(Surface* surface,
-                            Surface::SurfaceInfo* info);
+    void        signalServer();
 
     status_t    destroySurface(SurfaceID sid);
 
     void        _init(const sp<ISurfaceComposer>& sm,
                     const sp<ISurfaceFlingerClient>& conn);
-    void        _signal_server();
-    static void _send_dirty_region(layer_cblk_t* lcblk, const Region& dirty);
 
-    inline layer_state_t*   _get_state_l(const sp<Surface>& surface);
-    layer_state_t*          _lockLayerState(const sp<Surface>& surface);
+    inline layer_state_t*   _get_state_l(SurfaceID id);
+    layer_state_t*          _lockLayerState(SurfaceID id);
     inline void             _unlockLayerState();
 
-    status_t validateSurface(
-            per_client_cblk_t const* cblk, Surface const * surface);
-
-    void pinHeap(const sp<IMemoryHeap>& heap);
-
     mutable     Mutex                               mLock;
                 layer_state_t*                      mPrebuiltLayerState;
                 SortedVector<layer_state_t>         mStates;
@@ -165,11 +149,8 @@
                 // after assignment
                 status_t                    mStatus;
                 per_client_cblk_t*          mControl;
-                sp<IMemory>                 mControlMemory;
+                sp<IMemoryHeap>             mControlMemory;
                 sp<ISurfaceFlingerClient>   mClient;
-                sp<IMemoryHeap>             mSurfaceHeap;
-                uint8_t*                    mSurfaceHeapBase;
-                void*                       mGL;
                 SurfaceFlingerSynchro*      mSignalServer;
 };
 
diff --git a/include/ui/egl/android_natives.h b/include/ui/egl/android_natives.h
new file mode 100644
index 0000000..0398ea7
--- /dev/null
+++ b/include/ui/egl/android_natives.h
@@ -0,0 +1,210 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_ANDROID_NATIVES_H
+#define ANDROID_ANDROID_NATIVES_H
+
+#include <sys/types.h>
+#include <string.h>
+
+#include <hardware/gralloc.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*****************************************************************************/
+
+#define ANDROID_NATIVE_MAKE_CONSTANT(a,b,c,d) \
+    (((unsigned)(a)<<24)|((unsigned)(b)<<16)|((unsigned)(c)<<8)|(unsigned)(d))
+
+#define ANDROID_NATIVE_WINDOW_MAGIC \
+    ANDROID_NATIVE_MAKE_CONSTANT('_','w','n','d')
+
+#define ANDROID_NATIVE_BUFFER_MAGIC \
+    ANDROID_NATIVE_MAKE_CONSTANT('_','b','f','r')
+
+// ---------------------------------------------------------------------------
+
+struct android_native_buffer_t;
+
+// ---------------------------------------------------------------------------
+
+struct android_native_base_t
+{
+    /* a magic value defined by the actual EGL native type */
+    int magic;
+    
+    /* the sizeof() of the actual EGL native type */
+    int version;
+
+    void* reserved[4];
+
+    /* reference-counting interface */
+    void (*incRef)(struct android_native_base_t* base);
+    void (*decRef)(struct android_native_base_t* base);
+};
+
+// ---------------------------------------------------------------------------
+
+struct android_native_window_t 
+{
+#ifdef __cplusplus
+    android_native_window_t()
+        : flags(0), minSwapInterval(0), maxSwapInterval(0), xdpi(0), ydpi(0)
+    {
+        common.magic = ANDROID_NATIVE_WINDOW_MAGIC;
+        common.version = sizeof(android_native_window_t);
+        memset(common.reserved, 0, sizeof(common.reserved));
+    }
+#endif
+    
+    struct android_native_base_t common;
+
+    /* flags describing some attributes of this surface or its updater */
+    const uint32_t flags;
+    
+    /* min swap interval supported by this updated */
+    const int   minSwapInterval;
+
+    /* max swap interval supported by this updated */
+    const int   maxSwapInterval;
+
+    /* horizontal and vertical resolution in DPI */
+    const float xdpi;
+    const float ydpi;
+
+    /* Some storage reserved for the OEM's driver. */
+    intptr_t    oem[4];
+        
+
+    /*
+     * Set the swap interval for this surface.
+     * 
+     * Returns 0 on success or -errno on error.
+     */
+    int     (*setSwapInterval)(struct android_native_window_t* window,
+                int interval);
+    
+    /*
+     * hook called by EGL to acquire a buffer. After this call, the buffer
+     * is not locked, so its content cannot be modified.
+     * this call may block if no buffers are available.
+     * 
+     * Returns 0 on success or -errno on error.
+     */
+    int     (*dequeueBuffer)(struct android_native_window_t* window, 
+                struct android_native_buffer_t** buffer);
+
+    /*
+     * hook called by EGL to lock a buffer. This MUST be called before modifying
+     * the content of a buffer. The buffer must have been acquired with 
+     * dequeueBuffer first.
+     * 
+     * Returns 0 on success or -errno on error.
+     */
+    int     (*lockBuffer)(struct android_native_window_t* window,
+                struct android_native_buffer_t* buffer);
+   /*
+    * hook called by EGL when modifications to the render buffer are done. 
+    * This unlocks and post the buffer.
+    * 
+    * Buffers MUST be queued in the same order than they were dequeued.
+    * 
+    * Returns 0 on success or -errno on error.
+    */
+    int     (*queueBuffer)(struct android_native_window_t* window,
+                struct android_native_buffer_t* buffer);
+
+    
+    void* reserved_proc[5];
+};
+
+// ---------------------------------------------------------------------------
+
+/* FIXME: this is legacy for pixmaps */
+struct egl_native_pixmap_t
+{
+    int32_t     version;    /* must be 32 */
+    int32_t     width;
+    int32_t     height;
+    int32_t     stride;
+    uint8_t*    data;
+    uint8_t     format;
+    uint8_t     rfu[3];
+    union {
+        uint32_t    compressedFormat;
+        int32_t     vstride;
+    };
+    int32_t     reserved;
+};
+
+/*****************************************************************************/
+
+#ifdef __cplusplus
+}
+#endif
+
+
+/*****************************************************************************/
+
+#ifdef __cplusplus
+
+#include <utils/RefBase.h>
+
+namespace android {
+
+/*
+ * This helper class turns an EGL android_native_xxx type into a C++
+ * reference-counted object; with proper type conversions.
+ */
+template <typename NATIVE_TYPE, typename TYPE, typename REF>
+class EGLNativeBase : public NATIVE_TYPE, public REF
+{
+protected:
+    typedef EGLNativeBase<NATIVE_TYPE, TYPE, REF> BASE;
+    EGLNativeBase() : NATIVE_TYPE(), REF() {
+        NATIVE_TYPE::common.incRef = incRef;
+        NATIVE_TYPE::common.decRef = decRef;
+    }
+    static inline TYPE* getSelf(NATIVE_TYPE* self) {
+        return static_cast<TYPE*>(self);
+    }
+    static inline TYPE const* getSelf(NATIVE_TYPE const* self) {
+        return static_cast<TYPE const *>(self);
+    }
+    static inline TYPE* getSelf(android_native_base_t* base) {
+        return getSelf(reinterpret_cast<NATIVE_TYPE*>(base));
+    }
+    static inline TYPE const * getSelf(android_native_base_t const* base) {
+        return getSelf(reinterpret_cast<NATIVE_TYPE const*>(base));
+    }
+    static void incRef(android_native_base_t* base) {
+        EGLNativeBase* self = getSelf(base);
+        self->incStrong(self);
+    }
+    static void decRef(android_native_base_t* base) {
+        EGLNativeBase* self = getSelf(base);
+        self->decStrong(self);
+    }
+};
+
+} // namespace android
+#endif // __cplusplus
+
+/*****************************************************************************/
+
+#endif /* ANDROID_ANDROID_NATIVES_H */
diff --git a/include/utils.h b/include/utils.h
deleted file mode 100644
index 30648b1..0000000
--- a/include/utils.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Handy utility functions and portability code.  This file includes all
-// of the generally-useful headers in the "utils" directory.
-//
-#ifndef _LIBS_UTILS_H
-#define _LIBS_UTILS_H
-
-#include <utils/ported.h>
-#include <utils/Log.h>
-#include <utils/threads.h>
-#include <utils/Timers.h>
-#include <utils/List.h>
-#include <utils/string_array.h>
-#include <utils/misc.h>
-#include <utils/Errors.h>
-
-#endif // _LIBS_UTILS_H
diff --git a/include/utils/Debug.h b/include/utils/Debug.h
index a662b9c..21d04bd 100644
--- a/include/utils/Debug.h
+++ b/include/utils/Debug.h
@@ -14,10 +14,6 @@
  * limitations under the License.
  */
 
-//
-// Debugging tools.  These should be able to be stripped
-// in release builds.
-//
 #ifndef ANDROID_DEBUG_H
 #define ANDROID_DEBUG_H
 
@@ -25,9 +21,30 @@
 #include <sys/types.h>
 
 namespace android {
+// ---------------------------------------------------------------------------
 
+#ifdef __cplusplus
 template<bool> struct CompileTimeAssert;
 template<> struct CompileTimeAssert<true> {};
+#define COMPILE_TIME_ASSERT(_exp) \
+    template class CompileTimeAssert< (_exp) >;
+#endif
+
+// ---------------------------------------------------------------------------
+
+#ifdef __cplusplus
+template<bool C, typename LSH, typename RHS> struct CompileTimeIfElse;
+template<typename LHS, typename RHS> 
+struct CompileTimeIfElse<true,  LHS, RHS> { typedef LHS TYPE; };
+template<typename LHS, typename RHS> 
+struct CompileTimeIfElse<false, LHS, RHS> { typedef RHS TYPE; };
+#endif
+
+// ---------------------------------------------------------------------------
+
+#ifdef __cplusplus
+extern "C" {
+#endif
 
 const char* stringForIndent(int32_t indentLevel);
 
@@ -35,11 +52,17 @@
 
 void printTypeCode(uint32_t typeCode,
     debugPrintFunc func = 0, void* cookie = 0);
+
 void printHexData(int32_t indent, const void *buf, size_t length,
     size_t bytesPerLine=16, int32_t singleLineBytesCutoff=16,
     size_t alignment=0, bool cArrayStyle=false,
     debugPrintFunc func = 0, void* cookie = 0);
 
+#ifdef __cplusplus
+}
+#endif
+
+// ---------------------------------------------------------------------------
 }; // namespace android
 
 #endif // ANDROID_DEBUG_H
diff --git a/include/utils/KeyedVector.h b/include/utils/KeyedVector.h
index f4513ee..6bcdea4 100644
--- a/include/utils/KeyedVector.h
+++ b/include/utils/KeyedVector.h
@@ -164,7 +164,7 @@
 template<typename KEY, typename VALUE> inline
 ssize_t KeyedVector<KEY,VALUE>::replaceValueAt(size_t index, const VALUE& item) {
     if (index<size()) {
-        mVector.editValueAt(index).value = item;
+        mVector.editItemAt(index).value = item;
         return index;
     }
     return BAD_INDEX;
diff --git a/include/utils/List.h b/include/utils/List.h
index 1a6be9a..403cd7f 100644
--- a/include/utils/List.h
+++ b/include/utils/List.h
@@ -22,147 +22,200 @@
 // construction, so if the compiler's auto-generated versions won't work for
 // you, define your own.
 //
-// The only class you want to use from here is "List".  Do not use classes
-// starting with "_" directly.
+// The only class you want to use from here is "List".
 //
 #ifndef _LIBS_UTILS_LIST_H
 #define _LIBS_UTILS_LIST_H
 
+#include <stddef.h>
+#include <stdint.h>
+
 namespace android {
 
 /*
- * One element in the list.
- */
-template<class T> class _ListNode {
-public:
-    typedef _ListNode<T> _Node;
-
-    _ListNode(const T& val) : mVal(val) {}
-    ~_ListNode(void) {}
-
-    T& getRef(void) { return mVal; }
-    void setVal(const T& val) { mVal = val; }
-
-    _Node* getPrev(void) const { return mpPrev; }
-    void setPrev(_Node* ptr) { mpPrev = ptr; }
-    _Node* getNext(void) const { return mpNext; }
-    void setNext(_Node* ptr) { mpNext = ptr; }
-
-private:
-    T           mVal;
-    _Node*      mpPrev;
-    _Node*      mpNext;
-};
-
-/*
- * Iterator for walking through the list.
- */
-template<class T, class Tref> class _ListIterator {
-public:
-    typedef _ListIterator<T,Tref> _Iter;
-    typedef _ListNode<T> _Node;
-
-    _ListIterator(void) {}
-    _ListIterator(_Node* ptr) : mpNode(ptr) {}
-    ~_ListIterator(void) {}
-
-    /*
-     * Dereference operator.  Used to get at the juicy insides.
-     */
-    Tref operator*() const { return mpNode->getRef(); }
-
-    /*
-     * Iterator comparison.
-     */
-    bool operator==(const _Iter& right) const { return mpNode == right.mpNode; }
-    bool operator!=(const _Iter& right) const { return mpNode != right.mpNode; }
-
-    /*
-     * Incr/decr, used to move through the list.
-     */
-    _Iter& operator++(void) {        // pre-increment
-        mpNode = mpNode->getNext();
-        return *this;
-    }
-    _Iter operator++(int) {          // post-increment
-        _Iter tmp = *this;
-        ++*this;
-        return tmp;
-    }
-    _Iter& operator--(void) {        // pre-increment
-        mpNode = mpNode->getPrev();
-        return *this;
-    }
-    _Iter operator--(int) {          // post-increment
-        _Iter tmp = *this;
-        --*this;
-        return tmp;
-    }
-
-    _Node* getNode(void) const { return mpNode; }
-
-private:
-    _Node*      mpNode;
-};
-
-
-/*
  * Doubly-linked list.  Instantiate with "List<MyClass> myList".
  *
  * Objects added to the list are copied using the assignment operator,
  * so this must be defined.
  */
-template<class T> class List {
-public:
-    typedef _ListNode<T> _Node;
+template<typename T> 
+class List 
+{
+protected:
+    /*
+     * One element in the list.
+     */
+    class _Node {
+    public:
+        explicit _Node(const T& val) : mVal(val) {}
+        ~_Node() {}
+        inline T& getRef() { return mVal; }
+        inline const T& getRef() const { return mVal; }
+        inline _Node* getPrev() const { return mpPrev; }
+        inline _Node* getNext() const { return mpNext; }
+        inline void setVal(const T& val) { mVal = val; }
+        inline void setPrev(_Node* ptr) { mpPrev = ptr; }
+        inline void setNext(_Node* ptr) { mpNext = ptr; }
+    private:
+        friend class List;
+        friend class _ListIterator;
+        T           mVal;
+        _Node*      mpPrev;
+        _Node*      mpNext;
+    };
 
-    List(void) {
+    /*
+     * Iterator for walking through the list.
+     */
+    
+    template <typename TYPE>
+    struct CONST_ITERATOR {
+        typedef _Node const * NodePtr;
+        typedef const TYPE Type;
+    };
+    
+    template <typename TYPE>
+    struct NON_CONST_ITERATOR {
+        typedef _Node* NodePtr;
+        typedef TYPE Type;
+    };
+    
+    template<
+        typename U,
+        template <class> class Constness
+    > 
+    class _ListIterator {
+        typedef _ListIterator<U, Constness>     _Iter;
+        typedef typename Constness<U>::NodePtr  _NodePtr;
+        typedef typename Constness<U>::Type     _Type;
+
+        explicit _ListIterator(_NodePtr ptr) : mpNode(ptr) {}
+
+    public:
+        _ListIterator() {}
+        _ListIterator(const _Iter& rhs) : mpNode(rhs.mpNode) {}
+        ~_ListIterator() {}
+        
+        // this will handle conversions from iterator to const_iterator
+        // (and also all convertible iterators)
+        // Here, in this implementation, the iterators can be converted
+        // if the nodes can be converted
+        template<typename V> explicit 
+        _ListIterator(const V& rhs) : mpNode(rhs.mpNode) {}
+        
+
+        /*
+         * Dereference operator.  Used to get at the juicy insides.
+         */
+        _Type& operator*() const { return mpNode->getRef(); }
+        _Type* operator->() const { return &(mpNode->getRef()); }
+
+        /*
+         * Iterator comparison.
+         */
+        inline bool operator==(const _Iter& right) const { 
+            return mpNode == right.mpNode; }
+        
+        inline bool operator!=(const _Iter& right) const { 
+            return mpNode != right.mpNode; }
+
+        /*
+         * handle comparisons between iterator and const_iterator
+         */
+        template<typename OTHER>
+        inline bool operator==(const OTHER& right) const { 
+            return mpNode == right.mpNode; }
+        
+        template<typename OTHER>
+        inline bool operator!=(const OTHER& right) const { 
+            return mpNode != right.mpNode; }
+
+        /*
+         * Incr/decr, used to move through the list.
+         */
+        inline _Iter& operator++() {     // pre-increment
+            mpNode = mpNode->getNext();
+            return *this;
+        }
+        const _Iter operator++(int) {    // post-increment
+            _Iter tmp(*this);
+            mpNode = mpNode->getNext();
+            return tmp;
+        }
+        inline _Iter& operator--() {     // pre-increment
+            mpNode = mpNode->getPrev();
+            return *this;
+        }
+        const _Iter operator--(int) {   // post-increment
+            _Iter tmp(*this);
+            mpNode = mpNode->getPrev();
+            return tmp;
+        }
+
+        inline _NodePtr getNode() const { return mpNode; }
+
+        _NodePtr mpNode;    /* should be private, but older gcc fails */
+    private:
+        friend class List;
+    };
+
+public:
+    List() {
         prep();
     }
     List(const List<T>& src) {      // copy-constructor
         prep();
         insert(begin(), src.begin(), src.end());
     }
-    virtual ~List(void) {
+    virtual ~List() {
         clear();
         delete[] (unsigned char*) mpMiddle;
     }
 
-    typedef _ListIterator<T,T&> iterator;
-    typedef _ListIterator<T, const T&> const_iterator;
+    typedef _ListIterator<T, NON_CONST_ITERATOR> iterator;
+    typedef _ListIterator<T, CONST_ITERATOR> const_iterator;
 
     List<T>& operator=(const List<T>& right);
 
     /* returns true if the list is empty */
-    bool empty(void) const { return mpMiddle->getNext() == mpMiddle; }
+    inline bool empty() const { return mpMiddle->getNext() == mpMiddle; }
 
     /* return #of elements in list */
-    unsigned int size(void) const {
-        return distance(begin(), end());
+    size_t size() const {
+        return size_t(distance(begin(), end()));
     }
 
     /*
      * Return the first element or one past the last element.  The
-     * _ListNode* we're returning is converted to an "iterator" by a
+     * _Node* we're returning is converted to an "iterator" by a
      * constructor in _ListIterator.
      */
-    iterator begin()                { return mpMiddle->getNext(); }
-    const_iterator begin() const    { return mpMiddle->getNext(); }
-    iterator end()                  { return mpMiddle; }
-    const_iterator end() const      { return mpMiddle; }
+    inline iterator begin() { 
+        return iterator(mpMiddle->getNext()); 
+    }
+    inline const_iterator begin() const { 
+        return const_iterator(const_cast<_Node const*>(mpMiddle->getNext())); 
+    }
+    inline iterator end() { 
+        return iterator(mpMiddle); 
+    }
+    inline const_iterator end() const { 
+        return const_iterator(const_cast<_Node const*>(mpMiddle)); 
+    }
 
     /* add the object to the head or tail of the list */
     void push_front(const T& val) { insert(begin(), val); }
     void push_back(const T& val) { insert(end(), val); }
 
     /* insert before the current node; returns iterator at new node */
-    iterator insert(iterator posn, const T& val) {
+    iterator insert(iterator posn, const T& val) 
+    {
         _Node* newNode = new _Node(val);        // alloc & copy-construct
         newNode->setNext(posn.getNode());
         newNode->setPrev(posn.getNode()->getPrev());
         posn.getNode()->getPrev()->setNext(newNode);
         posn.getNode()->setPrev(newNode);
-        return newNode;
+        return iterator(newNode);
     }
 
     /* insert a range of elements before the current node */
@@ -178,18 +231,18 @@
         pPrev->setNext(pNext);
         pNext->setPrev(pPrev);
         delete posn.getNode();
-        return pNext;
+        return iterator(pNext);
     }
 
     /* remove a range of elements */
     iterator erase(iterator first, iterator last) {
         while (first != last)
             erase(first++);     // don't erase than incr later!
-        return last;
+        return iterator(last);
     }
 
     /* remove all contents of the list */
-    void clear(void) {
+    void clear() {
         _Node* pCurrent = mpMiddle->getNext();
         _Node* pNext;
 
@@ -207,21 +260,20 @@
      * will be equal to "last".  The iterators must refer to the same
      * list.
      *
-     * (This is actually a generic iterator function.  It should be part
-     * of some other class, possibly an iterator base class.  It needs to
-     * know the difference between a list, which has to march through,
-     * and a vector, which can just do pointer math.)
+     * FIXME: This is actually a generic iterator function. It should be a 
+     * template function at the top-level with specializations for things like
+     * vector<>, which can just do pointer math). Here we limit it to
+     * _ListIterator of the same type but different constness.
      */
-    unsigned int distance(iterator first, iterator last) {
-        unsigned int count = 0;
-        while (first != last) {
-            ++first;
-            ++count;
-        }
-        return count;
-    }
-    unsigned int distance(const_iterator first, const_iterator last) const {
-        unsigned int count = 0;
+    template<
+        typename U,
+        template <class> class CL,
+        template <class> class CR
+    > 
+    ptrdiff_t distance(
+            _ListIterator<U, CL> first, _ListIterator<U, CR> last) const 
+    {
+        ptrdiff_t count = 0;
         while (first != last) {
             ++first;
             ++count;
@@ -231,12 +283,12 @@
 
 private:
     /*
-     * I want a _ListNode but don't need it to hold valid data.  More
+     * I want a _Node but don't need it to hold valid data.  More
      * to the point, I don't want T's constructor to fire, since it
      * might have side-effects or require arguments.  So, we do this
      * slightly uncouth storage alloc.
      */
-    void prep(void) {
+    void prep() {
         mpMiddle = (_Node*) new unsigned char[sizeof(_Node)];
         mpMiddle->setPrev(mpMiddle);
         mpMiddle->setNext(mpMiddle);
diff --git a/include/utils/LogSocket.h b/include/utils/LogSocket.h
deleted file mode 100644
index 01fbfb5..0000000
--- a/include/utils/LogSocket.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* utils/LogSocket.h
-** 
-** Copyright 2008, The Android Open Source Project
-**
-** This file is dual licensed.  It may be redistributed and/or modified
-** under the terms of the Apache 2.0 License OR version 2 of the GNU
-** General Public License.
-*/
-
-#ifndef _UTILS_LOGSOCKET_H
-#define _UTILS_LOGSOCKET_H
-
-#define SOCKET_CLOSE_LOCAL 0
-
-void add_send_stats(int fd, int send);
-void add_recv_stats(int fd, int recv);
-void log_socket_close(int fd, short reason);
-void log_socket_connect(int fd, unsigned int ip, unsigned short port);
-
-#endif /* _UTILS_LOGSOCKET_H */
diff --git a/include/utils/Pipe.h b/include/utils/Pipe.h
deleted file mode 100644
index 6404168..0000000
--- a/include/utils/Pipe.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// FIFO I/O.
-//
-#ifndef _LIBS_UTILS_PIPE_H
-#define _LIBS_UTILS_PIPE_H
-
-#ifdef HAVE_ANDROID_OS
-#error DO NOT USE THIS FILE IN THE DEVICE BUILD
-#endif
-
-namespace android {
-
-/*
- * Simple anonymous unidirectional pipe.
- *
- * The primary goal is to create an implementation with minimal overhead
- * under Linux.  Making Windows, Mac OS X, and Linux all work the same way
- * is a secondary goal.  Part of this goal is to have something that can
- * be fed to a select() call, so that the application can sleep in the
- * kernel until something interesting happens.
- */
-class Pipe {
-public:
-    Pipe(void);
-    virtual ~Pipe(void);
-
-    /* Create the pipe */
-    bool create(void);
-
-    /* Create a read-only pipe, using the supplied handle as read handle */
-    bool createReader(unsigned long handle);
-    /* Create a write-only pipe, using the supplied handle as write handle */
-    bool createWriter(unsigned long handle);
-
-    /* Is this object ready to go? */
-    bool isCreated(void);
-
-    /*
-     * Read "count" bytes from the pipe.  Returns the amount of data read,
-     * or 0 if no data available and we're non-blocking.
-     * Returns -1 on error.
-     */
-    int read(void* buf, int count);
-
-    /*
-     * Write "count" bytes into the pipe.  Returns number of bytes written,
-     * or 0 if there's no room for more data and we're non-blocking.
-     * Returns -1 on error.
-     */
-    int write(const void* buf, int count);
-
-    /* Returns "true" if data is available to read */
-    bool readReady(void);
-
-    /* Enable or disable non-blocking I/O for reads */
-    bool setReadNonBlocking(bool val);
-    /* Enable or disable non-blocking I/O for writes.  Only works on Linux. */
-    bool setWriteNonBlocking(bool val);
-
-    /*
-     * Get the handle.  Only useful in some platform-specific situations.
-     */
-    unsigned long getReadHandle(void);
-    unsigned long getWriteHandle(void);
-
-    /*
-     * Modify inheritance, i.e. whether or not a child process will get
-     * copies of the descriptors.  Systems with fork+exec allow us to close
-     * the descriptors before launching the child process, but Win32
-     * doesn't allow it.
-     */
-    bool disallowReadInherit(void);
-    bool disallowWriteInherit(void);
-
-    /*
-     * Close one side or the other.  Useful in the parent after launching
-     * a child process.
-     */
-    bool closeRead(void);
-    bool closeWrite(void);
-
-private:
-    bool    mReadNonBlocking;
-    bool    mWriteNonBlocking;
-
-    unsigned long mReadHandle;
-    unsigned long mWriteHandle;
-};
-
-}; // android
-
-#endif // _LIBS_UTILS_PIPE_H
diff --git a/include/utils/RefBase.h b/include/utils/RefBase.h
index cbda0fd..bd7f28c 100644
--- a/include/utils/RefBase.h
+++ b/include/utils/RefBase.h
@@ -156,6 +156,10 @@
             delete static_cast<const T*>(this);
         }
     }
+    //! DEBUGGING ONLY: Get current strong ref count.
+    inline int32_t getStrongCount() const {
+        return mCount;
+    }
     
 protected:
     inline ~LightRefBase() { }
diff --git a/include/utils/Singleton.h b/include/utils/Singleton.h
new file mode 100644
index 0000000..bc7626a8
--- /dev/null
+++ b/include/utils/Singleton.h
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_UTILS_SINGLETON_H
+#define ANDROID_UTILS_SINGLETON_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <utils/threads.h>
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+template <typename TYPE>
+class Singleton
+{
+public:
+    static TYPE& getInstance() {
+        Mutex::Autolock _l(sLock);
+        TYPE* instance = sInstance;
+        if (instance == 0) {
+            instance = new TYPE();
+            sInstance = instance;
+        }
+        return *instance;
+    }
+    
+protected:
+    ~Singleton() { };
+    Singleton() { };
+
+private:
+    Singleton(const Singleton&);
+    Singleton& operator = (const Singleton&);
+    static Mutex sLock;
+    static TYPE* sInstance;
+};
+
+/*
+ * use ANDROID_SINGLETON_STATIC_INSTANCE(TYPE) in your implementation file
+ * (eg: <TYPE>.cpp) to create the static instance of Singleton<>'s attributes,
+ * and avoid to have a copy of them in each compilation units Singleton<TYPE>
+ * is used.
+ */
+
+#define ANDROID_SINGLETON_STATIC_INSTANCE(TYPE)             \
+    template class Singleton< TYPE >;                       \
+    template< class TYPE > Mutex Singleton< TYPE >::sLock;  \
+    template<> TYPE* Singleton< TYPE >::sInstance(0);
+
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_UTILS_SINGLETON_H
+
diff --git a/include/utils/Socket.h b/include/utils/Socket.h
deleted file mode 100644
index 8b7f4061..0000000
--- a/include/utils/Socket.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Socket class.  Modeled after Java classes.
-//
-#ifndef _RUNTIME_SOCKET_H
-#define _RUNTIME_SOCKET_H
-
-#include <utils/inet_address.h>
-#include <sys/types.h>
-
-namespace android {
-
-/*
- * Basic socket class, needed to abstract away the differences between
- * BSD sockets and WinSock.  This establishes a streaming network
- * connection (TCP/IP) to somebody.
- */
-class Socket {
-public:
-    Socket(void);
-    ~Socket(void);
-
-    // Create a connection to somewhere.
-    // Return 0 on success.
-    int connect(const char* host, int port);
-    int connect(const InetAddress* addr, int port);
-
-
-    // Close the socket.  Don't try to use this object again after
-    // calling this.  Returns false on failure.
-    bool close(void);
-
-    // If we created the socket without an address, we can use these
-    // to finish the connection.  Returns 0 on success.
-    int bind(const SocketAddress& bindPoint);
-    int connect(const SocketAddress& endPoint);
-
-    // Here we deviate from the traditional object-oriented fanciness
-    // and just provide read/write operators instead of getters for
-    // objects that abstract a stream.
-    //
-    // Standard read/write semantics.
-    int read(void* buf, ssize_t len) const;
-    int write(const void* buf, ssize_t len) const;
-
-    // This must be called once, at program startup.
-    static bool bootInit(void);
-    static void finalShutdown(void);
-
-private:
-    // Internal function that establishes a connection.
-    int doConnect(const InetSocketAddress& addr);
-
-    unsigned long   mSock;      // holds SOCKET or int
-
-    static bool     mBootInitialized;
-};
-
-
-// debug -- unit tests
-void TestSockets(void);
-
-}; // namespace android
-
-#endif // _RUNTIME_SOCKET_H
diff --git a/include/utils/SortedVector.h b/include/utils/SortedVector.h
index c8a6153..8beec57 100644
--- a/include/utils/SortedVector.h
+++ b/include/utils/SortedVector.h
@@ -141,8 +141,7 @@
     : SortedVectorImpl(sizeof(TYPE),
                 ((traits<TYPE>::has_trivial_ctor   ? HAS_TRIVIAL_CTOR   : 0)
                 |(traits<TYPE>::has_trivial_dtor   ? HAS_TRIVIAL_DTOR   : 0)
-                |(traits<TYPE>::has_trivial_copy   ? HAS_TRIVIAL_COPY   : 0)
-                |(traits<TYPE>::has_trivial_assign ? HAS_TRIVIAL_ASSIGN : 0))
+                |(traits<TYPE>::has_trivial_copy   ? HAS_TRIVIAL_COPY   : 0))
                 )
 {
 }
diff --git a/include/utils/StringArray.h b/include/utils/StringArray.h
new file mode 100644
index 0000000..c244587
--- /dev/null
+++ b/include/utils/StringArray.h
@@ -0,0 +1,83 @@
+/*
+ * 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.
+ */
+
+//
+// Sortable array of strings.  STL-ish, but STL-free.
+//  
+#ifndef _LIBS_UTILS_STRING_ARRAY_H
+#define _LIBS_UTILS_STRING_ARRAY_H
+
+#include <stdlib.h>
+#include <string.h>
+
+namespace android {
+
+//
+// An expanding array of strings.  Add, get, sort, delete.
+//
+class StringArray {
+public:
+    StringArray();
+    virtual ~StringArray();
+
+    //
+    // Add a string.  A copy of the string is made.
+    //
+    bool push_back(const char* str);
+
+    //
+    // Delete an entry.
+    //
+    void erase(int idx);
+
+    //
+    // Sort the array.
+    //
+    void sort(int (*compare)(const void*, const void*));
+    
+    //
+    // Pass this to the sort routine to do an ascending alphabetical sort.
+    //
+    static int cmpAscendingAlpha(const void* pstr1, const void* pstr2);
+    
+    //
+    // Get the #of items in the array.
+    //
+    inline int size(void) const { return mCurrent; }
+
+    //
+    // Return entry N.
+    // [should use operator[] here]
+    //
+    const char* getEntry(int idx) const {
+        return (unsigned(idx) >= unsigned(mCurrent)) ? NULL : mArray[idx];
+    }
+
+    //
+    // Set entry N to specified string.
+    // [should use operator[] here]
+    //
+    void setEntry(int idx, const char* str);
+
+private:
+    int     mMax;
+    int     mCurrent;
+    char**  mArray;
+};
+
+}; // namespace android
+
+#endif // _LIBS_UTILS_STRING_ARRAY_H
diff --git a/include/utils/TextOutput.h b/include/utils/TextOutput.h
index d8d86ba..de2fbbe 100644
--- a/include/utils/TextOutput.h
+++ b/include/utils/TextOutput.h
@@ -28,8 +28,8 @@
 class TextOutput
 {
 public:
-                        TextOutput() { }
-    virtual             ~TextOutput() { }
+                        TextOutput();
+    virtual             ~TextOutput();
     
     virtual status_t    print(const char* txt, size_t len) = 0;
     virtual void        moveIndent(int delta) = 0;
diff --git a/include/utils/TimerProbe.h b/include/utils/TimerProbe.h
deleted file mode 100644
index f2e32b2..0000000
--- a/include/utils/TimerProbe.h
+++ /dev/null
@@ -1,72 +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.
- */
-
-#ifndef ANDROID_TIMER_PROBE_H
-#define ANDROID_TIMER_PROBE_H
-
-#if 0 && defined(HAVE_POSIX_CLOCKS)
-#define ENABLE_TIMER_PROBE 1
-#else
-#define ENABLE_TIMER_PROBE 0
-#endif
-
-#if ENABLE_TIMER_PROBE
-
-#include <time.h>
-#include <sys/time.h>
-#include <utils/Vector.h>
-
-#define TIMER_PROBE(tag) \
-    static int _timer_slot_; \
-    android::TimerProbe probe(tag, &_timer_slot_)
-#define TIMER_PROBE_END() probe.end()
-#else
-#define TIMER_PROBE(tag)
-#define TIMER_PROBE_END()
-#endif
-
-#if ENABLE_TIMER_PROBE
-namespace android {
-
-class TimerProbe {
-public:
-    TimerProbe(const char tag[], int* slot);
-    void end();
-    ~TimerProbe();
-private:
-    struct Bucket {
-        int mStart, mReal, mProcess, mThread, mCount;
-        const char* mTag;
-        int* mSlotPtr;
-        int mIndent;
-    };
-    static Vector<Bucket> gBuckets;
-    static TimerProbe* gExecuteChain;
-    static int gIndent;
-    static timespec gRealBase;
-    TimerProbe* mNext;
-    static uint32_t ElapsedTime(const timespec& start, const timespec& end);
-    void print(const timespec& r, const timespec& p, const timespec& t) const;
-    timespec mRealStart, mPStart, mTStart;
-    const char* mTag;
-    int mIndent;
-    int mBucket;
-};
-
-}; // namespace android
-
-#endif
-#endif
diff --git a/include/utils/Timers.h b/include/utils/Timers.h
index 9610399..9a9e07c 100644
--- a/include/utils/Timers.h
+++ b/include/utils/Timers.h
@@ -88,9 +88,6 @@
 nsecs_t systemTime(int clock);
 #endif // def __cplusplus
 
-// return the system-time according to the specified clock
-int sleepForInterval(long interval, struct timeval* pNextTick);
-
 #ifdef __cplusplus
 } // extern "C"
 #endif
@@ -108,15 +105,15 @@
  */
 class DurationTimer {
 public:
-    DurationTimer(void) {}
-    ~DurationTimer(void) {}
+    DurationTimer() {}
+    ~DurationTimer() {}
 
     // Start the timer.
-    void start(void);
+    void start();
     // Stop the timer.
-    void stop(void);
+    void stop();
     // Get the duration in microseconds.
-    long long durationUsecs(void) const;
+    long long durationUsecs() const;
 
     // Subtract two timevals.  Returns the difference (ptv1-ptv2) in
     // microseconds.
diff --git a/include/utils/TypeHelpers.h b/include/utils/TypeHelpers.h
index c04c37f..2ff2749 100644
--- a/include/utils/TypeHelpers.h
+++ b/include/utils/TypeHelpers.h
@@ -29,35 +29,39 @@
 /*
  * Types traits
  */
-    
-template <typename T> struct trait_trivial_ctor  { enum { value = false }; };
-template <typename T> struct trait_trivial_dtor  { enum { value = false }; };
-template <typename T> struct trait_trivial_copy  { enum { value = false }; };
-template <typename T> struct trait_trivial_assign{ enum { value = false }; };
 
-template <typename T> struct trait_pointer     { enum { value = false }; };    
-template <typename T> struct trait_pointer<T*> { enum { value = true }; };
+template <typename T> struct trait_trivial_ctor { enum { value = false }; };
+template <typename T> struct trait_trivial_dtor { enum { value = false }; };
+template <typename T> struct trait_trivial_copy { enum { value = false }; };
+template <typename T> struct trait_trivial_move { enum { value = false }; };
+template <typename T> struct trait_pointer      { enum { value = false }; };    
+template <typename T> struct trait_pointer<T*>  { enum { value = true }; };
 
-#define ANDROID_BASIC_TYPES_TRAITS( T )                                       \
-    template<> struct trait_trivial_ctor< T >  { enum { value = true }; };    \
-    template<> struct trait_trivial_dtor< T >  { enum { value = true }; };    \
-    template<> struct trait_trivial_copy< T >  { enum { value = true }; };    \
-    template<> struct trait_trivial_assign< T >{ enum { value = true }; }; 
+// sp<> can be trivially moved
+template <typename T> class sp;
+template <typename T> struct trait_trivial_move< sp<T> >{
+    enum { value = true }; 
+};
 
-#define ANDROID_TYPE_TRAITS( T, ctor, dtor, copy, assign )                    \
-    template<> struct trait_trivial_ctor< T >  { enum { value = ctor }; };    \
-    template<> struct trait_trivial_dtor< T >  { enum { value = dtor }; };    \
-    template<> struct trait_trivial_copy< T >  { enum { value = copy }; };    \
-    template<> struct trait_trivial_assign< T >{ enum { value = assign }; }; 
+// wp<> can be trivially moved
+template <typename T> class wp;
+template <typename T> struct trait_trivial_move< wp<T> >{ 
+    enum { value = true }; 
+};
 
 template <typename TYPE>
 struct traits {
     enum {
+        // whether this type is a pointer
         is_pointer          = trait_pointer<TYPE>::value,
+        // whether this type's constructor is a no-op
         has_trivial_ctor    = is_pointer || trait_trivial_ctor<TYPE>::value,
+        // whether this type's destructor is a no-op
         has_trivial_dtor    = is_pointer || trait_trivial_dtor<TYPE>::value,
+        // whether this type type can be copy-constructed with memcpy
         has_trivial_copy    = is_pointer || trait_trivial_copy<TYPE>::value,
-        has_trivial_assign  = is_pointer || trait_trivial_assign<TYPE>::value   
+        // whether this type can be moved with memmove
+        has_trivial_move    = is_pointer || trait_trivial_move<TYPE>::value
     };
 };
 
@@ -65,37 +69,47 @@
 struct aggregate_traits {
     enum {
         is_pointer          = false,
-        has_trivial_ctor    = traits<T>::has_trivial_ctor && traits<U>::has_trivial_ctor,
-        has_trivial_dtor    = traits<T>::has_trivial_dtor && traits<U>::has_trivial_dtor,
-        has_trivial_copy    = traits<T>::has_trivial_copy && traits<U>::has_trivial_copy,
-        has_trivial_assign  = traits<T>::has_trivial_assign && traits<U>::has_trivial_assign
+        has_trivial_ctor    = 
+            traits<T>::has_trivial_ctor && traits<U>::has_trivial_ctor,
+        has_trivial_dtor    = 
+            traits<T>::has_trivial_dtor && traits<U>::has_trivial_dtor,
+        has_trivial_copy    = 
+            traits<T>::has_trivial_copy && traits<U>::has_trivial_copy,
+        has_trivial_move    = 
+            traits<T>::has_trivial_move && traits<U>::has_trivial_move
     };
 };
 
+#define ANDROID_BASIC_TYPES_TRAITS( T )                                     \
+    template<> struct trait_trivial_ctor< T >   { enum { value = true }; }; \
+    template<> struct trait_trivial_dtor< T >   { enum { value = true }; }; \
+    template<> struct trait_trivial_copy< T >   { enum { value = true }; }; \
+    template<> struct trait_trivial_move< T >   { enum { value = true }; };
+
 // ---------------------------------------------------------------------------
 
 /*
  * basic types traits
  */
- 
-ANDROID_BASIC_TYPES_TRAITS( void );
-ANDROID_BASIC_TYPES_TRAITS( bool );
-ANDROID_BASIC_TYPES_TRAITS( char );
-ANDROID_BASIC_TYPES_TRAITS( unsigned char );
-ANDROID_BASIC_TYPES_TRAITS( short );
-ANDROID_BASIC_TYPES_TRAITS( unsigned short );
-ANDROID_BASIC_TYPES_TRAITS( int );
-ANDROID_BASIC_TYPES_TRAITS( unsigned int );
-ANDROID_BASIC_TYPES_TRAITS( long );
-ANDROID_BASIC_TYPES_TRAITS( unsigned long );
-ANDROID_BASIC_TYPES_TRAITS( long long );
-ANDROID_BASIC_TYPES_TRAITS( unsigned long long );
-ANDROID_BASIC_TYPES_TRAITS( float );
-ANDROID_BASIC_TYPES_TRAITS( double );
+
+ANDROID_BASIC_TYPES_TRAITS( void )
+ANDROID_BASIC_TYPES_TRAITS( bool )
+ANDROID_BASIC_TYPES_TRAITS( char )
+ANDROID_BASIC_TYPES_TRAITS( unsigned char )
+ANDROID_BASIC_TYPES_TRAITS( short )
+ANDROID_BASIC_TYPES_TRAITS( unsigned short )
+ANDROID_BASIC_TYPES_TRAITS( int )
+ANDROID_BASIC_TYPES_TRAITS( unsigned int )
+ANDROID_BASIC_TYPES_TRAITS( long )
+ANDROID_BASIC_TYPES_TRAITS( unsigned long )
+ANDROID_BASIC_TYPES_TRAITS( long long )
+ANDROID_BASIC_TYPES_TRAITS( unsigned long long )
+ANDROID_BASIC_TYPES_TRAITS( float )
+ANDROID_BASIC_TYPES_TRAITS( double )
 
 // ---------------------------------------------------------------------------
 
-    
+
 /*
  * compare and order types
  */
@@ -111,9 +125,9 @@
 }
 
 /*
- * create, destroy, copy and assign types...
+ * create, destroy, copy and move types...
  */
- 
+
 template<typename TYPE> inline
 void construct_type(TYPE* p, size_t n) {
     if (!traits<TYPE>::has_trivial_ctor) {
@@ -146,17 +160,6 @@
 }
 
 template<typename TYPE> inline
-void assign_type(TYPE* d, const TYPE* s, size_t n) {
-    if (!traits<TYPE>::has_trivial_assign) {
-        while (n--) {
-            *d++ = *s++;
-        }
-    } else {
-        memcpy(d,s,n*sizeof(TYPE));
-    }
-}
-
-template<typename TYPE> inline
 void splat_type(TYPE* where, const TYPE* what, size_t n) {
     if (!traits<TYPE>::has_trivial_copy) {
         while (n--) {
@@ -164,15 +167,19 @@
             where++;
         }
     } else {
-         while (n--) {
-             *where++ = *what;
+        while (n--) {
+            *where++ = *what;
         }
     }
 }
 
 template<typename TYPE> inline
 void move_forward_type(TYPE* d, const TYPE* s, size_t n = 1) {
-    if (!traits<TYPE>::has_trivial_copy || !traits<TYPE>::has_trivial_dtor) {
+    if ((traits<TYPE>::has_trivial_dtor && traits<TYPE>::has_trivial_copy) 
+            || traits<TYPE>::has_trivial_move) 
+    {
+        memmove(d,s,n*sizeof(TYPE));
+    } else {
         d += n;
         s += n;
         while (n--) {
@@ -180,35 +187,37 @@
             if (!traits<TYPE>::has_trivial_copy) {
                 new(d) TYPE(*s);
             } else {
-                *d = *s;
+                *d = *s;   
             }
             if (!traits<TYPE>::has_trivial_dtor) {
                 s->~TYPE();
             }
         }
-    } else {
-        memmove(d,s,n*sizeof(TYPE));
     }
 }
 
 template<typename TYPE> inline
 void move_backward_type(TYPE* d, const TYPE* s, size_t n = 1) {
-    if (!traits<TYPE>::has_trivial_copy || !traits<TYPE>::has_trivial_dtor) {
+    if ((traits<TYPE>::has_trivial_dtor && traits<TYPE>::has_trivial_copy) 
+            || traits<TYPE>::has_trivial_move) 
+    {
+        memmove(d,s,n*sizeof(TYPE));
+    } else {
         while (n--) {
             if (!traits<TYPE>::has_trivial_copy) {
                 new(d) TYPE(*s);
             } else {
-                *d = *s;
+                *d = *s;   
             }
             if (!traits<TYPE>::has_trivial_dtor) {
                 s->~TYPE();
             }
             d++, s++;
         }
-    } else {
-        memmove(d,s,n*sizeof(TYPE));
     }
 }
+
+
 // ---------------------------------------------------------------------------
 
 /*
@@ -242,8 +251,8 @@
 { enum { value = aggregate_traits<K,V>::has_trivial_copy }; };
 template<> 
 template <typename K, typename V>
-struct trait_trivial_assign< key_value_pair_t<K, V> >
-{ enum { value = aggregate_traits<K,V>::has_trivial_assign};};
+struct trait_trivial_move< key_value_pair_t<K, V> >
+{ enum { value = aggregate_traits<K,V>::has_trivial_move }; };
 
 // ---------------------------------------------------------------------------
 
diff --git a/include/utils/Vector.h b/include/utils/Vector.h
index be365d8..ad59fd6 100644
--- a/include/utils/Vector.h
+++ b/include/utils/Vector.h
@@ -175,8 +175,7 @@
     : VectorImpl(sizeof(TYPE),
                 ((traits<TYPE>::has_trivial_ctor   ? HAS_TRIVIAL_CTOR   : 0)
                 |(traits<TYPE>::has_trivial_dtor   ? HAS_TRIVIAL_DTOR   : 0)
-                |(traits<TYPE>::has_trivial_copy   ? HAS_TRIVIAL_COPY   : 0)
-                |(traits<TYPE>::has_trivial_assign ? HAS_TRIVIAL_ASSIGN : 0))
+                |(traits<TYPE>::has_trivial_copy   ? HAS_TRIVIAL_COPY   : 0))
                 )
 {
 }
diff --git a/include/utils/VectorImpl.h b/include/utils/VectorImpl.h
index 2525229..49b03f1 100644
--- a/include/utils/VectorImpl.h
+++ b/include/utils/VectorImpl.h
@@ -44,7 +44,6 @@
         HAS_TRIVIAL_CTOR    = 0x00000001,
         HAS_TRIVIAL_DTOR    = 0x00000002,
         HAS_TRIVIAL_COPY    = 0x00000004,
-        HAS_TRIVIAL_ASSIGN  = 0x00000008
     };
 
                             VectorImpl(size_t itemSize, uint32_t flags);
diff --git a/include/utils/inet_address.h b/include/utils/inet_address.h
deleted file mode 100644
index dbd8672..0000000
--- a/include/utils/inet_address.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Internet address classes.  Modeled after Java classes.
-//
-#ifndef _RUNTIME_INET_ADDRESS_H
-#define _RUNTIME_INET_ADDRESS_H
-
-#ifdef HAVE_ANDROID_OS
-#error DO NOT USE THIS FILE IN THE DEVICE BUILD
-#endif
-
-
-namespace android {
-
-/*
- * This class holds Internet addresses.  Perhaps more useful is its
- * ability to look up addresses by name.
- *
- * Invoke one of the static factory methods to create a new object.
- */
-class InetAddress {
-public:
-    virtual ~InetAddress(void);
-
-    // create from w.x.y.z or foo.bar.com notation
-    static InetAddress* getByName(const char* host);
-
-    // copy-construction
-    InetAddress(const InetAddress& orig);
-
-    const void* getAddress(void) const { return mAddress; }
-    int getAddressLength(void) const { return mLength; }
-    const char* getHostName(void) const { return mName; }
-
-private:
-    InetAddress(void);
-    // assignment (private)
-    InetAddress& operator=(const InetAddress& addr);
-
-    // use a void* here so we don't have to expose actual socket headers
-    void*       mAddress;   // this is really a ptr to sockaddr_in
-    int         mLength;
-    char*       mName;
-};
-
-
-/*
- * Base class for socket addresses.
- */
-class SocketAddress {
-public:
-    SocketAddress() {}
-    virtual ~SocketAddress() {}
-};
-
-
-/*
- * Internet address class.  This combines an InetAddress with a port.
- */
-class InetSocketAddress : public SocketAddress {
-public:
-    InetSocketAddress() :
-        mAddress(0), mPort(-1)
-        {}
-    ~InetSocketAddress(void) {
-        delete mAddress;
-    }
-
-    // Create an address with a host wildcard (useful for servers).
-    bool create(int port);
-    // Create an address with the specified host and port.
-    bool create(const InetAddress* addr, int port);
-    // Create an address with the specified host and port.  Does the
-    // hostname lookup.
-    bool create(const char* host, int port);
-
-    const InetAddress* getAddress(void) const { return mAddress; }
-    const int getPort(void) const { return mPort; }
-    const char* getHostName(void) const { return mAddress->getHostName(); }
-
-private:
-    InetAddress* mAddress;
-    int         mPort;
-};
-
-}; // namespace android
-
-#endif // _RUNTIME_INET_ADDRESS_H
diff --git a/include/utils/misc.h b/include/utils/misc.h
index 62e84b4..23f2a4c 100644
--- a/include/utils/misc.h
+++ b/include/utils/misc.h
@@ -21,7 +21,7 @@
 #define _LIBS_UTILS_MISC_H
 
 #include <sys/time.h>
-#include "utils/Endian.h"
+#include <utils/Endian.h>
 
 namespace android {
 
diff --git a/include/utils/ported.h b/include/utils/ported.h
deleted file mode 100644
index eb3be01..0000000
--- a/include/utils/ported.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Standard functions ported to the current platform.  Note these are NOT
-// in the "android" namespace.
-//
-#ifndef _LIBS_UTILS_PORTED_H
-#define _LIBS_UTILS_PORTED_H
-
-#include <sys/time.h>       // for timeval
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* library replacement functions */
-#if defined(NEED_GETTIMEOFDAY)
-int gettimeofday(struct timeval* tv, struct timezone* tz);
-#endif
-#if defined(NEED_USLEEP)
-void usleep(unsigned long usec);
-#endif
-#if defined(NEED_PIPE)
-int pipe(int filedes[2]);
-#endif
-#if defined(NEED_SETENV)
-int setenv(const char* name, const char* value, int overwrite);
-void unsetenv(const char* name);
-char* getenv(const char* name);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // _LIBS_UTILS_PORTED_H
diff --git a/include/utils/string_array.h b/include/utils/string_array.h
deleted file mode 100644
index 064dda2..0000000
--- a/include/utils/string_array.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Sortable array of strings.  STL-ish, but STL-free.
-//  
-#ifndef _LIBS_UTILS_STRING_ARRAY_H
-#define _LIBS_UTILS_STRING_ARRAY_H
-
-#include <stdlib.h>
-#include <string.h>
-
-namespace android {
-
-//
-// An expanding array of strings.  Add, get, sort, delete.
-//
-class StringArray {
-public:
-    StringArray()
-        : mMax(0), mCurrent(0), mArray(NULL)
-        {}
-    virtual ~StringArray() {
-        for (int i = 0; i < mCurrent; i++)
-            delete[] mArray[i];
-        delete[] mArray;
-    }
-
-    //
-    // Add a string.  A copy of the string is made.
-    //
-    bool push_back(const char* str) {
-        if (mCurrent >= mMax) {
-            char** tmp;
-
-            if (mMax == 0)
-                mMax = 16;      // initial storage
-            else
-                mMax *= 2;
-
-            tmp = new char*[mMax];
-            if (tmp == NULL)
-                return false;
-
-            memcpy(tmp, mArray, mCurrent * sizeof(char*));
-            delete[] mArray;
-            mArray = tmp;
-        }
-
-        int len = strlen(str);
-        mArray[mCurrent] = new char[len+1];
-        memcpy(mArray[mCurrent], str, len+1);
-        mCurrent++;
-
-        return true;
-    }
-
-    //
-    // Delete an entry.
-    //
-    void erase(int idx) {
-        if (idx < 0 || idx >= mCurrent)
-            return;
-        delete[] mArray[idx];
-        if (idx < mCurrent-1) {
-            memmove(&mArray[idx], &mArray[idx+1],
-                (mCurrent-1 - idx) * sizeof(char*));
-        }
-        mCurrent--;
-    }
-
-    //
-    // Sort the array.
-    //
-    void sort(int (*compare)(const void*, const void*)) {
-        qsort(mArray, mCurrent, sizeof(char*), compare);
-    }
-
-    //
-    // Pass this to the sort routine to do an ascending alphabetical sort.
-    //
-    static int cmpAscendingAlpha(const void* pstr1, const void* pstr2) {
-        return strcmp(*(const char**)pstr1, *(const char**)pstr2);
-    }
-
-    //
-    // Get the #of items in the array.
-    //
-    inline int size(void) const { return mCurrent; }
-
-    //
-    // Return entry N.
-    // [should use operator[] here]
-    //
-    const char* getEntry(int idx) const {
-        if (idx < 0 || idx >= mCurrent)
-            return NULL;
-        return mArray[idx];
-    }
-
-    //
-    // Set entry N to specified string.
-    // [should use operator[] here]
-    //
-    void setEntry(int idx, const char* str) {
-        if (idx < 0 || idx >= mCurrent)
-            return;
-        delete[] mArray[idx];
-        int len = strlen(str);
-        mArray[idx] = new char[len+1];
-        memcpy(mArray[idx], str, len+1);
-    }
-
-private:
-    int     mMax;
-    int     mCurrent;
-    char**  mArray;
-};
-
-}; // namespace android
-
-#endif // _LIBS_UTILS_STRING_ARRAY_H
diff --git a/include/utils/threads.h b/include/utils/threads.h
index b320915..e9b0788 100644
--- a/include/utils/threads.h
+++ b/include/utils/threads.h
@@ -21,6 +21,10 @@
 #include <sys/types.h>
 #include <time.h>
 
+#if defined(HAVE_PTHREADS)
+# include <pthread.h>
+#endif
+
 // ------------------------------------------------------------------
 // C API
 
@@ -176,6 +180,8 @@
     return androidGetThreadId();
 }
 
+/*****************************************************************************/
+
 /*
  * Simple mutex class.  The implementation is system-dependent.
  *
@@ -184,8 +190,14 @@
  */
 class Mutex {
 public:
+    enum {
+        NORMAL = 0,
+        SHARED = 1
+    };
+    
                 Mutex();
                 Mutex(const char* name);
+                Mutex(int type, const char* name = NULL);
                 ~Mutex();
 
     // lock or unlock the mutex
@@ -199,11 +211,11 @@
     // constructed and released when Autolock goes out of scope.
     class Autolock {
     public:
-        inline Autolock(Mutex& mutex) : mpMutex(&mutex) { mutex.lock(); }
-        inline Autolock(Mutex* mutex) : mpMutex(mutex) { mutex->lock(); }
-        inline ~Autolock() { mpMutex->unlock(); }
+        inline Autolock(Mutex& mutex) : mLock(mutex)  { mLock.lock(); }
+        inline Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); }
+        inline ~Autolock() { mLock.unlock(); }
     private:
-        Mutex*  mpMutex;
+        Mutex& mLock;
     };
 
 private:
@@ -212,11 +224,49 @@
     // A mutex cannot be copied
                 Mutex(const Mutex&);
     Mutex&      operator = (const Mutex&);
-    void        _init();
     
+#if defined(HAVE_PTHREADS)
+    pthread_mutex_t mMutex;
+#else
+    void    _init();
     void*   mState;
+#endif
 };
 
+#if defined(HAVE_PTHREADS)
+
+inline Mutex::Mutex() {
+    pthread_mutex_init(&mMutex, NULL);
+}
+inline Mutex::Mutex(const char* name) {
+    pthread_mutex_init(&mMutex, NULL);
+}
+inline Mutex::Mutex(int type, const char* name) {
+    if (type == SHARED) {
+        pthread_mutexattr_t attr;
+        pthread_mutexattr_init(&attr);
+        pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
+        pthread_mutex_init(&mMutex, &attr);
+        pthread_mutexattr_destroy(&attr);
+    } else {
+        pthread_mutex_init(&mMutex, NULL);
+    }
+}
+inline Mutex::~Mutex() {
+    pthread_mutex_destroy(&mMutex);
+}
+inline status_t Mutex::lock() {
+    return -pthread_mutex_lock(&mMutex);
+}
+inline void Mutex::unlock() {
+    pthread_mutex_unlock(&mMutex);
+}
+inline status_t Mutex::tryLock() {
+    return -pthread_mutex_trylock(&mMutex);
+}
+
+#endif // HAVE_PTHREADS
+
 /*
  * Automatic mutex.  Declare one of these at the top of a function.
  * When the function returns, it will go out of scope, and release the
@@ -225,6 +275,7 @@
  
 typedef Mutex::Autolock AutoMutex;
 
+/*****************************************************************************/
 
 /*
  * Condition variable class.  The implementation is system-dependent.
@@ -240,9 +291,6 @@
     ~Condition();
     // Wait on the condition variable.  Lock the mutex before calling.
     status_t wait(Mutex& mutex);
-    // Wait on the condition variable until the given time.  Lock the mutex
-    // before calling.
-    status_t wait(Mutex& mutex, nsecs_t abstime);
     // same with relative timeout
     status_t waitRelative(Mutex& mutex, nsecs_t reltime);
     // Signal the condition variable, allowing one thread to continue.
@@ -251,9 +299,60 @@
     void broadcast();
 
 private:
+#if defined(HAVE_PTHREADS)
+    pthread_cond_t mCond;
+#else
     void*   mState;
+#endif
 };
 
+#if defined(HAVE_PTHREADS)
+
+inline Condition::Condition() {
+    pthread_cond_init(&mCond, NULL);
+}
+inline Condition::~Condition() {
+    pthread_cond_destroy(&mCond);
+}
+inline status_t Condition::wait(Mutex& mutex) {
+    return -pthread_cond_wait(&mCond, &mutex.mMutex);
+}
+inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) {
+#if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)
+    struct timespec ts;
+    ts.tv_sec  = reltime/1000000000;
+    ts.tv_nsec = reltime%1000000000;
+    return -pthread_cond_timedwait_relative_np(&mCond, &mutex.mMutex, &ts);
+#else // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
+    struct timespec ts;
+#if defined(HAVE_POSIX_CLOCKS)
+    clock_gettime(CLOCK_REALTIME, &ts);
+#else // HAVE_POSIX_CLOCKS
+    // we don't support the clocks here.
+    struct timeval t;
+    gettimeofday(&t, NULL);
+    ts.tv_sec = t.tv_sec;
+    ts.tv_nsec= t.tv_usec*1000;
+#endif // HAVE_POSIX_CLOCKS
+    ts.tv_sec += reltime/1000000000;
+    ts.tv_nsec+= reltime%1000000000;
+    if (ts.tv_nsec >= 1000000000) {
+        ts.tv_nsec -= 1000000000;
+        ts.tv_sec  += 1;
+    }
+    return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts);
+#endif // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
+}
+inline void Condition::signal() {
+    pthread_cond_signal(&mCond);
+}
+inline void Condition::broadcast() {
+    pthread_cond_broadcast(&mCond);
+}
+
+#endif // HAVE_PTHREADS
+
+/*****************************************************************************/
 
 /*
  * This is our spiffy thread object!
@@ -291,7 +390,7 @@
             bool        exitPending() const;
     
 private:
-    // Derived class must implemtent threadLoop(). The thread starts its life
+    // Derived class must implement threadLoop(). The thread starts its life
     // here. There are two ways of using the Thread object:
     // 1) loop: if threadLoop() returns true, it will be called again if
     //          requestExit() wasn't called.
diff --git a/libs/audioflinger/A2dpAudioInterface.cpp b/libs/audioflinger/A2dpAudioInterface.cpp
index 16a4f2d..6f9e934 100644
--- a/libs/audioflinger/A2dpAudioInterface.cpp
+++ b/libs/audioflinger/A2dpAudioInterface.cpp
@@ -29,25 +29,41 @@
 
 // ----------------------------------------------------------------------------
 
-A2dpAudioInterface::A2dpAudioInterface() :
-    mOutput(0)
+//AudioHardwareInterface* A2dpAudioInterface::createA2dpInterface()
+//{
+//    AudioHardwareInterface* hw = 0;
+//
+//    hw = AudioHardwareInterface::create();
+//    LOGD("new A2dpAudioInterface(hw: %p)", hw);
+//    hw = new A2dpAudioInterface(hw);
+//    return hw;
+//}
+
+A2dpAudioInterface::A2dpAudioInterface(AudioHardwareInterface* hw) :
+    mOutput(0), mHardwareInterface(hw), mBluetoothEnabled(true)
 {
 }
 
 A2dpAudioInterface::~A2dpAudioInterface()
 {
-    delete mOutput;
+    closeOutputStream((AudioStreamOut *)mOutput);
+    delete mHardwareInterface;
 }
 
 status_t A2dpAudioInterface::initCheck()
 {
-    return 0;
+    if (mHardwareInterface == 0) return NO_INIT;
+    return mHardwareInterface->initCheck();
 }
 
 AudioStreamOut* A2dpAudioInterface::openOutputStream(
-        int format, int channelCount, uint32_t sampleRate, status_t *status)
+        uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status)
 {
-    LOGD("A2dpAudioInterface::openOutputStream %d, %d, %d\n", format, channelCount, sampleRate);
+    if (!AudioSystem::isA2dpDevice((AudioSystem::audio_devices)devices)) {
+        LOGV("A2dpAudioInterface::openOutputStream() open HW device: %x", devices);
+        return mHardwareInterface->openOutputStream(devices, format, channels, sampleRate, status);
+    }
+
     status_t err = 0;
 
     // only one output stream allowed
@@ -59,71 +75,127 @@
 
     // create new output stream
     A2dpAudioStreamOut* out = new A2dpAudioStreamOut();
-    if ((err = out->set(format, channelCount, sampleRate)) == NO_ERROR) {
+    if ((err = out->set(devices, format, channels, sampleRate)) == NO_ERROR) {
         mOutput = out;
+        mOutput->setBluetoothEnabled(mBluetoothEnabled);
     } else {
         delete out;
     }
-    
+
     if (status)
         *status = err;
     return mOutput;
 }
 
+void A2dpAudioInterface::closeOutputStream(AudioStreamOut* out) {
+    if (mOutput == 0 || mOutput != out) {
+        LOGW("Attempt to close invalid output stream");
+    }
+    else {
+        delete mOutput;
+        mOutput = 0;
+    }
+}
+
+
 AudioStreamIn* A2dpAudioInterface::openInputStream(
-        int inputSource, int format, int channelCount, uint32_t sampleRate,
-        status_t *status, AudioSystem::audio_in_acoustics acoustics)
+        uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status,
+        AudioSystem::audio_in_acoustics acoustics)
 {
-    if (status)
-        *status = -1;
-    return NULL;
+    return mHardwareInterface->openInputStream(devices, format, channels, sampleRate, status, acoustics);
+}
+
+void A2dpAudioInterface::closeInputStream(AudioStreamIn* in)
+{
+    return mHardwareInterface->closeInputStream(in);
+}
+
+status_t A2dpAudioInterface::setMode(int mode)
+{
+    return mHardwareInterface->setMode(mode);
 }
 
 status_t A2dpAudioInterface::setMicMute(bool state)
 {
-    return 0;
+    return mHardwareInterface->setMicMute(state);
 }
 
 status_t A2dpAudioInterface::getMicMute(bool* state)
 {
-    return 0;
+    return mHardwareInterface->getMicMute(state);
 }
 
-status_t A2dpAudioInterface::setParameter(const char *key, const char *value)
+status_t A2dpAudioInterface::setParameters(const String8& keyValuePairs)
 {
-    LOGD("setParameter %s,%s\n", key, value);
+    AudioParameter param = AudioParameter(keyValuePairs);
+    String8 value;
+    String8 key;
+    status_t status = NO_ERROR;
 
-    if (!key || !value)
-        return -EINVAL;
+    LOGV("setParameters() %s", keyValuePairs.string());
 
-    if (strcmp(key, "a2dp_sink_address") == 0) {
-        return mOutput->setAddress(value);
-    }
-    if (strcmp(key, "bluetooth_enabled") == 0) {
-        mOutput->setBluetoothEnabled(strcmp(value, "true") == 0);
+    key = "bluetooth_enabled";
+    if (param.get(key, value) == NO_ERROR) {
+        mBluetoothEnabled = (value == "true");
+        if (mOutput) {
+            mOutput->setBluetoothEnabled(mBluetoothEnabled);
+        }
+        param.remove(key);
     }
 
-    return 0;
+    if (param.size()) {
+        status_t hwStatus = mHardwareInterface->setParameters(param.toString());
+        if (status == NO_ERROR) {
+            status = hwStatus;
+        }
+    }
+
+    return status;
+}
+
+String8 A2dpAudioInterface::getParameters(const String8& keys)
+{
+    AudioParameter param = AudioParameter(keys);
+    AudioParameter a2dpParam = AudioParameter();
+    String8 value;
+    String8 key;
+
+    key = "bluetooth_enabled";
+    if (param.get(key, value) == NO_ERROR) {
+        value = mBluetoothEnabled ? "true" : "false";
+        a2dpParam.add(key, value);
+        param.remove(key);
+    }
+
+    String8 keyValuePairs  = a2dpParam.toString();
+
+    if (param.size()) {
+        keyValuePairs += ";";
+        keyValuePairs += mHardwareInterface->getParameters(param.toString());
+    }
+
+    LOGV("getParameters() %s", keyValuePairs.string());
+    return keyValuePairs;
+}
+
+size_t A2dpAudioInterface::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
+{
+    return mHardwareInterface->getInputBufferSize(sampleRate, format, channelCount);
 }
 
 status_t A2dpAudioInterface::setVoiceVolume(float v)
 {
-    return 0;
+    return mHardwareInterface->setVoiceVolume(v);
 }
 
 status_t A2dpAudioInterface::setMasterVolume(float v)
 {
-    return 0;
-}
-
-status_t A2dpAudioInterface::doRouting()
-{
-    return 0;
+    return mHardwareInterface->setMasterVolume(v);
 }
 
 status_t A2dpAudioInterface::dump(int fd, const Vector<String16>& args)
 {
-    return 0;
+    return mHardwareInterface->dumpState(fd, args);
 }
 
 // ----------------------------------------------------------------------------
@@ -132,7 +204,7 @@
     mFd(-1), mStandby(true), mStartCount(0), mRetryCount(0), mData(NULL),
     // assume BT enabled to start, this is safe because its only the
     // enabled->disabled transition we are worried about
-    mBluetoothEnabled(true)
+    mBluetoothEnabled(true), mDevice(0)
 {
     // use any address by default
     strcpy(mA2dpAddress, "00:00:00:00:00:00");
@@ -140,27 +212,43 @@
 }
 
 status_t A2dpAudioInterface::A2dpAudioStreamOut::set(
-        int format, int channels, uint32_t rate)
+        uint32_t device, int *pFormat, uint32_t *pChannels, uint32_t *pRate)
 {
-    LOGD("A2dpAudioStreamOut::set %d, %d, %d\n", format, channels, rate);
+    int lFormat = pFormat ? *pFormat : 0;
+    uint32_t lChannels = pChannels ? *pChannels : 0;
+    uint32_t lRate = pRate ? *pRate : 0;
+
+    LOGD("A2dpAudioStreamOut::set %x, %d, %d, %d\n", device, lFormat, lChannels, lRate);
 
     // fix up defaults
-    if (format == 0) format = AudioSystem::PCM_16_BIT;
-    if (channels == 0) channels = channelCount();
-    if (rate == 0) rate = sampleRate();
+    if (lFormat == 0) lFormat = format();
+    if (lChannels == 0) lChannels = channels();
+    if (lRate == 0) lRate = sampleRate();
 
     // check values
-    if ((format != AudioSystem::PCM_16_BIT) ||
-            (channels != channelCount()) ||
-            (rate != sampleRate()))
+    if ((lFormat != format()) ||
+            (lChannels != channels()) ||
+            (lRate != sampleRate())){
+        if (pFormat) *pFormat = format();
+        if (pChannels) *pChannels = channels();
+        if (pRate) *pRate = sampleRate();
         return BAD_VALUE;
+    }
 
+    if (pFormat) *pFormat = lFormat;
+    if (pChannels) *pChannels = lChannels;
+    if (pRate) *pRate = lRate;
+
+    mDevice = device;
     return NO_ERROR;
 }
 
 A2dpAudioInterface::A2dpAudioStreamOut::~A2dpAudioStreamOut()
 {
+    LOGV("A2dpAudioStreamOut destructor");
+    standby();
     close();
+    LOGV("A2dpAudioStreamOut destructor returning from close()");
 }
 
 ssize_t A2dpAudioInterface::A2dpAudioStreamOut::write(const void* buffer, size_t bytes)
@@ -230,6 +318,59 @@
     return result;
 }
 
+status_t A2dpAudioInterface::A2dpAudioStreamOut::setParameters(const String8& keyValuePairs)
+{
+    AudioParameter param = AudioParameter(keyValuePairs);
+    String8 value;
+    String8 key = String8("a2dp_sink_address");
+    status_t status = NO_ERROR;
+    int device;
+    LOGV("A2dpAudioStreamOut::setParameters() %s", keyValuePairs.string());
+
+    if (param.get(key, value) == NO_ERROR) {
+        if (value.length() != strlen("00:00:00:00:00:00")) {
+            status = BAD_VALUE;
+        } else {
+            setAddress(value.string());
+        }
+        param.remove(key);
+    }
+    key = AudioParameter::keyRouting;
+    if (param.getInt(key, device) == NO_ERROR) {
+        if (AudioSystem::isA2dpDevice((AudioSystem::audio_devices)device)) {
+            mDevice = device;
+            status = NO_ERROR;
+        } else {
+            status = BAD_VALUE;
+        }
+        param.remove(key);
+    }
+
+    if (param.size()) {
+        status = BAD_VALUE;
+    }
+    return status;
+}
+
+String8 A2dpAudioInterface::A2dpAudioStreamOut::getParameters(const String8& keys)
+{
+    AudioParameter param = AudioParameter(keys);
+    String8 value;
+    String8 key = String8("a2dp_sink_address");
+
+    if (param.get(key, value) == NO_ERROR) {
+        value = mA2dpAddress;
+        param.add(key, value);
+    }
+    key = AudioParameter::keyRouting;
+    if (param.get(key, value) == NO_ERROR) {
+        param.addInt(key, (int)mDevice);
+    }
+
+    LOGV("A2dpAudioStreamOut::getParameters() %s", param.toString().string());
+    return param.toString();
+}
+
 status_t A2dpAudioInterface::A2dpAudioStreamOut::setAddress(const char* address)
 {
     Mutex::Autolock lock(mLock);
@@ -260,12 +401,14 @@
 status_t A2dpAudioInterface::A2dpAudioStreamOut::close()
 {
     Mutex::Autolock lock(mLock);
+    LOGV("A2dpAudioStreamOut::close() calling close_l()");
     return close_l();
 }
 
 status_t A2dpAudioInterface::A2dpAudioStreamOut::close_l()
 {
     if (mData) {
+        LOGV("A2dpAudioStreamOut::close_l() calling a2dp_cleanup(mData)");
         a2dp_cleanup(mData);
         mData = NULL;
     }
@@ -277,5 +420,4 @@
     return NO_ERROR;
 }
 
-
 }; // namespace android
diff --git a/libs/audioflinger/A2dpAudioInterface.h b/libs/audioflinger/A2dpAudioInterface.h
index 091e775..d6709e2 100644
--- a/libs/audioflinger/A2dpAudioInterface.h
+++ b/libs/audioflinger/A2dpAudioInterface.h
@@ -32,38 +32,44 @@
     class A2dpAudioStreamOut;
 
 public:
-                        A2dpAudioInterface();
+                        A2dpAudioInterface(AudioHardwareInterface* hw);
     virtual             ~A2dpAudioInterface();
     virtual status_t    initCheck();
 
     virtual status_t    setVoiceVolume(float volume);
     virtual status_t    setMasterVolume(float volume);
 
+    virtual status_t    setMode(int mode);
+
     // mic mute
     virtual status_t    setMicMute(bool state);
     virtual status_t    getMicMute(bool* state);
 
-    // Temporary interface, do not use
-    // TODO: Replace with a more generic key:value get/set mechanism
-    virtual status_t    setParameter(const char *key, const char *value);
+    virtual status_t    setParameters(const String8& keyValuePairs);
+    virtual String8     getParameters(const String8& keys);
+
+    virtual size_t      getInputBufferSize(uint32_t sampleRate, int format, int channelCount);
 
     // create I/O streams
     virtual AudioStreamOut* openOutputStream(
-                                int format=0,
-                                int channelCount=0,
-                                uint32_t sampleRate=0,
+                                uint32_t devices,
+                                int *format=0,
+                                uint32_t *channels=0,
+                                uint32_t *sampleRate=0,
                                 status_t *status=0);
+    virtual    void        closeOutputStream(AudioStreamOut* out);
 
     virtual AudioStreamIn* openInputStream(
-                                int inputSource,
-                                int format,
-                                int channelCount,
-                                uint32_t sampleRate,
+                                uint32_t devices,
+                                int *format,
+                                uint32_t *channels,
+                                uint32_t *sampleRate,
                                 status_t *status,
                                 AudioSystem::audio_in_acoustics acoustics);
+    virtual    void        closeInputStream(AudioStreamIn* in);
+//    static AudioHardwareInterface* createA2dpInterface();
 
 protected:
-    virtual status_t    doRouting();
     virtual status_t    dump(int fd, const Vector<String16>& args);
 
 private:
@@ -71,19 +77,22 @@
     public:
                             A2dpAudioStreamOut();
         virtual             ~A2dpAudioStreamOut();
-                status_t    set(int format,
-                                int channelCount,
-                                uint32_t sampleRate);
+                status_t    set(uint32_t device,
+                                int *pFormat,
+                                uint32_t *pChannels,
+                                uint32_t *pRate);
         virtual uint32_t    sampleRate() const { return 44100; }
         // SBC codec wants a multiple of 512
         virtual size_t      bufferSize() const { return 512 * 20; }
-        virtual int         channelCount() const { return 2; }
+        virtual uint32_t    channels() const { return AudioSystem::CHANNEL_OUT_STEREO; }
         virtual int         format() const { return AudioSystem::PCM_16_BIT; }
         virtual uint32_t    latency() const { return ((1000*bufferSize())/frameSize())/sampleRate() + 200; }
-        virtual status_t    setVolume(float volume) { return INVALID_OPERATION; }
+        virtual status_t    setVolume(float left, float right) { return INVALID_OPERATION; }
         virtual ssize_t     write(const void* buffer, size_t bytes);
                 status_t    standby();
         virtual status_t    dump(int fd, const Vector<String16>& args);
+        virtual status_t    setParameters(const String8& keyValuePairs);
+        virtual String8     getParameters(const String8& keys);
 
     private:
         friend class A2dpAudioInterface;
@@ -102,11 +111,18 @@
                 void*       mData;
                 Mutex       mLock;
                 bool        mBluetoothEnabled;
+                uint32_t    mDevice;
     };
 
+    friend class A2dpAudioStreamOut;
+
     A2dpAudioStreamOut*     mOutput;
+    AudioHardwareInterface  *mHardwareInterface;
+    char        mA2dpAddress[20];
+    bool        mBluetoothEnabled;
 };
 
+
 // ----------------------------------------------------------------------------
 
 }; // namespace android
diff --git a/libs/audioflinger/Android.mk b/libs/audioflinger/Android.mk
index 50d516b..c10e02b 100644
--- a/libs/audioflinger/Android.mk
+++ b/libs/audioflinger/Android.mk
@@ -1,16 +1,30 @@
 LOCAL_PATH:= $(call my-dir)
 
+#AUDIO_POLICY_TEST := true
+#ENABLE_AUDIO_DUMP := true
+
 include $(CLEAR_VARS)
 
+
+ifeq ($(AUDIO_POLICY_TEST),true)
+  ENABLE_AUDIO_DUMP := true
+endif
+
+
 LOCAL_SRC_FILES:= \
     AudioHardwareGeneric.cpp \
     AudioHardwareStub.cpp \
-    AudioDumpInterface.cpp \
     AudioHardwareInterface.cpp
 
+ifeq ($(ENABLE_AUDIO_DUMP),true)
+  LOCAL_SRC_FILES += AudioDumpInterface.cpp
+  LOCAL_CFLAGS += -DENABLE_AUDIO_DUMP
+endif
+
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
     libutils \
+	libbinder \
     libmedia \
     libhardware_legacy
 
@@ -20,8 +34,44 @@
 
 LOCAL_MODULE:= libaudiointerface
 
+ifeq ($(BOARD_HAVE_BLUETOOTH),true)
+  LOCAL_SRC_FILES += A2dpAudioInterface.cpp
+  LOCAL_SHARED_LIBRARIES += liba2dp
+  LOCAL_CFLAGS += -DWITH_BLUETOOTH -DWITH_A2DP
+  LOCAL_C_INCLUDES += $(call include-path-for, bluez)
+endif
+
 include $(BUILD_STATIC_LIBRARY)
 
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:=               \
+    AudioPolicyManagerGeneric.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+    libcutils \
+    libutils \
+    libmedia
+
+ifeq ($(TARGET_SIMULATOR),true)
+ LOCAL_LDLIBS += -ldl
+else
+ LOCAL_SHARED_LIBRARIES += libdl
+endif
+
+LOCAL_MODULE:= libaudiopolicygeneric
+
+ifeq ($(BOARD_HAVE_BLUETOOTH),true)
+  LOCAL_CFLAGS += -DWITH_A2DP
+endif
+
+ifeq ($(AUDIO_POLICY_TEST),true)
+  LOCAL_CFLAGS += -DAUDIO_POLICY_TEST
+endif
+
+include $(BUILD_SHARED_LIBRARY)
+
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:=               \
@@ -29,28 +79,44 @@
     AudioMixer.cpp.arm          \
     AudioResampler.cpp.arm      \
     AudioResamplerSinc.cpp.arm  \
-    AudioResamplerCubic.cpp.arm
+    AudioResamplerCubic.cpp.arm \
+    AudioPolicyService.cpp
 
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
     libutils \
+	libbinder \
     libmedia \
-    libhardware_legacy
+    libhardware_legacy \
+    libaudiopolicygeneric
 
 ifeq ($(strip $(BOARD_USES_GENERIC_AUDIO)),true)
   LOCAL_STATIC_LIBRARIES += libaudiointerface
+  LOCAL_CFLAGS += -DGENERIC_AUDIO
 else
-  LOCAL_SHARED_LIBRARIES += libaudio
+  LOCAL_SHARED_LIBRARIES += libaudio libaudiopolicy
+endif
+
+ifeq ($(TARGET_SIMULATOR),true)
+ LOCAL_LDLIBS += -ldl
+else
+ LOCAL_SHARED_LIBRARIES += libdl
 endif
 
 LOCAL_MODULE:= libaudioflinger
 
 ifeq ($(BOARD_HAVE_BLUETOOTH),true)
-  LOCAL_SRC_FILES += A2dpAudioInterface.cpp
-  LOCAL_SHARED_LIBRARIES += liba2dp
   LOCAL_CFLAGS += -DWITH_BLUETOOTH -DWITH_A2DP
-  LOCAL_C_INCLUDES += $(call include-path-for, bluez-libs)
-  LOCAL_C_INCLUDES += $(call include-path-for, bluez-utils)
+endif
+
+ifeq ($(AUDIO_POLICY_TEST),true)
+  LOCAL_CFLAGS += -DAUDIO_POLICY_TEST
+endif
+
+ifeq ($(TARGET_SIMULATOR),true)
+	ifeq ($(HOST_OS),linux)
+		LOCAL_LDLIBS += -lrt -lpthread
+	endif
 endif
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/libs/audioflinger/AudioDumpInterface.cpp b/libs/audioflinger/AudioDumpInterface.cpp
index b4940cb..87bb014 100644
--- a/libs/audioflinger/AudioDumpInterface.cpp
+++ b/libs/audioflinger/AudioDumpInterface.cpp
@@ -16,6 +16,7 @@
 */
 
 #define LOG_TAG "AudioFlingerDump"
+//#define LOG_NDEBUG 0
 
 #include <stdint.h>
 #include <sys/types.h>
@@ -28,68 +29,209 @@
 
 namespace android {
 
-bool gFirst = true;       // true if first write after a standby
-
 // ----------------------------------------------------------------------------
 
 AudioDumpInterface::AudioDumpInterface(AudioHardwareInterface* hw)
+    : mFirstHwOutput(true), mPolicyCommands(String8("")), mFileName(String8(""))
 {
     if(hw == 0) {
         LOGE("Dump construct hw = 0");
     }
     mFinalInterface = hw;
-    mStreamOut = 0;
+    LOGV("Constructor %p, mFinalInterface %p", this, mFinalInterface);
 }
 
 
 AudioDumpInterface::~AudioDumpInterface()
 {
+    for (size_t i = 0; i < mOutputs.size(); i++) {
+        closeOutputStream((AudioStreamOut *)mOutputs[i]);
+    }
     if(mFinalInterface) delete mFinalInterface;
-    if(mStreamOut) delete mStreamOut;
 }
 
 
 AudioStreamOut* AudioDumpInterface::openOutputStream(
-        int format, int channelCount, uint32_t sampleRate, status_t *status)
+        uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status)
 {
-    AudioStreamOut* outFinal = mFinalInterface->openOutputStream(format, channelCount, sampleRate, status);
+    AudioStreamOut* outFinal = NULL;
+    int lFormat = AudioSystem::PCM_16_BIT;
+    uint32_t lChannels = AudioSystem::CHANNEL_OUT_STEREO;
+    uint32_t lRate = 44100;
 
-    if(outFinal) {
-        mStreamOut =  new AudioStreamOutDump(outFinal);
-        return mStreamOut;
+
+    if (AudioSystem::isA2dpDevice((AudioSystem::audio_devices)devices) || mFirstHwOutput) {
+        outFinal = mFinalInterface->openOutputStream(devices, format, channels, sampleRate, status);
+        if (outFinal != 0) {
+            lFormat = outFinal->format();
+            lChannels = outFinal->channels();
+            lRate = outFinal->sampleRate();
+            if (!AudioSystem::isA2dpDevice((AudioSystem::audio_devices)devices)) {
+                mFirstHwOutput = false;
+            }
+        }
     } else {
-        LOGE("Dump outFinal=0");
-        return 0;
+        if (format != 0 && *format != 0) lFormat = *format;
+        if (channels != 0 && *channels != 0) lChannels = *channels;
+        if (sampleRate != 0 && *sampleRate != 0) lRate = *sampleRate;
+        if (status) *status = NO_ERROR;
     }
+    LOGV("openOutputStream(), outFinal %p", outFinal);
+
+    AudioStreamOutDump *dumOutput = new AudioStreamOutDump(this, mOutputs.size(), outFinal,
+            devices, lFormat, lChannels, lRate);
+    mOutputs.add(dumOutput);
+
+    return dumOutput;
 }
 
+void AudioDumpInterface::closeOutputStream(AudioStreamOut* out)
+{
+    AudioStreamOutDump *dumpOut = (AudioStreamOutDump *)out;
+
+    if (mOutputs.indexOf(dumpOut) < 0) {
+        LOGW("Attempt to close invalid output stream");
+        return;
+    }
+    dumpOut->standby();
+    if (dumpOut->finalStream() != NULL) {
+        mFinalInterface->closeOutputStream(dumpOut->finalStream());
+    }
+
+    mOutputs.remove(dumpOut);
+    delete dumpOut;
+}
+
+AudioStreamIn* AudioDumpInterface::openInputStream(uint32_t devices, int *format, uint32_t *channels,
+        uint32_t *sampleRate, status_t *status, AudioSystem::audio_in_acoustics acoustics)
+{
+    AudioStreamIn* inFinal = NULL;
+    int lFormat = AudioSystem::PCM_16_BIT;
+    uint32_t lChannels = AudioSystem::CHANNEL_IN_MONO;
+    uint32_t lRate = 8000;
+
+
+    if (mInputs.size() == 0) {
+        inFinal = mFinalInterface->openInputStream(devices, format, channels, sampleRate, status, acoustics);
+        if (inFinal == 0) return 0;
+
+        lFormat = inFinal->format();
+        lChannels = inFinal->channels();
+        lRate = inFinal->sampleRate();
+    } else {
+        if (format != 0 && *format != 0) lFormat = *format;
+        if (channels != 0 && *channels != 0) lChannels = *channels;
+        if (sampleRate != 0 && *sampleRate != 0) lRate = *sampleRate;
+        if (status) *status = NO_ERROR;
+    }
+    LOGV("openInputStream(), inFinal %p", inFinal);
+
+    AudioStreamInDump *dumInput = new AudioStreamInDump(this, mInputs.size(), inFinal,
+            devices, lFormat, lChannels, lRate);
+    mInputs.add(dumInput);
+
+    return dumInput;
+}
+void AudioDumpInterface::closeInputStream(AudioStreamIn* in)
+{
+    AudioStreamInDump *dumpIn = (AudioStreamInDump *)in;
+
+    if (mInputs.indexOf(dumpIn) < 0) {
+        LOGW("Attempt to close invalid input stream");
+        return;
+    }
+    dumpIn->standby();
+    if (dumpIn->finalStream() != NULL) {
+        mFinalInterface->closeInputStream(dumpIn->finalStream());
+    }
+
+    mInputs.remove(dumpIn);
+    delete dumpIn;
+}
+
+
+status_t AudioDumpInterface::setParameters(const String8& keyValuePairs)
+{
+    AudioParameter param = AudioParameter(keyValuePairs);
+    String8 value;
+    int valueInt;
+    LOGV("setParameters %s", keyValuePairs.string());
+
+    if (param.get(String8("test_cmd_file_name"), value) == NO_ERROR) {
+        mFileName = value;
+        return NO_ERROR;
+    }
+    if (param.get(String8("test_cmd_policy"), value) == NO_ERROR) {
+        Mutex::Autolock _l(mLock);
+        param.remove(String8("test_cmd_policy"));
+        mPolicyCommands = param.toString();
+        LOGV("test_cmd_policy command %s written", mPolicyCommands.string());
+        return NO_ERROR;
+    }
+
+    if (mFinalInterface != 0 ) return mFinalInterface->setParameters(keyValuePairs);
+    return NO_ERROR;
+}
+
+String8 AudioDumpInterface::getParameters(const String8& keys)
+{
+    AudioParameter param = AudioParameter(keys);
+    String8 value;
+
+//    LOGV("getParameters %s", keys.string());
+
+    if (param.get(String8("test_cmd_file_name"), value) == NO_ERROR) {
+        return mFileName;
+    }
+    if (param.get(String8("test_cmd_policy"), value) == NO_ERROR) {
+        Mutex::Autolock _l(mLock);
+//        LOGV("test_cmd_policy command %s read", mPolicyCommands.string());
+        return mPolicyCommands;
+    }
+
+    if (mFinalInterface != 0 ) return mFinalInterface->getParameters(keys);
+    return String8("");
+}
+
+
 // ----------------------------------------------------------------------------
 
-AudioStreamOutDump::AudioStreamOutDump( AudioStreamOut* finalStream)
+AudioStreamOutDump::AudioStreamOutDump(AudioDumpInterface *interface,
+                                        int id,
+                                        AudioStreamOut* finalStream,
+                                        uint32_t devices,
+                                        int format,
+                                        uint32_t channels,
+                                        uint32_t sampleRate)
+    : mInterface(interface), mId(id),
+      mSampleRate(sampleRate), mFormat(format), mChannels(channels), mLatency(0), mDevice(devices),
+      mBufferSize(1024), mFinalStream(finalStream), mOutFile(0), mFileCount(0)
 {
-    mFinalStream = finalStream;
-    mOutFile = 0;
+    LOGV("AudioStreamOutDump Constructor %p, mInterface %p, mFinalStream %p", this, mInterface, mFinalStream);
 }
 
 
 AudioStreamOutDump::~AudioStreamOutDump()
 {
     Close();
-    delete mFinalStream;
 }
 
 ssize_t AudioStreamOutDump::write(const void* buffer, size_t bytes)
 {
     ssize_t ret;
 
-    ret = mFinalStream->write(buffer, bytes);
-    if(!mOutFile && gFirst) {
-        gFirst = false;
-        // check if dump file exist
-        mOutFile = fopen(FLINGER_DUMP_NAME, "r");
-        if(mOutFile) {
-            fclose(mOutFile);
-            mOutFile = fopen(FLINGER_DUMP_NAME, "ab");
+    if (mFinalStream) {
+        ret = mFinalStream->write(buffer, bytes);
+    } else {
+        usleep((bytes * 1000000) / frameSize() / sampleRate());
+        ret = bytes;
+    }
+    if(!mOutFile) {
+        if (mInterface->fileName() != "") {
+            char name[255];
+            sprintf(name, "%s_%d_%d.pcm", mInterface->fileName().string(), mId, ++mFileCount);
+            mOutFile = fopen(name, "wb");
+            LOGV("Opening dump file %s, fh %p", name, mOutFile);
         }
     }
     if (mOutFile) {
@@ -100,13 +242,65 @@
 
 status_t AudioStreamOutDump::standby()
 {
+    LOGV("AudioStreamOutDump standby(), mOutFile %p, mFinalStream %p", mOutFile, mFinalStream);
+
     Close();
-    gFirst = true;
-    return mFinalStream->standby();
+    if (mFinalStream != 0 ) return mFinalStream->standby();
+    return NO_ERROR;
 }
 
+uint32_t AudioStreamOutDump::sampleRate() const
+{
+    if (mFinalStream != 0 ) return mFinalStream->sampleRate();
+    return mSampleRate;
+}
 
-void AudioStreamOutDump::Close(void)
+size_t AudioStreamOutDump::bufferSize() const
+{
+    if (mFinalStream != 0 ) return mFinalStream->bufferSize();
+    return mBufferSize;
+}
+
+uint32_t AudioStreamOutDump::channels() const
+{
+    if (mFinalStream != 0 ) return mFinalStream->channels();
+    return mChannels;
+}
+int AudioStreamOutDump::format() const
+{
+    if (mFinalStream != 0 ) return mFinalStream->format();
+    return mFormat;
+}
+uint32_t AudioStreamOutDump::latency() const
+{
+    if (mFinalStream != 0 ) return mFinalStream->latency();
+    return 0;
+}
+status_t AudioStreamOutDump::setVolume(float left, float right)
+{
+    if (mFinalStream != 0 ) return mFinalStream->setVolume(left, right);
+    return NO_ERROR;
+}
+status_t AudioStreamOutDump::setParameters(const String8& keyValuePairs)
+{
+    LOGV("AudioStreamOutDump::setParameters()");
+    if (mFinalStream != 0 ) return mFinalStream->setParameters(keyValuePairs);
+    return NO_ERROR;
+}
+String8 AudioStreamOutDump::getParameters(const String8& keys)
+{
+    String8 result = String8("");
+    if (mFinalStream != 0 ) result = mFinalStream->getParameters(keys);
+    return result;
+}
+
+status_t AudioStreamOutDump::dump(int fd, const Vector<String16>& args)
+{
+    if (mFinalStream != 0 ) return mFinalStream->dump(fd, args);
+    return NO_ERROR;
+}
+
+void AudioStreamOutDump::Close()
 {
     if(mOutFile) {
         fclose(mOutFile);
@@ -114,4 +308,140 @@
     }
 }
 
+// ----------------------------------------------------------------------------
+
+AudioStreamInDump::AudioStreamInDump(AudioDumpInterface *interface,
+                                        int id,
+                                        AudioStreamIn* finalStream,
+                                        uint32_t devices,
+                                        int format,
+                                        uint32_t channels,
+                                        uint32_t sampleRate)
+    : mInterface(interface), mId(id),
+      mSampleRate(sampleRate), mFormat(format), mChannels(channels), mDevice(devices),
+      mBufferSize(1024), mFinalStream(finalStream), mInFile(0)
+{
+    LOGV("AudioStreamInDump Constructor %p, mInterface %p, mFinalStream %p", this, mInterface, mFinalStream);
+}
+
+
+AudioStreamInDump::~AudioStreamInDump()
+{
+    Close();
+}
+
+ssize_t AudioStreamInDump::read(void* buffer, ssize_t bytes)
+{
+    if (mFinalStream) {
+        return mFinalStream->read(buffer, bytes);
+    }
+
+    usleep((bytes * 1000000) / frameSize() / sampleRate());
+
+    if(!mInFile) {
+        char name[255];
+        strcpy(name, "/sdcard/music/sine440");
+        if (channels() == AudioSystem::CHANNEL_IN_MONO) {
+            strcat(name, "_mo");
+        } else {
+            strcat(name, "_st");
+        }
+        if (format() == AudioSystem::PCM_16_BIT) {
+            strcat(name, "_16b");
+        } else {
+            strcat(name, "_8b");
+        }
+        if (sampleRate() < 16000) {
+            strcat(name, "_8k");
+        } else if (sampleRate() < 32000) {
+            strcat(name, "_22k");
+        } else if (sampleRate() < 48000) {
+            strcat(name, "_44k");
+        } else {
+            strcat(name, "_48k");
+        }
+        strcat(name, ".wav");
+        mInFile = fopen(name, "rb");
+        LOGV("Opening dump file %s, fh %p", name, mInFile);
+        if (mInFile) {
+            fseek(mInFile, AUDIO_DUMP_WAVE_HDR_SIZE, SEEK_SET);
+        }
+
+    }
+    if (mInFile) {
+        ssize_t bytesRead = fread(buffer, bytes, 1, mInFile);
+        if (bytesRead != bytes) {
+            fseek(mInFile, AUDIO_DUMP_WAVE_HDR_SIZE, SEEK_SET);
+            fread((uint8_t *)buffer+bytesRead, bytes-bytesRead, 1, mInFile);
+        }
+    }
+    return bytes;
+}
+
+status_t AudioStreamInDump::standby()
+{
+    LOGV("AudioStreamInDump standby(), mInFile %p, mFinalStream %p", mInFile, mFinalStream);
+
+    Close();
+    if (mFinalStream != 0 ) return mFinalStream->standby();
+    return NO_ERROR;
+}
+
+status_t AudioStreamInDump::setGain(float gain)
+{
+    if (mFinalStream != 0 ) return mFinalStream->setGain(gain);
+    return NO_ERROR;
+}
+
+uint32_t AudioStreamInDump::sampleRate() const
+{
+    if (mFinalStream != 0 ) return mFinalStream->sampleRate();
+    return mSampleRate;
+}
+
+size_t AudioStreamInDump::bufferSize() const
+{
+    if (mFinalStream != 0 ) return mFinalStream->bufferSize();
+    return mBufferSize;
+}
+
+uint32_t AudioStreamInDump::channels() const
+{
+    if (mFinalStream != 0 ) return mFinalStream->channels();
+    return mChannels;
+}
+
+int AudioStreamInDump::format() const
+{
+    if (mFinalStream != 0 ) return mFinalStream->format();
+    return mFormat;
+}
+
+status_t AudioStreamInDump::setParameters(const String8& keyValuePairs)
+{
+    LOGV("AudioStreamInDump::setParameters()");
+    if (mFinalStream != 0 ) return mFinalStream->setParameters(keyValuePairs);
+    return NO_ERROR;
+}
+
+String8 AudioStreamInDump::getParameters(const String8& keys)
+{
+    String8 result = String8("");
+    if (mFinalStream != 0 ) result = mFinalStream->getParameters(keys);
+    return result;
+}
+
+status_t AudioStreamInDump::dump(int fd, const Vector<String16>& args)
+{
+    if (mFinalStream != 0 ) return mFinalStream->dump(fd, args);
+    return NO_ERROR;
+}
+
+void AudioStreamInDump::Close()
+{
+    if(mInFile) {
+        fclose(mInFile);
+        mInFile = 0;
+    }
+}
 }; // namespace android
diff --git a/libs/audioflinger/AudioDumpInterface.h b/libs/audioflinger/AudioDumpInterface.h
index b72c94e..4de4a16 100644
--- a/libs/audioflinger/AudioDumpInterface.h
+++ b/libs/audioflinger/AudioDumpInterface.h
@@ -20,35 +20,94 @@
 
 #include <stdint.h>
 #include <sys/types.h>
+#include <utils/String8.h>
+#include <utils/SortedVector.h>
 
 #include <hardware_legacy/AudioHardwareBase.h>
 
 namespace android {
 
-#define FLINGER_DUMP_NAME "/data/FlingerOut.pcm" // name of file used for dump
+#define AUDIO_DUMP_WAVE_HDR_SIZE 44
+
+class AudioDumpInterface;
 
 class AudioStreamOutDump : public AudioStreamOut {
 public:
-                        AudioStreamOutDump( AudioStreamOut* FinalStream);
+                        AudioStreamOutDump(AudioDumpInterface *interface,
+                                            int id,
+                                            AudioStreamOut* finalStream,
+                                            uint32_t devices,
+                                            int format,
+                                            uint32_t channels,
+                                            uint32_t sampleRate);
                         ~AudioStreamOutDump();
-                        virtual ssize_t     write(const void* buffer, size_t bytes);
 
-    virtual uint32_t    sampleRate() const { return mFinalStream->sampleRate(); }
-    virtual size_t      bufferSize() const { return mFinalStream->bufferSize(); }
-    virtual int         channelCount() const { return mFinalStream->channelCount(); }
-    virtual int         format() const { return mFinalStream->format(); }
-    virtual uint32_t    latency() const { return mFinalStream->latency(); }
-    virtual status_t    setVolume(float volume)
-                            { return mFinalStream->setVolume(volume); }
+    virtual ssize_t     write(const void* buffer, size_t bytes);
+    virtual uint32_t    sampleRate() const;
+    virtual size_t      bufferSize() const;
+    virtual uint32_t    channels() const;
+    virtual int         format() const;
+    virtual uint32_t    latency() const;
+    virtual status_t    setVolume(float left, float right);
     virtual status_t    standby();
-    virtual status_t    dump(int fd, const Vector<String16>& args) { return mFinalStream->dump(fd, args); }
+    virtual status_t    setParameters(const String8& keyValuePairs);
+    virtual String8     getParameters(const String8& keys);
+    virtual status_t    dump(int fd, const Vector<String16>& args);
     void                Close(void);
+    AudioStreamOut*     finalStream() { return mFinalStream; }
+    uint32_t            device() { return mDevice; }
 
 private:
+    AudioDumpInterface *mInterface;
+    int                  mId;
+    uint32_t mSampleRate;               //
+    uint32_t mFormat;                   //
+    uint32_t mChannels;                 // output configuration
+    uint32_t mLatency;                  //
+    uint32_t mDevice;                   // current device this output is routed to
+    size_t  mBufferSize;
     AudioStreamOut      *mFinalStream;
-    FILE                *mOutFile;     // output file
+    FILE                *mOutFile;      // output file
+    int                 mFileCount;
 };
 
+class AudioStreamInDump : public AudioStreamIn {
+public:
+                        AudioStreamInDump(AudioDumpInterface *interface,
+                                            int id,
+                                            AudioStreamIn* finalStream,
+                                            uint32_t devices,
+                                            int format,
+                                            uint32_t channels,
+                                            uint32_t sampleRate);
+                        ~AudioStreamInDump();
+
+    virtual uint32_t    sampleRate() const;
+    virtual size_t      bufferSize() const;
+    virtual uint32_t    channels() const;
+    virtual int         format() const;
+
+    virtual status_t    setGain(float gain);
+    virtual ssize_t     read(void* buffer, ssize_t bytes);
+    virtual status_t    standby();
+    virtual status_t    setParameters(const String8& keyValuePairs);
+    virtual String8     getParameters(const String8& keys);
+    virtual status_t    dump(int fd, const Vector<String16>& args);
+    void                Close(void);
+    AudioStreamIn*     finalStream() { return mFinalStream; }
+    uint32_t            device() { return mDevice; }
+
+private:
+    AudioDumpInterface *mInterface;
+    int                  mId;
+    uint32_t mSampleRate;               //
+    uint32_t mFormat;                   //
+    uint32_t mChannels;                 // output configuration
+    uint32_t mDevice;                   // current device this output is routed to
+    size_t  mBufferSize;
+    AudioStreamIn      *mFinalStream;
+    FILE                *mInFile;      // output file
+};
 
 class AudioDumpInterface : public AudioHardwareBase
 {
@@ -56,10 +115,13 @@
 public:
                         AudioDumpInterface(AudioHardwareInterface* hw);
     virtual AudioStreamOut* openOutputStream(
-                                int format=0,
-                                int channelCount=0,
-                                uint32_t sampleRate=0,
+                                uint32_t devices,
+                                int *format=0,
+                                uint32_t *channels=0,
+                                uint32_t *sampleRate=0,
                                 status_t *status=0);
+    virtual    void        closeOutputStream(AudioStreamOut* out);
+
     virtual             ~AudioDumpInterface();
 
     virtual status_t    initCheck()
@@ -75,21 +137,25 @@
     virtual status_t    getMicMute(bool* state)
                             {return mFinalInterface->getMicMute(state);}
 
-    virtual status_t    setParameter(const char* key, const char* value)
-                            {return mFinalInterface->setParameter(key, value);}
+    virtual status_t    setParameters(const String8& keyValuePairs);
+    virtual String8     getParameters(const String8& keys);
 
-    virtual AudioStreamIn* openInputStream(int inputSource, int format, int channelCount,
-            uint32_t sampleRate, status_t *status, AudioSystem::audio_in_acoustics acoustics)
-        { return mFinalInterface->openInputStream(inputSource, format, channelCount, sampleRate, status, acoustics); }
+    virtual AudioStreamIn* openInputStream(uint32_t devices, int *format, uint32_t *channels,
+            uint32_t *sampleRate, status_t *status, AudioSystem::audio_in_acoustics acoustics);
+    virtual    void        closeInputStream(AudioStreamIn* in);
 
     virtual status_t    dump(int fd, const Vector<String16>& args) { return mFinalInterface->dumpState(fd, args); }
 
+            String8     fileName() const { return mFileName; }
 protected:
-    virtual status_t    doRouting() {return mFinalInterface->setRouting(mMode, mRoutes[mMode]);}
 
-    AudioHardwareInterface  *mFinalInterface;
-    AudioStreamOutDump      *mStreamOut;
-
+    AudioHardwareInterface          *mFinalInterface;
+    SortedVector<AudioStreamOutDump *>    mOutputs;
+    bool                            mFirstHwOutput;
+    SortedVector<AudioStreamInDump *>    mInputs;
+    Mutex                           mLock;
+    String8                         mPolicyCommands;
+    String8                         mFileName;
 };
 
 }; // namespace android
diff --git a/libs/audioflinger/AudioFlinger.cpp b/libs/audioflinger/AudioFlinger.cpp
index f5bdeda..1336131 100644
--- a/libs/audioflinger/AudioFlinger.cpp
+++ b/libs/audioflinger/AudioFlinger.cpp
@@ -24,10 +24,10 @@
 #include <sys/time.h>
 #include <sys/resource.h>
 
-#include <utils/IServiceManager.h>
+#include <binder/IServiceManager.h>
 #include <utils/Log.h>
-#include <utils/Parcel.h>
-#include <utils/IPCThreadState.h>
+#include <binder/Parcel.h>
+#include <binder/IPCThreadState.h>
 #include <utils/String16.h>
 #include <utils/threads.h>
 
@@ -71,15 +71,9 @@
 static const int8_t kMaxTrackRetries = 50;
 static const int8_t kMaxTrackStartupRetries = 50;
 
-static const int kStartSleepTime = 30000;
-static const int kStopSleepTime = 30000;
-
 static const int kDumpLockRetries = 50;
 static const int kDumpLockSleep = 20000;
 
-// Maximum number of pending buffers allocated by OutputTrack::write()
-static const uint8_t kMaxOutputTrackBuffers = 5;
-
 
 #define AUDIOFLINGER_SECURITY_ENABLED 1
 
@@ -121,131 +115,32 @@
 
 AudioFlinger::AudioFlinger()
     : BnAudioFlinger(),
-        mAudioHardware(0), mA2dpAudioInterface(0), mA2dpEnabled(false), mNotifyA2dpChange(false),
-        mForcedSpeakerCount(0), mA2dpDisableCount(0), mA2dpSuppressed(false), mForcedRoute(0),
-        mRouteRestoreTime(0), mMusicMuteSaved(false)
+        mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false)
 {
     mHardwareStatus = AUDIO_HW_IDLE;
+
     mAudioHardware = AudioHardwareInterface::create();
+
     mHardwareStatus = AUDIO_HW_INIT;
     if (mAudioHardware->initCheck() == NO_ERROR) {
         // open 16-bit output stream for s/w mixer
-        mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
-        status_t status;
-        AudioStreamOut *hwOutput = mAudioHardware->openOutputStream(AudioSystem::PCM_16_BIT, 0, 0, &status);
-        mHardwareStatus = AUDIO_HW_IDLE;
-        if (hwOutput) {
-            mHardwareMixerThread = new MixerThread(this, hwOutput, AudioSystem::AUDIO_OUTPUT_HARDWARE);
-        } else {
-            LOGE("Failed to initialize hardware output stream, status: %d", status);
-        }
-        
-#ifdef WITH_A2DP
-        // Create A2DP interface
-        mA2dpAudioInterface = new A2dpAudioInterface();
-        AudioStreamOut *a2dpOutput = mA2dpAudioInterface->openOutputStream(AudioSystem::PCM_16_BIT, 0, 0, &status);
-        if (a2dpOutput) {
-            mA2dpMixerThread = new MixerThread(this, a2dpOutput, AudioSystem::AUDIO_OUTPUT_A2DP);
-            if (hwOutput) {  
-                uint32_t frameCount = ((a2dpOutput->bufferSize()/a2dpOutput->frameSize()) * hwOutput->sampleRate()) / a2dpOutput->sampleRate();
-                MixerThread::OutputTrack *a2dpOutTrack = new MixerThread::OutputTrack(mA2dpMixerThread,
-                                                            hwOutput->sampleRate(),
-                                                            AudioSystem::PCM_16_BIT,
-                                                            hwOutput->channelCount(),
-                                                            frameCount);
-                mHardwareMixerThread->setOuputTrack(a2dpOutTrack);                
-            }
-        } else {
-            LOGE("Failed to initialize A2DP output stream, status: %d", status);
-        }
-#endif
- 
-        // FIXME - this should come from settings
-        setRouting(AudioSystem::MODE_NORMAL, AudioSystem::ROUTE_SPEAKER, AudioSystem::ROUTE_ALL);
-        setRouting(AudioSystem::MODE_RINGTONE, AudioSystem::ROUTE_SPEAKER, AudioSystem::ROUTE_ALL);
-        setRouting(AudioSystem::MODE_IN_CALL, AudioSystem::ROUTE_EARPIECE, AudioSystem::ROUTE_ALL);
+
         setMode(AudioSystem::MODE_NORMAL);
 
         setMasterVolume(1.0f);
         setMasterMute(false);
-
-        // Start record thread
-        mAudioRecordThread = new AudioRecordThread(mAudioHardware, this);
-        if (mAudioRecordThread != 0) {
-            mAudioRecordThread->run("AudioRecordThread", PRIORITY_URGENT_AUDIO);            
-        }
-     } else {
+    } else {
         LOGE("Couldn't even initialize the stubbed audio hardware!");
     }
 }
 
 AudioFlinger::~AudioFlinger()
 {
-    if (mAudioRecordThread != 0) {
-        mAudioRecordThread->exit();
-        mAudioRecordThread.clear();        
-    }
-    mHardwareMixerThread.clear();
-    delete mAudioHardware;
-    // deleting mA2dpAudioInterface also deletes mA2dpOutput;
-#ifdef WITH_A2DP
-    mA2dpMixerThread.clear();
-    delete mA2dpAudioInterface;
-#endif
+    mRecordThreads.clear();
+    mPlaybackThreads.clear();
 }
 
 
-#ifdef WITH_A2DP
-// setA2dpEnabled_l() must be called with AudioFlinger::mLock held
-void AudioFlinger::setA2dpEnabled_l(bool enable)
-{    
-    SortedVector < sp<MixerThread::Track> > tracks;
-    SortedVector < wp<MixerThread::Track> > activeTracks;
-    
-    LOGV_IF(enable, "set output to A2DP\n");
-    LOGV_IF(!enable, "set output to hardware audio\n");
-
-    // Transfer tracks playing on MUSIC stream from one mixer to the other
-    if (enable) {
-        mHardwareMixerThread->getTracks_l(tracks, activeTracks);
-        mA2dpMixerThread->putTracks_l(tracks, activeTracks);
-    } else {
-        mA2dpMixerThread->getTracks_l(tracks, activeTracks);
-        mHardwareMixerThread->putTracks_l(tracks, activeTracks);
-    }
-    mA2dpEnabled = enable;
-    mNotifyA2dpChange = true;
-    mWaitWorkCV.broadcast();
-}
-
-// checkA2dpEnabledChange_l() must be called with AudioFlinger::mLock held
-void AudioFlinger::checkA2dpEnabledChange_l()
-{
-    if (mNotifyA2dpChange) {
-        // Notify AudioSystem of the A2DP activation/deactivation
-        size_t size = mNotificationClients.size();
-        for (size_t i = 0; i < size; i++) {
-            sp<IBinder> binder = mNotificationClients.itemAt(i).promote();
-            if (binder != NULL) {
-                LOGV("Notifying output change to client %p", binder.get());
-                sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
-                client->a2dpEnabledChanged(mA2dpEnabled);
-            }
-        }
-        mNotifyA2dpChange = false;
-    }
-}
-#endif // WITH_A2DP
-
-bool AudioFlinger::streamForcedToSpeaker(int streamType)
-{
-    // NOTE that streams listed here must not be routed to A2DP by default:
-    // AudioSystem::routedToA2dpOutput(streamType) == false
-    return (streamType == AudioSystem::RING ||
-            streamType == AudioSystem::ALARM ||
-            streamType == AudioSystem::NOTIFICATION ||
-            streamType == AudioSystem::ENFORCED_AUDIBLE);
-}
 
 status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
 {
@@ -275,10 +170,7 @@
     char buffer[SIZE];
     String8 result;
     int hardwareStatus = mHardwareStatus;
-    
-    if (hardwareStatus == AUDIO_HW_IDLE && mHardwareMixerThread->mStandby) {
-        hardwareStatus = AUDIO_HW_STANDBY;
-    }
+
     snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
     result.append(buffer);
     write(fd, result.string(), result.size());
@@ -336,13 +228,16 @@
 
         dumpClients(fd, args);
         dumpInternals(fd, args);
-        mHardwareMixerThread->dump(fd, args);
-#ifdef WITH_A2DP
-        mA2dpMixerThread->dump(fd, args);
-#endif
 
-        // dump record client
-        if (mAudioRecordThread != 0) mAudioRecordThread->dump(fd, args);
+        // dump playback threads
+        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
+            mPlaybackThreads[i]->dump(fd, args);
+        }
+
+        // dump record threads
+        for (size_t i = 0; i < mRecordThreads.size(); i++) {
+            mRecordThreads[i]->dump(fd, args);
+        }
 
         if (mAudioHardware) {
             mAudioHardware->dumpState(fd, args);
@@ -352,6 +247,7 @@
     return NO_ERROR;
 }
 
+
 // IAudioFlinger interface
 
 
@@ -364,9 +260,10 @@
         int frameCount,
         uint32_t flags,
         const sp<IMemory>& sharedBuffer,
+        void *output,
         status_t *status)
 {
-    sp<MixerThread::Track> track;
+    sp<PlaybackThread::Track> track;
     sp<TrackHandle> trackHandle;
     sp<Client> client;
     wp<Client> wclient;
@@ -380,6 +277,12 @@
 
     {
         Mutex::Autolock _l(mLock);
+        PlaybackThread *thread = checkPlaybackThread_l(output);
+        if (thread == NULL) {
+            LOGE("unknown output thread");
+            lStatus = BAD_VALUE;
+            goto Exit;
+        }
 
         wclient = mClients.valueFor(pid);
 
@@ -389,16 +292,8 @@
             client = new Client(this, pid);
             mClients.add(pid, client);
         }
-#ifdef WITH_A2DP
-        if (isA2dpEnabled() && AudioSystem::routedToA2dpOutput(streamType)) {
-            track = mA2dpMixerThread->createTrack_l(client, streamType, sampleRate, format,
-                    channelCount, frameCount, sharedBuffer, &lStatus);            
-        } else 
-#endif
-        {
-            track = mHardwareMixerThread->createTrack_l(client, streamType, sampleRate, format,
-                    channelCount, frameCount, sharedBuffer, &lStatus);            
-        }
+        track = thread->createTrack_l(client, streamType, sampleRate, format,
+                channelCount, frameCount, sharedBuffer, &lStatus);
     }
     if (lStatus == NO_ERROR) {
         trackHandle = new TrackHandle(track);
@@ -413,54 +308,59 @@
     return trackHandle;
 }
 
-uint32_t AudioFlinger::sampleRate(int output) const
+uint32_t AudioFlinger::sampleRate(void *output) const
 {
-#ifdef WITH_A2DP
-     if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
-         return mA2dpMixerThread->sampleRate();
-     }
-#endif
-     return mHardwareMixerThread->sampleRate();
+    Mutex::Autolock _l(mLock);
+    PlaybackThread *thread = checkPlaybackThread_l(output);
+    if (thread == NULL) {
+        LOGW("sampleRate() unknown thread %p", output);
+        return 0;
+    }
+    return thread->sampleRate();
 }
 
-int AudioFlinger::channelCount(int output) const
+int AudioFlinger::channelCount(void *output) const
 {
-#ifdef WITH_A2DP
-     if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
-         return mA2dpMixerThread->channelCount();
-     }
-#endif
-     return mHardwareMixerThread->channelCount();
+    Mutex::Autolock _l(mLock);
+    PlaybackThread *thread = checkPlaybackThread_l(output);
+    if (thread == NULL) {
+        LOGW("channelCount() unknown thread %p", output);
+        return 0;
+    }
+    return thread->channelCount();
 }
 
-int AudioFlinger::format(int output) const
+int AudioFlinger::format(void *output) const
 {
-#ifdef WITH_A2DP
-     if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
-         return mA2dpMixerThread->format();
-     }
-#endif
-     return mHardwareMixerThread->format();
+    Mutex::Autolock _l(mLock);
+    PlaybackThread *thread = checkPlaybackThread_l(output);
+    if (thread == NULL) {
+        LOGW("format() unknown thread %p", output);
+        return 0;
+    }
+    return thread->format();
 }
 
-size_t AudioFlinger::frameCount(int output) const
+size_t AudioFlinger::frameCount(void *output) const
 {
-#ifdef WITH_A2DP
-     if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
-         return mA2dpMixerThread->frameCount();
-     }
-#endif
-     return mHardwareMixerThread->frameCount();
+    Mutex::Autolock _l(mLock);
+    PlaybackThread *thread = checkPlaybackThread_l(output);
+    if (thread == NULL) {
+        LOGW("frameCount() unknown thread %p", output);
+        return 0;
+    }
+    return thread->frameCount();
 }
 
-uint32_t AudioFlinger::latency(int output) const
+uint32_t AudioFlinger::latency(void *output) const
 {
-#ifdef WITH_A2DP
-     if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
-         return mA2dpMixerThread->latency();
-     }
-#endif
-     return mHardwareMixerThread->latency();
+    Mutex::Autolock _l(mLock);
+    PlaybackThread *thread = checkPlaybackThread_l(output);
+    if (thread == NULL) {
+        LOGW("latency() unknown thread %p", output);
+        return 0;
+    }
+    return thread->latency();
 }
 
 status_t AudioFlinger::setMasterVolume(float value)
@@ -477,96 +377,14 @@
         value = 1.0f;
     }
     mHardwareStatus = AUDIO_HW_IDLE;
-    mHardwareMixerThread->setMasterVolume(value);
-#ifdef WITH_A2DP
-    mA2dpMixerThread->setMasterVolume(value);
-#endif
+
+    mMasterVolume = value;
+    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
+       mPlaybackThreads[i]->setMasterVolume(value);
 
     return NO_ERROR;
 }
 
-status_t AudioFlinger::setRouting(int mode, uint32_t routes, uint32_t mask)
-{
-    status_t err = NO_ERROR;
-
-    // check calling permissions
-    if (!settingsAllowed()) {
-        return PERMISSION_DENIED;
-    }
-    if ((mode < AudioSystem::MODE_CURRENT) || (mode >= AudioSystem::NUM_MODES)) {
-        LOGW("Illegal value: setRouting(%d, %u, %u)", mode, routes, mask);
-        return BAD_VALUE;
-    }
-
-#ifdef WITH_A2DP
-    LOGV("setRouting %d %d %d, tid %d, calling tid %d\n", mode, routes, mask, gettid(),
-            IPCThreadState::self()->getCallingPid());
-    if (mode == AudioSystem::MODE_NORMAL && 
-            (mask & AudioSystem::ROUTE_BLUETOOTH_A2DP)) {
-        AutoMutex lock(&mLock);
-
-        bool enableA2dp = false;
-        if (routes & AudioSystem::ROUTE_BLUETOOTH_A2DP) {
-            enableA2dp = true;
-        }
-        if (mA2dpDisableCount > 0) {
-            mA2dpSuppressed = enableA2dp;
-        } else {
-            setA2dpEnabled_l(enableA2dp);
-        }
-        LOGV("setOutput done\n");
-    }
-    // setRouting() is always called at least for mode == AudioSystem::MODE_IN_CALL when 
-    // SCO is enabled, whatever current mode is so we can safely handle A2DP disabling only
-    // in this case to avoid doing it several times.
-    if (mode == AudioSystem::MODE_IN_CALL &&
-        (mask & AudioSystem::ROUTE_BLUETOOTH_SCO)) {
-        AutoMutex lock(&mLock);
-        handleRouteDisablesA2dp_l(routes);
-    }
-#endif
-
-    // do nothing if only A2DP routing is affected
-    mask &= ~AudioSystem::ROUTE_BLUETOOTH_A2DP;
-    if (mask) {
-        AutoMutex lock(mHardwareLock);
-        mHardwareStatus = AUDIO_HW_GET_ROUTING;
-        uint32_t r;
-        err = mAudioHardware->getRouting(mode, &r);
-        if (err == NO_ERROR) {
-            r = (r & ~mask) | (routes & mask);
-            if (mode == AudioSystem::MODE_NORMAL || 
-                (mode == AudioSystem::MODE_CURRENT && getMode() == AudioSystem::MODE_NORMAL)) {
-                mSavedRoute = r;
-                r |= mForcedRoute;
-                LOGV("setRouting mSavedRoute %08x mForcedRoute %08x\n", mSavedRoute, mForcedRoute);
-            }
-            mHardwareStatus = AUDIO_HW_SET_ROUTING;
-            err = mAudioHardware->setRouting(mode, r);
-        }
-        mHardwareStatus = AUDIO_HW_IDLE;
-    }
-    return err;
-}
-
-uint32_t AudioFlinger::getRouting(int mode) const
-{
-    uint32_t routes = 0;
-    if ((mode >= AudioSystem::MODE_CURRENT) && (mode < AudioSystem::NUM_MODES)) {
-        if (mode == AudioSystem::MODE_NORMAL || 
-            (mode == AudioSystem::MODE_CURRENT && getMode() == AudioSystem::MODE_NORMAL)) {
-            routes = mSavedRoute;                
-        } else {
-            mHardwareStatus = AUDIO_HW_GET_ROUTING;
-            mAudioHardware->getRouting(mode, &routes);
-            mHardwareStatus = AUDIO_HW_IDLE;
-        }
-    } else {
-        LOGW("Illegal value: getRouting(%d)", mode);
-    }
-    return routes;
-}
-
 status_t AudioFlinger::setMode(int mode)
 {
     // check calling permissions
@@ -585,15 +403,6 @@
     return ret;
 }
 
-int AudioFlinger::getMode() const
-{
-    int mode = AudioSystem::MODE_INVALID;
-    mHardwareStatus = AUDIO_HW_SET_MODE;
-    mAudioHardware->getMode(&mode);
-    mHardwareStatus = AUDIO_HW_IDLE;
-    return mode;
-}
-
 status_t AudioFlinger::setMicMute(bool state)
 {
     // check calling permissions
@@ -623,36 +432,46 @@
     if (!settingsAllowed()) {
         return PERMISSION_DENIED;
     }
-    mHardwareMixerThread->setMasterMute(muted);
-#ifdef WITH_A2DP
-    mA2dpMixerThread->setMasterMute(muted);
-#endif
+
+    mMasterMute = muted;
+    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
+       mPlaybackThreads[i]->setMasterMute(muted);
+
     return NO_ERROR;
 }
 
 float AudioFlinger::masterVolume() const
 {
-    return mHardwareMixerThread->masterVolume();
+    return mMasterVolume;
 }
 
 bool AudioFlinger::masterMute() const
 {
-    return mHardwareMixerThread->masterMute();
+    return mMasterMute;
 }
 
-status_t AudioFlinger::setStreamVolume(int stream, float value)
+status_t AudioFlinger::setStreamVolume(int stream, float value, void *output)
 {
     // check calling permissions
     if (!settingsAllowed()) {
         return PERMISSION_DENIED;
     }
 
-    if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
-        uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
+    if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
         return BAD_VALUE;
     }
 
+    AutoMutex lock(mLock);
+    PlaybackThread *thread = NULL;
+    if (output) {
+        thread = checkPlaybackThread_l(output);
+        if (thread == NULL) {
+            return BAD_VALUE;
+        }
+    }
+
     status_t ret = NO_ERROR;
+
     if (stream == AudioSystem::VOICE_CALL ||
         stream == AudioSystem::BLUETOOTH_SCO) {
         float hwValue;
@@ -669,12 +488,18 @@
         mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
         ret = mAudioHardware->setVoiceVolume(hwValue);
         mHardwareStatus = AUDIO_HW_IDLE;
+
     }
 
-    mHardwareMixerThread->setStreamVolume(stream, value);
-#ifdef WITH_A2DP
-    mA2dpMixerThread->setStreamVolume(stream, value);
-#endif
+    mStreamTypes[stream].volume = value;
+
+    if (thread == NULL) {
+        for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
+           mPlaybackThreads[i]->setStreamVolume(stream, value);
+
+    } else {
+        thread->setStreamVolume(stream, value);
+    }
 
     return ret;
 }
@@ -686,82 +511,116 @@
         return PERMISSION_DENIED;
     }
 
-    if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
+    if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
         uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
         return BAD_VALUE;
     }
 
-#ifdef WITH_A2DP
-    mA2dpMixerThread->setStreamMute(stream, muted);
-#endif
-    if (stream == AudioSystem::MUSIC) 
-    {
-        AutoMutex lock(&mHardwareLock);
-        if (mForcedRoute != 0)
-            mMusicMuteSaved = muted;
-        else
-            mHardwareMixerThread->setStreamMute(stream, muted);
-    } else {
-        mHardwareMixerThread->setStreamMute(stream, muted);
-    }
+    mStreamTypes[stream].mute = muted;
+    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
+       mPlaybackThreads[i]->setStreamMute(stream, muted);
 
     return NO_ERROR;
 }
 
-float AudioFlinger::streamVolume(int stream) const
+float AudioFlinger::streamVolume(int stream, void *output) const
 {
-    if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
+    if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
         return 0.0f;
     }
-    
-    float volume = mHardwareMixerThread->streamVolume(stream); 
+
+    AutoMutex lock(mLock);
+    float volume;
+    if (output) {
+        PlaybackThread *thread = checkPlaybackThread_l(output);
+        if (thread == NULL) {
+            return 0.0f;
+        }
+        volume = thread->streamVolume(stream);
+    } else {
+        volume = mStreamTypes[stream].volume;
+    }
+
     // remove correction applied by setStreamVolume()
     if (stream == AudioSystem::VOICE_CALL) {
         volume = (volume - 0.01) / 0.99 ;
     }
-    
+
     return volume;
 }
 
 bool AudioFlinger::streamMute(int stream) const
 {
-    if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
+    if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
         return true;
     }
-    
-    if (stream == AudioSystem::MUSIC && mForcedRoute != 0) 
-    {
-        return mMusicMuteSaved;
-    }
-    return mHardwareMixerThread->streamMute(stream);
+
+    return mStreamTypes[stream].mute;
 }
 
 bool AudioFlinger::isMusicActive() const
 {
     Mutex::Autolock _l(mLock);
- #ifdef WITH_A2DP
-     if (isA2dpEnabled()) {
-         return mA2dpMixerThread->isMusicActive_l();
-     }
- #endif
-    return mHardwareMixerThread->isMusicActive_l();
+    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
+        if (mPlaybackThreads[i]->isMusicActive()) {
+            return true;
+        }
+    }
+    return false;
 }
 
-status_t AudioFlinger::setParameter(const char* key, const char* value)
+status_t AudioFlinger::setParameters(void *ioHandle, const String8& keyValuePairs)
 {
-    status_t result, result2;
-    AutoMutex lock(mHardwareLock);
-    mHardwareStatus = AUDIO_SET_PARAMETER;
-    
-    LOGV("setParameter() key %s, value %s, tid %d, calling tid %d", key, value, gettid(), IPCThreadState::self()->getCallingPid());
-    result = mAudioHardware->setParameter(key, value);
-    if (mA2dpAudioInterface) {
-        result2 = mA2dpAudioInterface->setParameter(key, value);
-        if (result2)
-            result = result2;
+    status_t result;
+
+    LOGV("setParameters(): io %p, keyvalue %s, tid %d, calling tid %d",
+            ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
+    // check calling permissions
+    if (!settingsAllowed()) {
+        return PERMISSION_DENIED;
     }
-    mHardwareStatus = AUDIO_HW_IDLE;
-    return result;
+
+    // ioHandle == 0 means the parameters are global to the audio hardware interface
+    if (ioHandle == 0) {
+        AutoMutex lock(mHardwareLock);
+        mHardwareStatus = AUDIO_SET_PARAMETER;
+        result = mAudioHardware->setParameters(keyValuePairs);
+        mHardwareStatus = AUDIO_HW_IDLE;
+        return result;
+    }
+
+    // Check if parameters are for an output
+    PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
+    if (playbackThread != NULL) {
+        return playbackThread->setParameters(keyValuePairs);
+    }
+
+    // Check if parameters are for an input
+    RecordThread *recordThread = checkRecordThread_l(ioHandle);
+    if (recordThread != NULL) {
+        return recordThread->setParameters(keyValuePairs);
+    }
+
+    return BAD_VALUE;
+}
+
+String8 AudioFlinger::getParameters(void *ioHandle, const String8& keys)
+{
+//    LOGV("getParameters() io %p, keys %s, tid %d, calling tid %d",
+//            ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
+
+    if (ioHandle == 0) {
+        return mAudioHardware->getParameters(keys);
+    }
+    PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
+    if (playbackThread != NULL) {
+        return playbackThread->getParameters(keys);
+    }
+    RecordThread *recordThread = checkRecordThread_l(ioHandle);
+    if (recordThread != NULL) {
+        return recordThread->getParameters(keys);
+    }
+    return String8("");
 }
 
 size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
@@ -771,7 +630,7 @@
 
 void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
 {
-    
+
     LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
     Mutex::Autolock _l(mLock);
 
@@ -780,12 +639,21 @@
         LOGV("Adding notification client %p", binder.get());
         binder->linkToDeath(this);
         mNotificationClients.add(binder);
-        client->a2dpEnabledChanged(isA2dpEnabled());
+    }
+
+    // the config change is always sent from playback or record threads to avoid deadlock
+    // with AudioSystem::gLock
+    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
+        mPlaybackThreads[i]->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
+    }
+
+    for (size_t i = 0; i < mRecordThreads.size(); i++) {
+        mRecordThreads[i]->sendConfigEvent(AudioSystem::INPUT_OPENED);
     }
 }
 
 void AudioFlinger::binderDied(const wp<IBinder>& who) {
-    
+
     LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
     Mutex::Autolock _l(mLock);
 
@@ -800,6 +668,17 @@
     }
 }
 
+void AudioFlinger::audioConfigChanged(int event, void *param1, void *param2) {
+    Mutex::Autolock _l(mLock);
+    size_t size = mNotificationClients.size();
+    for (size_t i = 0; i < size; i++) {
+        sp<IBinder> binder = mNotificationClients.itemAt(i);
+        LOGV("audioConfigChanged() Notifying change to client %p", binder.get());
+        sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
+        client->ioConfigChanged(event, param1, param2);
+    }
+}
+
 void AudioFlinger::removeClient(pid_t pid)
 {
     LOGV("removeClient() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
@@ -807,147 +686,139 @@
     mClients.removeItem(pid);
 }
 
-bool AudioFlinger::isA2dpEnabled() const
+// ----------------------------------------------------------------------------
+
+AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger)
+    :   Thread(false),
+        mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
+        mFormat(0), mFrameSize(1), mNewParameters(String8("")), mStandby(false)
 {
-    return mA2dpEnabled;
 }
 
-void AudioFlinger::handleForcedSpeakerRoute(int command)
+AudioFlinger::ThreadBase::~ThreadBase()
 {
-    switch(command) {
-    case ACTIVE_TRACK_ADDED:
-        {
-            AutoMutex lock(mHardwareLock);
-            if (mForcedSpeakerCount++ == 0) {
-                if (mForcedRoute == 0) {
-                    mMusicMuteSaved = mHardwareMixerThread->streamMute(AudioSystem::MUSIC);
-                    LOGV("++mForcedSpeakerCount == 0, mMusicMuteSaved = %d, mRouteRestoreTime = %d", mMusicMuteSaved, mRouteRestoreTime);
-                    if (!(mSavedRoute & AudioSystem::ROUTE_SPEAKER)) {
-                        LOGV("Route forced to Speaker ON %08x", mSavedRoute | AudioSystem::ROUTE_SPEAKER);
-                        mHardwareMixerThread->setStreamMute(AudioSystem::MUSIC, true);
-                        usleep(mHardwareMixerThread->latency()*1000);
-                        mHardwareStatus = AUDIO_HW_SET_ROUTING;
-                        mAudioHardware->setRouting(AudioSystem::MODE_NORMAL, mSavedRoute | AudioSystem::ROUTE_SPEAKER);
-                        mHardwareStatus = AUDIO_HW_IDLE;
-                        // delay track start so that audio hardware has time to siwtch routes
-                        usleep(kStartSleepTime);
-                    }
-                }
-                mForcedRoute = AudioSystem::ROUTE_SPEAKER;
-                mRouteRestoreTime = 0;
-            }
-            LOGV("mForcedSpeakerCount incremented to %d", mForcedSpeakerCount);
-        }
-        break;
-    case ACTIVE_TRACK_REMOVED:
-        {
-            AutoMutex lock(mHardwareLock);
-            if (mForcedSpeakerCount > 0){
-                if (--mForcedSpeakerCount == 0) {
-                    mRouteRestoreTime = systemTime() + milliseconds(kStopSleepTime/1000);
-                }
-                LOGV("mForcedSpeakerCount decremented to %d", mForcedSpeakerCount);
-            } else {
-                LOGE("mForcedSpeakerCount is already zero");
-            }
-        }
-        break;
-    case CHECK_ROUTE_RESTORE_TIME:
-    case FORCE_ROUTE_RESTORE:
-        if (mRouteRestoreTime) {
-            AutoMutex lock(mHardwareLock);
-            if (mRouteRestoreTime && 
-               (systemTime() > mRouteRestoreTime || command == FORCE_ROUTE_RESTORE)) {
-                mHardwareMixerThread->setStreamMute(AudioSystem::MUSIC, mMusicMuteSaved);
-                mForcedRoute = 0;
-                if (!(mSavedRoute & AudioSystem::ROUTE_SPEAKER)) {
-                    mHardwareStatus = AUDIO_HW_SET_ROUTING;
-                    mAudioHardware->setRouting(AudioSystem::MODE_NORMAL, mSavedRoute);
-                    mHardwareStatus = AUDIO_HW_IDLE;
-                    LOGV("Route forced to Speaker OFF %08x", mSavedRoute);
-                }
-                mRouteRestoreTime = 0;
-            }
-        }
-        break;
-    }
 }
 
-#ifdef WITH_A2DP
-// handleRouteDisablesA2dp_l() must be called with AudioFlinger::mLock held
-void AudioFlinger::handleRouteDisablesA2dp_l(int routes)
+void AudioFlinger::ThreadBase::exit()
 {
-   if (routes & AudioSystem::ROUTE_BLUETOOTH_SCO) {
-        if (mA2dpDisableCount++ == 0) {
-            if (mA2dpEnabled) {
-                setA2dpEnabled_l(false);
-                mA2dpSuppressed = true;
-            }
-        }
-        LOGV("mA2dpDisableCount incremented to %d", mA2dpDisableCount);
-   } else {
-        if (mA2dpDisableCount > 0) {
-            if (--mA2dpDisableCount == 0) {
-                if (mA2dpSuppressed) {
-                    setA2dpEnabled_l(true);
-                    mA2dpSuppressed = false;
-                }
-            }
-            LOGV("mA2dpDisableCount decremented to %d", mA2dpDisableCount);
-        } else {
-            LOGV("mA2dpDisableCount is already zero");
-        }
+    // keep a strong ref on ourself so that we want get
+    // destroyed in the middle of requestExitAndWait()
+    sp <ThreadBase> strongMe = this;
+
+    LOGV("ThreadBase::exit");
+    {
+        AutoMutex lock(&mLock);
+        requestExit();
+        mWaitWorkCV.signal();
     }
+    requestExitAndWait();
 }
-#endif
+
+uint32_t AudioFlinger::ThreadBase::sampleRate() const
+{
+    return mSampleRate;
+}
+
+int AudioFlinger::ThreadBase::channelCount() const
+{
+    return mChannelCount;
+}
+
+int AudioFlinger::ThreadBase::format() const
+{
+    return mFormat;
+}
+
+size_t AudioFlinger::ThreadBase::frameCount() const
+{
+    return mFrameCount;
+}
+
+status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
+{
+    status_t result;
+
+    Mutex::Autolock _l(mLock);
+    mNewParameters = keyValuePairs;
+
+    mWaitWorkCV.signal();
+    mParamCond.wait(mLock);
+
+    return mParamStatus;
+}
+
+void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
+{
+    Mutex::Autolock _l(mLock);
+    ConfigEvent *configEvent = new ConfigEvent();
+    configEvent->mEvent = event;
+    configEvent->mParam = param;
+    mConfigEvents.add(configEvent);
+    LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
+    mWaitWorkCV.signal();
+}
+
+void AudioFlinger::ThreadBase::processConfigEvents()
+{
+    mLock.lock();
+    while(!mConfigEvents.isEmpty()) {
+        LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
+        ConfigEvent *configEvent = mConfigEvents[0];
+        mConfigEvents.removeAt(0);
+        // release mLock because audioConfigChanged() will call
+        // Audioflinger::audioConfigChanged() which locks AudioFlinger mLock thus creating
+        // potential cross deadlock between AudioFlinger::mLock and mLock
+        mLock.unlock();
+        audioConfigChanged(configEvent->mEvent, configEvent->mParam);
+        delete configEvent;
+        mLock.lock();
+    }
+    mLock.unlock();
+}
+
 
 // ----------------------------------------------------------------------------
 
-AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int outputType)
-    :   Thread(false),
-        mAudioFlinger(audioFlinger), mAudioMixer(0), mOutput(output), mOutputType(outputType), 
-        mSampleRate(0), mFrameCount(0), mChannelCount(0), mFormat(0), mMixBuffer(0),
-        mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mStandby(false),
-        mInWrite(false)
+AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
+    :   ThreadBase(audioFlinger),
+        mMixBuffer(0), mSuspended(false), mBytesWritten(0), mOutput(output),
+        mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
 {
-    mSampleRate = output->sampleRate();
-    mChannelCount = output->channelCount();
+    readOutputParameters();
 
-    // FIXME - Current mixer implementation only supports stereo output
-    if (mChannelCount == 1) {
-        LOGE("Invalid audio hardware channel count");
+    mMasterVolume = mAudioFlinger->masterVolume();
+    mMasterMute = mAudioFlinger->masterMute();
+
+    for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
+        mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
+        mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
     }
-
-    mFormat = output->format();
-    mFrameCount = output->bufferSize() / output->channelCount() / sizeof(int16_t);
-    mAudioMixer = new AudioMixer(mFrameCount, output->sampleRate());
-
-    // FIXME - Current mixer implementation only supports stereo output: Always
-    // Allocate a stereo buffer even if HW output is mono.
-    mMixBuffer = new int16_t[mFrameCount * 2];
-    memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
+    // notify client processes that a new input has been opened
+    sendConfigEvent(AudioSystem::OUTPUT_OPENED);
 }
 
-AudioFlinger::MixerThread::~MixerThread()
+AudioFlinger::PlaybackThread::~PlaybackThread()
 {
     delete [] mMixBuffer;
-    delete mAudioMixer;
+    if (mType != DUPLICATING) {
+        mAudioFlinger->mAudioHardware->closeOutputStream(mOutput);
+    }
 }
 
-status_t AudioFlinger::MixerThread::dump(int fd, const Vector<String16>& args)
+status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
 {
     dumpInternals(fd, args);
     dumpTracks(fd, args);
     return NO_ERROR;
 }
 
-status_t AudioFlinger::MixerThread::dumpTracks(int fd, const Vector<String16>& args)
+status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
 {
     const size_t SIZE = 256;
     char buffer[SIZE];
     String8 result;
 
-    snprintf(buffer, SIZE, "Output %d mixer thread tracks\n", mOutputType);
+    snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
     result.append(buffer);
     result.append("   Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
     for (size_t i = 0; i < mTracks.size(); ++i) {
@@ -958,7 +829,7 @@
         }
     }
 
-    snprintf(buffer, SIZE, "Output %d mixer thread active tracks\n", mOutputType);
+    snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
     result.append(buffer);
     result.append("   Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
     for (size_t i = 0; i < mActiveTracks.size(); ++i) {
@@ -975,15 +846,13 @@
     return NO_ERROR;
 }
 
-status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
+status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
 {
     const size_t SIZE = 256;
     char buffer[SIZE];
     String8 result;
 
-    snprintf(buffer, SIZE, "Output %d mixer thread internals\n", mOutputType);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
+    snprintf(buffer, SIZE, "Output thread %p internals\n", this);
     result.append(buffer);
     snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
     result.append(buffer);
@@ -1000,275 +869,28 @@
 }
 
 // Thread virtuals
-bool AudioFlinger::MixerThread::threadLoop()
-{
-    unsigned long sleepTime = kBufferRecoveryInUsecs;
-    int16_t* curBuf = mMixBuffer;
-    Vector< sp<Track> > tracksToRemove;
-    size_t enabledTracks = 0;
-    nsecs_t standbyTime = systemTime();   
-    size_t mixBufferSize = mFrameCount*mChannelCount*sizeof(int16_t);
-    nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
-
-#ifdef WITH_A2DP
-    bool outputTrackActive = false;
-#endif
-
-    do {
-        enabledTracks = 0;
-        { // scope for the AudioFlinger::mLock
-        
-            Mutex::Autolock _l(mAudioFlinger->mLock);
-
-#ifdef WITH_A2DP
-            if (mOutputTrack != NULL && !mAudioFlinger->isA2dpEnabled()) {
-                if (outputTrackActive) {
-                    mAudioFlinger->mLock.unlock();
-                    mOutputTrack->stop();
-                    mAudioFlinger->mLock.lock();
-                    outputTrackActive = false;
-                }
-            }
-            mAudioFlinger->checkA2dpEnabledChange_l();
-#endif
-
-            const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
-
-            // put audio hardware into standby after short delay
-            if UNLIKELY(!activeTracks.size() && systemTime() > standbyTime) {
-                // wait until we have something to do...
-                LOGV("Audio hardware entering standby, output %d\n", mOutputType);
-                if (!mStandby) {
-                    mOutput->standby();
-                    mStandby = true;
-                }
-                
-#ifdef WITH_A2DP
-                if (outputTrackActive) {
-                    mAudioFlinger->mLock.unlock();
-                    mOutputTrack->stop();
-                    mAudioFlinger->mLock.lock();
-                    outputTrackActive = false;
-                }
-#endif
-                if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
-                    mAudioFlinger->handleForcedSpeakerRoute(FORCE_ROUTE_RESTORE);
-                }                
-                // we're about to wait, flush the binder command buffer
-                IPCThreadState::self()->flushCommands();
-                mAudioFlinger->mWaitWorkCV.wait(mAudioFlinger->mLock);
-                LOGV("Audio hardware exiting standby, output %d\n", mOutputType);
-                
-                if (mMasterMute == false) {
-                    char value[PROPERTY_VALUE_MAX];
-                    property_get("ro.audio.silent", value, "0");
-                    if (atoi(value)) {
-                        LOGD("Silence is golden");
-                        setMasterMute(true);
-                    }                    
-                }
-                
-                standbyTime = systemTime() + kStandbyTimeInNsecs;
-                continue;
-            }
-
-            // Forced route to speaker is handled by hardware mixer thread
-            if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
-                mAudioFlinger->handleForcedSpeakerRoute(CHECK_ROUTE_RESTORE_TIME);
-            }
-
-            // find out which tracks need to be processed
-            size_t count = activeTracks.size();
-            for (size_t i=0 ; i<count ; i++) {
-                sp<Track> t = activeTracks[i].promote();
-                if (t == 0) continue;
-
-                Track* const track = t.get();
-                audio_track_cblk_t* cblk = track->cblk();
-
-                // The first time a track is added we wait
-                // for all its buffers to be filled before processing it
-                mAudioMixer->setActiveTrack(track->name());
-                if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
-                        !track->isPaused())
-                {
-                    //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
-
-                    // compute volume for this track
-                    int16_t left, right;
-                    if (track->isMuted() || mMasterMute || track->isPausing()) {
-                        left = right = 0;
-                        if (track->isPausing()) {
-                            LOGV("paused(%d)", track->name());
-                            track->setPaused();
-                        }
-                    } else {
-                        float typeVolume = mStreamTypes[track->type()].volume;
-                        float v = mMasterVolume * typeVolume;
-                        float v_clamped = v * cblk->volume[0];
-                        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
-                        left = int16_t(v_clamped);
-                        v_clamped = v * cblk->volume[1];
-                        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
-                        right = int16_t(v_clamped);
-                    }
-
-                    // XXX: these things DON'T need to be done each time
-                    mAudioMixer->setBufferProvider(track);
-                    mAudioMixer->enable(AudioMixer::MIXING);
-
-                    int param;
-                    if ( track->mFillingUpStatus == Track::FS_FILLED) {
-                        // no ramp for the first volume setting
-                        track->mFillingUpStatus = Track::FS_ACTIVE;
-                        if (track->mState == TrackBase::RESUMING) {
-                            track->mState = TrackBase::ACTIVE;
-                            param = AudioMixer::RAMP_VOLUME;
-                        } else {
-                            param = AudioMixer::VOLUME;
-                        }
-                    } else {
-                        param = AudioMixer::RAMP_VOLUME;
-                    }
-                    mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
-                    mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
-                    mAudioMixer->setParameter(
-                        AudioMixer::TRACK,
-                        AudioMixer::FORMAT, track->format());
-                    mAudioMixer->setParameter(
-                        AudioMixer::TRACK,
-                        AudioMixer::CHANNEL_COUNT, track->channelCount());
-                    mAudioMixer->setParameter(
-                        AudioMixer::RESAMPLE,
-                        AudioMixer::SAMPLE_RATE,
-                        int(cblk->sampleRate));
-
-                    // reset retry count
-                    track->mRetryCount = kMaxTrackRetries;
-                    enabledTracks++;
-                } else {
-                    //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
-                    if (track->isStopped()) {
-                        track->reset();
-                    }
-                    if (track->isTerminated() || track->isStopped() || track->isPaused()) {
-                        // We have consumed all the buffers of this track.
-                        // Remove it from the list of active tracks.
-                        LOGV("remove(%d) from active list", track->name());
-                        tracksToRemove.add(track);
-                    } else {
-                        // No buffers for this track. Give it a few chances to
-                        // fill a buffer, then remove it from active list.
-                        if (--(track->mRetryCount) <= 0) {
-                            LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
-                            tracksToRemove.add(track);
-                        }
-                    }
-                    // LOGV("disable(%d)", track->name());
-                    mAudioMixer->disable(AudioMixer::MIXING);
-                }
-            }
-
-            // remove all the tracks that need to be...
-            count = tracksToRemove.size();
-            if (UNLIKELY(count)) {
-                for (size_t i=0 ; i<count ; i++) {
-                    const sp<Track>& track = tracksToRemove[i];
-                    removeActiveTrack_l(track);
-                    if (track->isTerminated()) {
-                        mTracks.remove(track);
-                        deleteTrackName_l(track->mName);
-                    }
-                }
-            }
-       }
-        
-        if (LIKELY(enabledTracks)) {
-            // mix buffers...
-            mAudioMixer->process(curBuf);
-
-#ifdef WITH_A2DP
-            if (mOutputTrack != NULL && mAudioFlinger->isA2dpEnabled()) {
-                if (!outputTrackActive) {
-                    LOGV("starting output track in mixer for output %d", mOutputType);
-                    mOutputTrack->start();
-                    outputTrackActive = true;
-                }
-                mOutputTrack->write(curBuf, mFrameCount);
-            }
-#endif
-
-            // output audio to hardware
-            mLastWriteTime = systemTime();
-            mInWrite = true;
-            mOutput->write(curBuf, mixBufferSize);
-            mNumWrites++;
-            mInWrite = false;
-            mStandby = false;
-            nsecs_t temp = systemTime();
-            standbyTime = temp + kStandbyTimeInNsecs;
-            nsecs_t delta = temp - mLastWriteTime;
-            if (delta > maxPeriod) {
-                LOGW("write blocked for %llu msecs", ns2ms(delta));
-                mNumDelayedWrites++;
-            }
-            sleepTime = kBufferRecoveryInUsecs;
-        } else {         
-#ifdef WITH_A2DP
-            if (mOutputTrack != NULL && mAudioFlinger->isA2dpEnabled()) {
-                if (outputTrackActive) {
-                    mOutputTrack->write(curBuf, 0);
-                    if (mOutputTrack->bufferQueueEmpty()) {
-                        mOutputTrack->stop();
-                        outputTrackActive = false;
-                    } else {
-                        standbyTime = systemTime() + kStandbyTimeInNsecs;
-                    }
-                }
-            }
-#endif
-            // There was nothing to mix this round, which means all
-            // active tracks were late. Sleep a little bit to give
-            // them another chance. If we're too late, the audio
-            // hardware will zero-fill for us.
-            //LOGV("no buffers - usleep(%lu)", sleepTime);
-            usleep(sleepTime);
-            if (sleepTime < kMaxBufferRecoveryInUsecs) {
-                sleepTime += kBufferRecoveryInUsecs;
-            }
-        }
-
-        // finally let go of all our tracks, without the lock held
-        // since we can't guarantee the destructors won't acquire that
-        // same lock.
-        tracksToRemove.clear();
-    } while (true);
-
-    return false;
-}
-
-status_t AudioFlinger::MixerThread::readyToRun()
+status_t AudioFlinger::PlaybackThread::readyToRun()
 {
     if (mSampleRate == 0) {
         LOGE("No working audio driver found.");
         return NO_INIT;
     }
-    LOGI("AudioFlinger's thread ready to run for output %d", mOutputType);
+    LOGI("AudioFlinger's thread %p ready to run", this);
     return NO_ERROR;
 }
 
-void AudioFlinger::MixerThread::onFirstRef()
+void AudioFlinger::PlaybackThread::onFirstRef()
 {
     const size_t SIZE = 256;
     char buffer[SIZE];
 
-    snprintf(buffer, SIZE, "Mixer Thread for output %d", mOutputType);
+    snprintf(buffer, SIZE, "Playback Thread %p", this);
 
     run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
 }
 
-// MixerThread::createTrack_l() must be called with AudioFlinger::mLock held
-sp<AudioFlinger::MixerThread::Track>  AudioFlinger::MixerThread::createTrack_l(
+// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
+sp<AudioFlinger::PlaybackThread::Track>  AudioFlinger::PlaybackThread::createTrack_l(
         const sp<AudioFlinger::Client>& client,
         int streamType,
         uint32_t sampleRate,
@@ -1280,28 +902,39 @@
 {
     sp<Track> track;
     status_t lStatus;
-    
-    // Resampler implementation limits input sampling rate to 2 x output sampling rate.
-    if (sampleRate > mSampleRate*2) {
-        LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
-        lStatus = BAD_VALUE;
-        goto Exit;
+
+    if (mType == DIRECT) {
+        if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
+            LOGE("createTrack_l() Bad parameter:  sampleRate %d format %d, channelCount %d for output %p",
+                 sampleRate, format, channelCount, mOutput);
+            lStatus = BAD_VALUE;
+            goto Exit;
+        }
+    } else {
+        // Resampler implementation limits input sampling rate to 2 x output sampling rate.
+        if (sampleRate > mSampleRate*2) {
+            LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
+            lStatus = BAD_VALUE;
+            goto Exit;
+        }
     }
 
-
-    if (mSampleRate == 0) {
+    if (mOutput == 0) {
         LOGE("Audio driver not initialized.");
         lStatus = NO_INIT;
         goto Exit;
     }
 
-    track = new Track(this, client, streamType, sampleRate, format,
-            channelCount, frameCount, sharedBuffer);
-    if (track->getCblk() == NULL) {
-        lStatus = NO_MEMORY;
-        goto Exit;
+    { // scope for mLock
+        Mutex::Autolock _l(mLock);
+        track = new Track(this, client, streamType, sampleRate, format,
+                channelCount, frameCount, sharedBuffer);
+        if (track->getCblk() == NULL) {
+            lStatus = NO_MEMORY;
+            goto Exit;
+        }
+        mTracks.add(track);
     }
-    mTracks.add(track);
     lStatus = NO_ERROR;
 
 Exit:
@@ -1311,87 +944,7 @@
     return track;
 }
 
-// getTracks_l() must be called with AudioFlinger::mLock held
-void AudioFlinger::MixerThread::getTracks_l(
-        SortedVector < sp<Track> >& tracks,
-        SortedVector < wp<Track> >& activeTracks)
-{
-    size_t size = mTracks.size();
-    LOGV ("MixerThread::getTracks_l() for output %d, mTracks.size %d, mActiveTracks.size %d", mOutputType,  mTracks.size(), mActiveTracks.size());
-    for (size_t i = 0; i < size; i++) {
-        sp<Track> t = mTracks[i];
-        if (AudioSystem::routedToA2dpOutput(t->mStreamType)) {
-            tracks.add(t);
-            int j = mActiveTracks.indexOf(t);
-            if (j >= 0) {
-                t = mActiveTracks[j].promote();
-                if (t != NULL) {
-                    activeTracks.add(t);                                    
-                }                            
-            }
-        }
-    }
-
-    size = activeTracks.size();
-    for (size_t i = 0; i < size; i++) {
-        removeActiveTrack_l(activeTracks[i]);
-    }
-    
-    size = tracks.size();
-    for (size_t i = 0; i < size; i++) {
-        sp<Track> t = tracks[i];
-        mTracks.remove(t);
-        deleteTrackName_l(t->name());
-    }
-}
-
-// putTracks_l() must be called with AudioFlinger::mLock held
-void AudioFlinger::MixerThread::putTracks_l(
-        SortedVector < sp<Track> >& tracks,
-        SortedVector < wp<Track> >& activeTracks)
-{
-
-    LOGV ("MixerThread::putTracks_l() for output %d, tracks.size %d, activeTracks.size %d", mOutputType,  tracks.size(), activeTracks.size());
-
-    size_t size = tracks.size();
-    for (size_t i = 0; i < size ; i++) {
-        sp<Track> t = tracks[i];
-        int name = getTrackName_l();
-
-        if (name < 0) return;
-        
-        t->mName = name;
-        t->mMixerThread = this;
-        mTracks.add(t);
-
-        int j = activeTracks.indexOf(t);
-        if (j >= 0) {
-            addActiveTrack_l(t);
-        }            
-    }
-}
-
-uint32_t AudioFlinger::MixerThread::sampleRate() const
-{
-    return mSampleRate;
-}
-
-int AudioFlinger::MixerThread::channelCount() const
-{
-    return mChannelCount;
-}
-
-int AudioFlinger::MixerThread::format() const
-{
-    return mFormat;
-}
-
-size_t AudioFlinger::MixerThread::frameCount() const
-{
-    return mFrameCount;
-}
-
-uint32_t AudioFlinger::MixerThread::latency() const
+uint32_t AudioFlinger::PlaybackThread::latency() const
 {
     if (mOutput) {
         return mOutput->latency();
@@ -1401,66 +954,66 @@
     }
 }
 
-status_t AudioFlinger::MixerThread::setMasterVolume(float value)
+status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
 {
     mMasterVolume = value;
     return NO_ERROR;
 }
 
-status_t AudioFlinger::MixerThread::setMasterMute(bool muted)
+status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
 {
     mMasterMute = muted;
     return NO_ERROR;
 }
 
-float AudioFlinger::MixerThread::masterVolume() const
+float AudioFlinger::PlaybackThread::masterVolume() const
 {
     return mMasterVolume;
 }
 
-bool AudioFlinger::MixerThread::masterMute() const
+bool AudioFlinger::PlaybackThread::masterMute() const
 {
     return mMasterMute;
 }
 
-status_t AudioFlinger::MixerThread::setStreamVolume(int stream, float value)
+status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
 {
     mStreamTypes[stream].volume = value;
     return NO_ERROR;
 }
 
-status_t AudioFlinger::MixerThread::setStreamMute(int stream, bool muted)
+status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
 {
     mStreamTypes[stream].mute = muted;
     return NO_ERROR;
 }
 
-float AudioFlinger::MixerThread::streamVolume(int stream) const
+float AudioFlinger::PlaybackThread::streamVolume(int stream) const
 {
     return mStreamTypes[stream].volume;
 }
 
-bool AudioFlinger::MixerThread::streamMute(int stream) const
+bool AudioFlinger::PlaybackThread::streamMute(int stream) const
 {
     return mStreamTypes[stream].mute;
 }
 
-// isMusicActive_l() must be called with AudioFlinger::mLock held
-bool AudioFlinger::MixerThread::isMusicActive_l() const
+bool AudioFlinger::PlaybackThread::isMusicActive() const
 {
+    Mutex::Autolock _l(mLock);
     size_t count = mActiveTracks.size();
     for (size_t i = 0 ; i < count ; ++i) {
         sp<Track> t = mActiveTracks[i].promote();
         if (t == 0) continue;
         Track* const track = t.get();
-        if (t->mStreamType == AudioSystem::MUSIC)
+        if (t->type() == AudioSystem::MUSIC)
             return true;
     }
     return false;
 }
 
-// addTrack_l() must be called with AudioFlinger::mLock held
-status_t AudioFlinger::MixerThread::addTrack_l(const sp<Track>& track)
+// addTrack_l() must be called with ThreadBase::mLock held
+status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
 {
     status_t status = ALREADY_EXISTS;
 
@@ -1481,18 +1034,18 @@
         // effectively get the latency it requested.
         track->mFillingUpStatus = Track::FS_FILLING;
         track->mResetDone = false;
-        addActiveTrack_l(track);
+        mActiveTracks.add(track);
         status = NO_ERROR;
     }
-    
+
     LOGV("mWaitWorkCV.broadcast");
-    mAudioFlinger->mWaitWorkCV.broadcast();
+    mWaitWorkCV.broadcast();
 
     return status;
 }
 
-// destroyTrack_l() must be called with AudioFlinger::mLock held
-void AudioFlinger::MixerThread::destroyTrack_l(const sp<Track>& track)
+// destroyTrack_l() must be called with ThreadBase::mLock held
+void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
 {
     track->mState = TrackBase::TERMINATED;
     if (mActiveTracks.indexOf(track) < 0) {
@@ -1502,62 +1055,893 @@
     }
 }
 
-// addActiveTrack_l() must be called with AudioFlinger::mLock held
-void AudioFlinger::MixerThread::addActiveTrack_l(const wp<Track>& t)
+String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
 {
-    mActiveTracks.add(t);
+    return mOutput->getParameters(keys);
+}
 
-    // Force routing to speaker for certain stream types
-    // The forced routing to speaker is managed by hardware mixer
-    if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
-        sp<Track> track = t.promote();
-        if (track == NULL) return;
-   
-        if (streamForcedToSpeaker(track->type())) {
-            mAudioFlinger->handleForcedSpeakerRoute(ACTIVE_TRACK_ADDED);
-        }        
+void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
+    AudioSystem::OutputDescriptor desc;
+    void *param2 = 0;
+
+    LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
+
+    switch (event) {
+    case AudioSystem::OUTPUT_OPENED:
+    case AudioSystem::OUTPUT_CONFIG_CHANGED:
+        desc.channels = mChannelCount;
+        desc.samplingRate = mSampleRate;
+        desc.format = mFormat;
+        desc.frameCount = mFrameCount;
+        desc.latency = latency();
+        param2 = &desc;
+        break;
+
+    case AudioSystem::STREAM_CONFIG_CHANGED:
+        param2 = &param;
+    case AudioSystem::OUTPUT_CLOSED:
+    default:
+        break;
+    }
+    mAudioFlinger->audioConfigChanged(event, this, param2);
+}
+
+void AudioFlinger::PlaybackThread::readOutputParameters()
+{
+    mSampleRate = mOutput->sampleRate();
+    mChannelCount = AudioSystem::popCount(mOutput->channels());
+
+    mFormat = mOutput->format();
+    mFrameSize = mOutput->frameSize();
+    mFrameCount = mOutput->bufferSize() / mFrameSize;
+
+    mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
+    // FIXME - Current mixer implementation only supports stereo output: Always
+    // Allocate a stereo buffer even if HW output is mono.
+    if (mMixBuffer != NULL) delete mMixBuffer;
+    mMixBuffer = new int16_t[mFrameCount * 2];
+    memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
+}
+
+// ----------------------------------------------------------------------------
+
+AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
+    :   PlaybackThread(audioFlinger, output),
+        mAudioMixer(0)
+{
+    mType = PlaybackThread::MIXER;
+    mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
+
+    // FIXME - Current mixer implementation only supports stereo output
+    if (mChannelCount == 1) {
+        LOGE("Invalid audio hardware channel count");
     }
 }
 
-// removeActiveTrack_l() must be called with AudioFlinger::mLock held
-void AudioFlinger::MixerThread::removeActiveTrack_l(const wp<Track>& t)
+AudioFlinger::MixerThread::~MixerThread()
 {
-    mActiveTracks.remove(t);
+    delete mAudioMixer;
+}
 
-    // Force routing to speaker for certain stream types
-    // The forced routing to speaker is managed by hardware mixer
-    if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
-        sp<Track> track = t.promote();
-        if (track == NULL) return;
+bool AudioFlinger::MixerThread::threadLoop()
+{
+    unsigned long sleepTime = kBufferRecoveryInUsecs;
+    int16_t* curBuf = mMixBuffer;
+    Vector< sp<Track> > tracksToRemove;
+    size_t enabledTracks = 0;
+    nsecs_t standbyTime = systemTime();
+    size_t mixBufferSize = mFrameCount * mFrameSize;
+    nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
 
-        if (streamForcedToSpeaker(track->type())) {
-            mAudioFlinger->handleForcedSpeakerRoute(ACTIVE_TRACK_REMOVED);
+    while (!exitPending())
+    {
+        processConfigEvents();
+
+        enabledTracks = 0;
+        { // scope for mLock
+
+            Mutex::Autolock _l(mLock);
+
+            if (checkForNewParameters_l()) {
+                mixBufferSize = mFrameCount * mFrameSize;
+                maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
+            }
+
+            const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
+
+            // put audio hardware into standby after short delay
+            if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
+                        mSuspended) {
+                if (!mStandby) {
+                    LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
+                    mOutput->standby();
+                    mStandby = true;
+                    mBytesWritten = 0;
+                }
+
+                if (!activeTracks.size() && mConfigEvents.isEmpty()) {
+                    // we're about to wait, flush the binder command buffer
+                    IPCThreadState::self()->flushCommands();
+
+                    if (exitPending()) break;
+
+                    // wait until we have something to do...
+                    LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
+                    mWaitWorkCV.wait(mLock);
+                    LOGV("MixerThread %p TID %d waking up\n", this, gettid());
+
+                    if (mMasterMute == false) {
+                        char value[PROPERTY_VALUE_MAX];
+                        property_get("ro.audio.silent", value, "0");
+                        if (atoi(value)) {
+                            LOGD("Silence is golden");
+                            setMasterMute(true);
+                        }
+                    }
+
+                    standbyTime = systemTime() + kStandbyTimeInNsecs;
+                    continue;
+                }
+            }
+
+            enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
+       }
+
+        if (LIKELY(enabledTracks)) {
+            // mix buffers...
+            mAudioMixer->process(curBuf);
+
+            // output audio to hardware
+            if (mSuspended) {
+                usleep(kMaxBufferRecoveryInUsecs);
+            } else {
+                mLastWriteTime = systemTime();
+                mInWrite = true;
+                int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
+                if (bytesWritten > 0) mBytesWritten += bytesWritten;
+                mNumWrites++;
+                mInWrite = false;
+                mStandby = false;
+                nsecs_t temp = systemTime();
+                standbyTime = temp + kStandbyTimeInNsecs;
+                nsecs_t delta = temp - mLastWriteTime;
+                if (delta > maxPeriod) {
+                    LOGW("write blocked for %llu msecs", ns2ms(delta));
+                    mNumDelayedWrites++;
+                }
+                sleepTime = kBufferRecoveryInUsecs;
+            }
+        } else {
+            // There was nothing to mix this round, which means all
+            // active tracks were late. Sleep a little bit to give
+            // them another chance. If we're too late, the audio
+            // hardware will zero-fill for us.
+            // LOGV("thread %p no buffers - usleep(%lu)", this, sleepTime);
+            usleep(sleepTime);
+            if (sleepTime < kMaxBufferRecoveryInUsecs) {
+                sleepTime += kBufferRecoveryInUsecs;
+            }
+        }
+
+        // finally let go of all our tracks, without the lock held
+        // since we can't guarantee the destructors won't acquire that
+        // same lock.
+        tracksToRemove.clear();
+    }
+
+    if (!mStandby) {
+        mOutput->standby();
+    }
+    sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
+    processConfigEvents();
+
+    LOGV("MixerThread %p exiting", this);
+    return false;
+}
+
+// prepareTracks_l() must be called with ThreadBase::mLock held
+size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
+{
+
+    size_t enabledTracks = 0;
+    // find out which tracks need to be processed
+    size_t count = activeTracks.size();
+    for (size_t i=0 ; i<count ; i++) {
+        sp<Track> t = activeTracks[i].promote();
+        if (t == 0) continue;
+
+        Track* const track = t.get();
+        audio_track_cblk_t* cblk = track->cblk();
+
+        // The first time a track is added we wait
+        // for all its buffers to be filled before processing it
+        mAudioMixer->setActiveTrack(track->name());
+        if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
+                !track->isPaused())
+        {
+            //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
+
+            // compute volume for this track
+            int16_t left, right;
+            if (track->isMuted() || mMasterMute || track->isPausing() ||
+                mStreamTypes[track->type()].mute) {
+                left = right = 0;
+                if (track->isPausing()) {
+                    track->setPaused();
+                }
+            } else {
+                float typeVolume = mStreamTypes[track->type()].volume;
+                float v = mMasterVolume * typeVolume;
+                float v_clamped = v * cblk->volume[0];
+                if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
+                left = int16_t(v_clamped);
+                v_clamped = v * cblk->volume[1];
+                if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
+                right = int16_t(v_clamped);
+            }
+
+            // XXX: these things DON'T need to be done each time
+            mAudioMixer->setBufferProvider(track);
+            mAudioMixer->enable(AudioMixer::MIXING);
+
+            int param;
+            if ( track->mFillingUpStatus == Track::FS_FILLED) {
+                // no ramp for the first volume setting
+                track->mFillingUpStatus = Track::FS_ACTIVE;
+                if (track->mState == TrackBase::RESUMING) {
+                    track->mState = TrackBase::ACTIVE;
+                    param = AudioMixer::RAMP_VOLUME;
+                } else {
+                    param = AudioMixer::VOLUME;
+                }
+            } else {
+                param = AudioMixer::RAMP_VOLUME;
+            }
+            mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
+            mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
+            mAudioMixer->setParameter(
+                AudioMixer::TRACK,
+                AudioMixer::FORMAT, track->format());
+            mAudioMixer->setParameter(
+                AudioMixer::TRACK,
+                AudioMixer::CHANNEL_COUNT, track->channelCount());
+            mAudioMixer->setParameter(
+                AudioMixer::RESAMPLE,
+                AudioMixer::SAMPLE_RATE,
+                int(cblk->sampleRate));
+
+            // reset retry count
+            track->mRetryCount = kMaxTrackRetries;
+            enabledTracks++;
+        } else {
+            //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
+            if (track->isStopped()) {
+                track->reset();
+            }
+            if (track->isTerminated() || track->isStopped() || track->isPaused()) {
+                // We have consumed all the buffers of this track.
+                // Remove it from the list of active tracks.
+                tracksToRemove->add(track);
+                mAudioMixer->disable(AudioMixer::MIXING);
+            } else {
+                // No buffers for this track. Give it a few chances to
+                // fill a buffer, then remove it from active list.
+                if (--(track->mRetryCount) <= 0) {
+                    LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
+                    tracksToRemove->add(track);
+                }
+                // For tracks using static shared memry buffer, make sure that we have
+                // written enough data to audio hardware before disabling the track
+                // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
+                // don't care about code removing track from active list above.
+                if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
+                    mAudioMixer->disable(AudioMixer::MIXING);
+                } else {
+                    enabledTracks++;
+                }
+            }
+        }
+    }
+
+    // remove all the tracks that need to be...
+    count = tracksToRemove->size();
+    if (UNLIKELY(count)) {
+        for (size_t i=0 ; i<count ; i++) {
+            const sp<Track>& track = tracksToRemove->itemAt(i);
+            mActiveTracks.remove(track);
+            if (track->isTerminated()) {
+                mTracks.remove(track);
+                deleteTrackName_l(track->mName);
+            }
+        }
+    }
+
+    return enabledTracks;
+}
+
+void AudioFlinger::MixerThread::getTracks(
+        SortedVector < sp<Track> >& tracks,
+        SortedVector < wp<Track> >& activeTracks,
+        int streamType)
+{
+    LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this,  mTracks.size(), mActiveTracks.size());
+    Mutex::Autolock _l(mLock);
+    size_t size = mTracks.size();
+    for (size_t i = 0; i < size; i++) {
+        sp<Track> t = mTracks[i];
+        if (t->type() == streamType) {
+            tracks.add(t);
+            int j = mActiveTracks.indexOf(t);
+            if (j >= 0) {
+                t = mActiveTracks[j].promote();
+                if (t != NULL) {
+                    activeTracks.add(t);
+                }
+            }
+        }
+    }
+
+    size = activeTracks.size();
+    for (size_t i = 0; i < size; i++) {
+        mActiveTracks.remove(activeTracks[i]);
+    }
+
+    size = tracks.size();
+    for (size_t i = 0; i < size; i++) {
+        sp<Track> t = tracks[i];
+        mTracks.remove(t);
+        deleteTrackName_l(t->name());
+    }
+}
+
+void AudioFlinger::MixerThread::putTracks(
+        SortedVector < sp<Track> >& tracks,
+        SortedVector < wp<Track> >& activeTracks)
+{
+    LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this,  tracks.size(), activeTracks.size());
+    Mutex::Autolock _l(mLock);
+    size_t size = tracks.size();
+    for (size_t i = 0; i < size ; i++) {
+        sp<Track> t = tracks[i];
+        int name = getTrackName_l();
+
+        if (name < 0) return;
+
+        t->mName = name;
+        t->mThread = this;
+        mTracks.add(t);
+
+        int j = activeTracks.indexOf(t);
+        if (j >= 0) {
+            mActiveTracks.add(t);
         }
     }
 }
 
-// getTrackName_l() must be called with AudioFlinger::mLock held
+// getTrackName_l() must be called with ThreadBase::mLock held
 int AudioFlinger::MixerThread::getTrackName_l()
 {
     return mAudioMixer->getTrackName();
 }
 
-// deleteTrackName_l() must be called with AudioFlinger::mLock held
+// deleteTrackName_l() must be called with ThreadBase::mLock held
 void AudioFlinger::MixerThread::deleteTrackName_l(int name)
 {
     mAudioMixer->deleteTrackName(name);
 }
 
-size_t AudioFlinger::MixerThread::getOutputFrameCount() 
+// checkForNewParameters_l() must be called with ThreadBase::mLock held
+bool AudioFlinger::MixerThread::checkForNewParameters_l()
 {
-    return mOutput->bufferSize() / mOutput->channelCount() / sizeof(int16_t);
+    bool reconfig = false;
+
+    if (mNewParameters != "") {
+        status_t status = NO_ERROR;
+        AudioParameter param = AudioParameter(mNewParameters);
+        int value;
+        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
+            reconfig = true;
+        }
+        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
+            if (value != AudioSystem::PCM_16_BIT) {
+                status = BAD_VALUE;
+            } else {
+                reconfig = true;
+            }
+        }
+        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
+            if (value != AudioSystem::CHANNEL_OUT_STEREO) {
+                status = BAD_VALUE;
+            } else {
+                reconfig = true;
+            }
+        }
+        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
+            // do not accept frame count changes if tracks are open as the track buffer
+            // size depends on frame count and correct behavior would not be garantied
+            // if frame count is changed after track creation
+            if (!mTracks.isEmpty()) {
+                status = INVALID_OPERATION;
+            } else {
+                reconfig = true;
+            }
+        }
+        if (status == NO_ERROR) {
+            status = mOutput->setParameters(mNewParameters);
+            if (!mStandby && status == INVALID_OPERATION) {
+               mOutput->standby();
+               mStandby = true;
+               mBytesWritten = 0;
+               status = mOutput->setParameters(mNewParameters);
+            }
+            if (status == NO_ERROR && reconfig) {
+                delete mAudioMixer;
+                readOutputParameters();
+                mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
+                for (size_t i = 0; i < mTracks.size() ; i++) {
+                    int name = getTrackName_l();
+                    if (name < 0) break;
+                    mTracks[i]->mName = name;
+                }
+                sendConfigEvent(AudioSystem::OUTPUT_CONFIG_CHANGED);
+            }
+        }
+        mParamStatus = status;
+        mNewParameters = "";
+        mParamCond.signal();
+    }
+    return reconfig;
+}
+
+status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
+{
+    const size_t SIZE = 256;
+    char buffer[SIZE];
+    String8 result;
+
+    PlaybackThread::dumpInternals(fd, args);
+
+    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
+    result.append(buffer);
+    write(fd, result.string(), result.size());
+    return NO_ERROR;
+}
+
+// ----------------------------------------------------------------------------
+AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
+    :   PlaybackThread(audioFlinger, output),
+    mLeftVolume (1.0), mRightVolume(1.0)
+{
+    mType = PlaybackThread::DIRECT;
+}
+
+AudioFlinger::DirectOutputThread::~DirectOutputThread()
+{
+}
+
+
+bool AudioFlinger::DirectOutputThread::threadLoop()
+{
+    unsigned long sleepTime = kBufferRecoveryInUsecs;
+    sp<Track> trackToRemove;
+    sp<Track> activeTrack;
+    nsecs_t standbyTime = systemTime();
+    int8_t *curBuf;
+    size_t mixBufferSize = mFrameCount*mFrameSize;
+
+    while (!exitPending())
+    {
+        processConfigEvents();
+
+        { // scope for the mLock
+
+            Mutex::Autolock _l(mLock);
+
+            if (checkForNewParameters_l()) {
+                mixBufferSize = mFrameCount*mFrameSize;
+            }
+
+            // put audio hardware into standby after short delay
+            if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
+                        mSuspended) {
+                // wait until we have something to do...
+                if (!mStandby) {
+                    LOGV("Audio hardware entering standby, mixer %p\n", this);
+                    mOutput->standby();
+                    mStandby = true;
+                    mBytesWritten = 0;
+                }
+
+                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
+                    // we're about to wait, flush the binder command buffer
+                    IPCThreadState::self()->flushCommands();
+
+                    if (exitPending()) break;
+
+                    LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
+                    mWaitWorkCV.wait(mLock);
+                    LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
+
+                    if (mMasterMute == false) {
+                        char value[PROPERTY_VALUE_MAX];
+                        property_get("ro.audio.silent", value, "0");
+                        if (atoi(value)) {
+                            LOGD("Silence is golden");
+                            setMasterMute(true);
+                        }
+                    }
+
+                    standbyTime = systemTime() + kStandbyTimeInNsecs;
+                    continue;
+                }
+            }
+
+            // find out which tracks need to be processed
+            if (mActiveTracks.size() != 0) {
+                sp<Track> t = mActiveTracks[0].promote();
+                if (t == 0) continue;
+
+                Track* const track = t.get();
+                audio_track_cblk_t* cblk = track->cblk();
+
+                // The first time a track is added we wait
+                // for all its buffers to be filled before processing it
+                if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
+                        !track->isPaused())
+                {
+                    //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
+
+                    // compute volume for this track
+                    float left, right;
+                    if (track->isMuted() || mMasterMute || track->isPausing() ||
+                        mStreamTypes[track->type()].mute) {
+                        left = right = 0;
+                        if (track->isPausing()) {
+                            track->setPaused();
+                        }
+                    } else {
+                        float typeVolume = mStreamTypes[track->type()].volume;
+                        float v = mMasterVolume * typeVolume;
+                        float v_clamped = v * cblk->volume[0];
+                        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
+                        left = v_clamped/MAX_GAIN;
+                        v_clamped = v * cblk->volume[1];
+                        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
+                        right = v_clamped/MAX_GAIN;
+                    }
+
+                    if (left != mLeftVolume || right != mRightVolume) {
+                        mOutput->setVolume(left, right);
+                        left = mLeftVolume;
+                        right = mRightVolume;
+                    }
+
+                    if (track->mFillingUpStatus == Track::FS_FILLED) {
+                        track->mFillingUpStatus = Track::FS_ACTIVE;
+                        if (track->mState == TrackBase::RESUMING) {
+                            track->mState = TrackBase::ACTIVE;
+                        }
+                    }
+
+                    // reset retry count
+                    track->mRetryCount = kMaxTrackRetries;
+                    activeTrack = t;
+                } else {
+                    //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
+                    if (track->isStopped()) {
+                        track->reset();
+                    }
+                    if (track->isTerminated() || track->isStopped() || track->isPaused()) {
+                        // We have consumed all the buffers of this track.
+                        // Remove it from the list of active tracks.
+                        trackToRemove = track;
+                    } else {
+                        // No buffers for this track. Give it a few chances to
+                        // fill a buffer, then remove it from active list.
+                        if (--(track->mRetryCount) <= 0) {
+                            LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
+                            trackToRemove = track;
+                        }
+
+                        // For tracks using static shared memry buffer, make sure that we have
+                        // written enough data to audio hardware before disabling the track
+                        // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
+                        // don't care about code removing track from active list above.
+                        if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
+                            activeTrack = t;
+                        }
+                     }
+                }
+            }
+
+            // remove all the tracks that need to be...
+            if (UNLIKELY(trackToRemove != 0)) {
+                mActiveTracks.remove(trackToRemove);
+                if (trackToRemove->isTerminated()) {
+                    mTracks.remove(trackToRemove);
+                    deleteTrackName_l(trackToRemove->mName);
+                }
+            }
+       }
+
+        if (activeTrack != 0) {
+            AudioBufferProvider::Buffer buffer;
+            size_t frameCount = mFrameCount;
+            curBuf = (int8_t *)mMixBuffer;
+            // output audio to hardware
+            mLastWriteTime = systemTime();
+            mInWrite = true;
+            while(frameCount) {
+                buffer.frameCount = frameCount;
+                activeTrack->getNextBuffer(&buffer);
+                if (UNLIKELY(buffer.raw == 0)) {
+                    memset(curBuf, 0, frameCount * mFrameSize);
+                    break;
+                }
+                memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
+                frameCount -= buffer.frameCount;
+                curBuf += buffer.frameCount * mFrameSize;
+                activeTrack->releaseBuffer(&buffer);
+            }
+            if (mSuspended) {
+                usleep(kMaxBufferRecoveryInUsecs);
+            } else {
+                int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
+                if (bytesWritten) mBytesWritten += bytesWritten;
+                mNumWrites++;
+                mInWrite = false;
+                mStandby = false;
+                nsecs_t temp = systemTime();
+                standbyTime = temp + kStandbyTimeInNsecs;
+                sleepTime = kBufferRecoveryInUsecs;
+            }
+        } else {
+            // There was nothing to mix this round, which means all
+            // active tracks were late. Sleep a little bit to give
+            // them another chance. If we're too late, the audio
+            // hardware will zero-fill for us.
+            //LOGV("no buffers - usleep(%lu)", sleepTime);
+            usleep(sleepTime);
+            if (sleepTime < kMaxBufferRecoveryInUsecs) {
+                sleepTime += kBufferRecoveryInUsecs;
+            }
+        }
+
+        // finally let go of removed track, without the lock held
+        // since we can't guarantee the destructors won't acquire that
+        // same lock.
+        trackToRemove.clear();
+        activeTrack.clear();
+    }
+
+    if (!mStandby) {
+        mOutput->standby();
+    }
+    sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
+    processConfigEvents();
+
+    LOGV("DirectOutputThread %p exiting", this);
+    return false;
+}
+
+// getTrackName_l() must be called with ThreadBase::mLock held
+int AudioFlinger::DirectOutputThread::getTrackName_l()
+{
+    return 0;
+}
+
+// deleteTrackName_l() must be called with ThreadBase::mLock held
+void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
+{
+}
+
+// checkForNewParameters_l() must be called with ThreadBase::mLock held
+bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
+{
+    bool reconfig = false;
+
+    if (mNewParameters != "") {
+        status_t status = NO_ERROR;
+        AudioParameter param = AudioParameter(mNewParameters);
+        int value;
+        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
+            // do not accept frame count changes if tracks are open as the track buffer
+            // size depends on frame count and correct behavior would not be garantied
+            // if frame count is changed after track creation
+            if (!mTracks.isEmpty()) {
+                status = INVALID_OPERATION;
+            } else {
+                reconfig = true;
+            }
+        }
+        if (status == NO_ERROR) {
+            status = mOutput->setParameters(mNewParameters);
+            if (!mStandby && status == INVALID_OPERATION) {
+               mOutput->standby();
+               mStandby = true;
+               mBytesWritten = 0;
+               status = mOutput->setParameters(mNewParameters);
+            }
+            if (status == NO_ERROR && reconfig) {
+                readOutputParameters();
+                sendConfigEvent(AudioSystem::OUTPUT_CONFIG_CHANGED);
+            }
+        }
+        mParamStatus = status;
+        mNewParameters = "";
+        mParamCond.signal();
+    }
+    return reconfig;
 }
 
 // ----------------------------------------------------------------------------
 
+AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
+    :   MixerThread(audioFlinger, mainThread->getOutput())
+{
+    mType = PlaybackThread::DUPLICATING;
+    addOutputTrack(mainThread);
+}
+
+AudioFlinger::DuplicatingThread::~DuplicatingThread()
+{
+    mOutputTracks.clear();
+}
+
+bool AudioFlinger::DuplicatingThread::threadLoop()
+{
+    unsigned long sleepTime = kBufferRecoveryInUsecs;
+    int16_t* curBuf = mMixBuffer;
+    Vector< sp<Track> > tracksToRemove;
+    size_t enabledTracks = 0;
+    nsecs_t standbyTime = systemTime();
+    size_t mixBufferSize = mFrameCount*mFrameSize;
+    SortedVector< sp<OutputTrack> > outputTracks;
+
+    while (!exitPending())
+    {
+        processConfigEvents();
+
+        enabledTracks = 0;
+        { // scope for the mLock
+
+            Mutex::Autolock _l(mLock);
+
+            if (checkForNewParameters_l()) {
+                mixBufferSize = mFrameCount*mFrameSize;
+            }
+
+            const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
+
+            for (size_t i = 0; i < mOutputTracks.size(); i++) {
+                outputTracks.add(mOutputTracks[i]);
+            }
+
+            // put audio hardware into standby after short delay
+            if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
+                         mSuspended) {
+                if (!mStandby) {
+                    for (size_t i = 0; i < outputTracks.size(); i++) {
+                        mLock.unlock();
+                        outputTracks[i]->stop();
+                        mLock.lock();
+                    }
+                    mStandby = true;
+                    mBytesWritten = 0;
+                }
+
+                if (!activeTracks.size() && mConfigEvents.isEmpty()) {
+                    // we're about to wait, flush the binder command buffer
+                    IPCThreadState::self()->flushCommands();
+                    outputTracks.clear();
+
+                    if (exitPending()) break;
+
+                    LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
+                    mWaitWorkCV.wait(mLock);
+                    LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
+                    if (mMasterMute == false) {
+                        char value[PROPERTY_VALUE_MAX];
+                        property_get("ro.audio.silent", value, "0");
+                        if (atoi(value)) {
+                            LOGD("Silence is golden");
+                            setMasterMute(true);
+                        }
+                    }
+
+                    standbyTime = systemTime() + kStandbyTimeInNsecs;
+                    sleepTime = kBufferRecoveryInUsecs;
+                    continue;
+                }
+            }
+
+            enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
+       }
+
+        bool mustSleep = true;
+        if (LIKELY(enabledTracks)) {
+            // mix buffers...
+            mAudioMixer->process(curBuf);
+            if (!mSuspended) {
+                for (size_t i = 0; i < outputTracks.size(); i++) {
+                    outputTracks[i]->write(curBuf, mFrameCount);
+                }
+                mStandby = false;
+                mustSleep = false;
+                mBytesWritten += mixBufferSize;
+            }
+        } else {
+            // flush remaining overflow buffers in output tracks
+            for (size_t i = 0; i < outputTracks.size(); i++) {
+                if (outputTracks[i]->isActive()) {
+                    outputTracks[i]->write(curBuf, 0);
+                    standbyTime = systemTime() + kStandbyTimeInNsecs;
+                    mustSleep = false;
+                }
+            }
+        }
+        if (mustSleep) {
+//            LOGV("threadLoop() sleeping %d", sleepTime);
+            usleep(sleepTime);
+            if (sleepTime < kMaxBufferRecoveryInUsecs) {
+                sleepTime += kBufferRecoveryInUsecs;
+            }
+        } else {
+            sleepTime = kBufferRecoveryInUsecs;
+        }
+
+        // finally let go of all our tracks, without the lock held
+        // since we can't guarantee the destructors won't acquire that
+        // same lock.
+        tracksToRemove.clear();
+        outputTracks.clear();
+    }
+
+    if (!mStandby) {
+        for (size_t i = 0; i < outputTracks.size(); i++) {
+            mLock.unlock();
+            outputTracks[i]->stop();
+            mLock.lock();
+        }
+    }
+
+    sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
+    processConfigEvents();
+
+    return false;
+}
+
+void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
+{
+    int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
+    OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
+                                            mSampleRate,
+                                            mFormat,
+                                            mChannelCount,
+                                            frameCount);
+    thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
+    mOutputTracks.add(outputTrack);
+    LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
+}
+
+void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
+{
+    Mutex::Autolock _l(mLock);
+    for (size_t i = 0; i < mOutputTracks.size(); i++) {
+        if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
+            mOutputTracks.removeAt(i);
+            return;
+        }
+    }
+    LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
+}
+
+
+// ----------------------------------------------------------------------------
+
 // TrackBase constructor must be called with AudioFlinger::mLock held
-AudioFlinger::MixerThread::TrackBase::TrackBase(
-            const sp<MixerThread>& mixerThread,
+AudioFlinger::ThreadBase::TrackBase::TrackBase(
+            const wp<ThreadBase>& thread,
             const sp<Client>& client,
             uint32_t sampleRate,
             int format,
@@ -1566,7 +1950,7 @@
             uint32_t flags,
             const sp<IMemory>& sharedBuffer)
     :   RefBase(),
-        mMixerThread(mixerThread),
+        mThread(thread),
         mClient(client),
         mFrameCount(0),
         mState(IDLE),
@@ -1574,13 +1958,6 @@
         mFormat(format),
         mFlags(flags & ~SYSTEM_FLAGS_MASK)
 {
-    mName = mixerThread->getTrackName_l();
-    LOGV("TrackBase contructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
-    if (mName < 0) {
-        LOGE("no more track names availlable");
-        return;
-    }
-
     LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
 
     // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
@@ -1634,16 +2011,19 @@
    }
 }
 
-AudioFlinger::MixerThread::TrackBase::~TrackBase()
+AudioFlinger::PlaybackThread::TrackBase::~TrackBase()
 {
     if (mCblk) {
-        mCblk->~audio_track_cblk_t();   // destroy our shared-structure.        
+        mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
+        if (mClient == NULL) {
+            delete mCblk;
+        }
     }
     mCblkMemory.clear();            // and free the shared memory
     mClient.clear();
 }
 
-void AudioFlinger::MixerThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
+void AudioFlinger::PlaybackThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
 {
     buffer->raw = 0;
     mFrameCount = buffer->frameCount;
@@ -1651,7 +2031,7 @@
     buffer->frameCount = 0;
 }
 
-bool AudioFlinger::MixerThread::TrackBase::step() {
+bool AudioFlinger::PlaybackThread::TrackBase::step() {
     bool result;
     audio_track_cblk_t* cblk = this->cblk();
 
@@ -1663,7 +2043,7 @@
     return result;
 }
 
-void AudioFlinger::MixerThread::TrackBase::reset() {
+void AudioFlinger::PlaybackThread::TrackBase::reset() {
     audio_track_cblk_t* cblk = this->cblk();
 
     cblk->user = 0;
@@ -1674,27 +2054,27 @@
     LOGV("TrackBase::reset");
 }
 
-sp<IMemory> AudioFlinger::MixerThread::TrackBase::getCblk() const
+sp<IMemory> AudioFlinger::PlaybackThread::TrackBase::getCblk() const
 {
     return mCblkMemory;
 }
 
-int AudioFlinger::MixerThread::TrackBase::sampleRate() const {
+int AudioFlinger::PlaybackThread::TrackBase::sampleRate() const {
     return (int)mCblk->sampleRate;
 }
 
-int AudioFlinger::MixerThread::TrackBase::channelCount() const {
+int AudioFlinger::PlaybackThread::TrackBase::channelCount() const {
     return (int)mCblk->channels;
 }
 
-void* AudioFlinger::MixerThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
+void* AudioFlinger::PlaybackThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
     audio_track_cblk_t* cblk = this->cblk();
-    int16_t *bufferStart = (int16_t *)mBuffer + (offset-cblk->serverBase)*cblk->channels;
-    int16_t *bufferEnd = bufferStart + frames * cblk->channels;
+    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
+    int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
 
     // Check validity of returned pointer in case the track control block would have been corrupted.
-    if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd || 
-        (cblk->channels == 2 && ((unsigned long)bufferStart & 3))) {
+    if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
+        ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
         LOGE("TrackBase::getBuffer buffer out of range:\n    start: %p, end %p , mBuffer %p mBufferEnd %p\n    \
                 server %d, serverBase %d, user %d, userBase %d, channels %d",
                 bufferStart, bufferEnd, mBuffer, mBufferEnd,
@@ -1707,9 +2087,9 @@
 
 // ----------------------------------------------------------------------------
 
-// Track constructor must be called with AudioFlinger::mLock held
-AudioFlinger::MixerThread::Track::Track(
-            const sp<MixerThread>& mixerThread,
+// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
+AudioFlinger::PlaybackThread::Track::Track(
+            const wp<ThreadBase>& thread,
             const sp<Client>& client,
             int streamType,
             uint32_t sampleRate,
@@ -1717,40 +2097,58 @@
             int channelCount,
             int frameCount,
             const sp<IMemory>& sharedBuffer)
-    :   TrackBase(mixerThread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer)
+    :   TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
+    mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
 {
+    sp<ThreadBase> baseThread = thread.promote();
+    if (baseThread != 0) {
+        PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
+        mName = playbackThread->getTrackName_l();
+    }
+    LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
+    if (mName < 0) {
+        LOGE("no more track names available");
+    }
     mVolume[0] = 1.0f;
     mVolume[1] = 1.0f;
-    mMute = false;
-    mSharedBuffer = sharedBuffer;
     mStreamType = streamType;
+    // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
+    // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
+    mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
 }
 
-AudioFlinger::MixerThread::Track::~Track()
+AudioFlinger::PlaybackThread::Track::~Track()
 {
-    wp<Track> weak(this); // never create a strong ref from the dtor
-    Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
-    mState = TERMINATED;
-}
-
-void AudioFlinger::MixerThread::Track::destroy()
-{
-    // NOTE: destroyTrack_l() can remove a strong reference to this Track 
-    // by removing it from mTracks vector, so there is a risk that this Tracks's
-    // desctructor is called. As the destructor needs to lock AudioFlinger::mLock,
-    // we must acquire a strong reference on this Track before locking AudioFlinger::mLock
-    // here so that the destructor is called only when exiting this function.
-    // On the other hand, as long as Track::destroy() is only called by 
-    // TrackHandle destructor, the TrackHandle still holds a strong ref on 
-    // this Track with its member mTrack.
-    sp<Track> keep(this);
-    { // scope for AudioFlinger::mLock
-        Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
-        mMixerThread->destroyTrack_l(this);
+    LOGV("PlaybackThread::Track destructor");
+    sp<ThreadBase> thread = mThread.promote();
+    if (thread != 0) {
+        Mutex::Autolock _l(thread->mLock);
+        mState = TERMINATED;
     }
 }
 
-void AudioFlinger::MixerThread::Track::dump(char* buffer, size_t size)
+void AudioFlinger::PlaybackThread::Track::destroy()
+{
+    // NOTE: destroyTrack_l() can remove a strong reference to this Track
+    // by removing it from mTracks vector, so there is a risk that this Tracks's
+    // desctructor is called. As the destructor needs to lock mLock,
+    // we must acquire a strong reference on this Track before locking mLock
+    // here so that the destructor is called only when exiting this function.
+    // On the other hand, as long as Track::destroy() is only called by
+    // TrackHandle destructor, the TrackHandle still holds a strong ref on
+    // this Track with its member mTrack.
+    sp<Track> keep(this);
+    { // scope for mLock
+        sp<ThreadBase> thread = mThread.promote();
+        if (thread != 0) {
+            Mutex::Autolock _l(thread->mLock);
+            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
+            playbackThread->destroyTrack_l(this);
+        }
+    }
+}
+
+void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
 {
     snprintf(buffer, size, "  %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
             mName - AudioMixer::TRACK0,
@@ -1769,7 +2167,7 @@
             mCblk->user);
 }
 
-status_t AudioFlinger::MixerThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
+status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
 {
      audio_track_cblk_t* cblk = this->cblk();
      uint32_t framesReady;
@@ -1806,76 +2204,90 @@
 getNextBuffer_exit:
      buffer->raw = 0;
      buffer->frameCount = 0;
+     LOGV("getNextBuffer() no more data");
      return NOT_ENOUGH_DATA;
 }
 
-bool AudioFlinger::MixerThread::Track::isReady() const {
+bool AudioFlinger::PlaybackThread::Track::isReady() const {
     if (mFillingUpStatus != FS_FILLING) return true;
 
     if (mCblk->framesReady() >= mCblk->frameCount ||
         mCblk->forceReady) {
         mFillingUpStatus = FS_FILLED;
         mCblk->forceReady = 0;
-        LOGV("Track::isReady() track %d for output %d", mName, mMixerThread->mOutputType);
         return true;
     }
     return false;
 }
 
-status_t AudioFlinger::MixerThread::Track::start()
+status_t AudioFlinger::PlaybackThread::Track::start()
 {
-    LOGV("start(%d), calling thread %d for output %d", mName, IPCThreadState::self()->getCallingPid(), mMixerThread->mOutputType);
-    Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
-    mMixerThread->addTrack_l(this);
+    LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
+    sp<ThreadBase> thread = mThread.promote();
+    if (thread != 0) {
+        Mutex::Autolock _l(thread->mLock);
+        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
+        playbackThread->addTrack_l(this);
+    }
     return NO_ERROR;
 }
 
-void AudioFlinger::MixerThread::Track::stop()
+void AudioFlinger::PlaybackThread::Track::stop()
 {
-    LOGV("stop(%d), calling thread %d for output %d", mName, IPCThreadState::self()->getCallingPid(), mMixerThread->mOutputType);
-    Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
-    if (mState > STOPPED) {
-        mState = STOPPED;
-        // If the track is not active (PAUSED and buffers full), flush buffers
-        if (mMixerThread->mActiveTracks.indexOf(this) < 0) {
-            reset();
+    LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
+    sp<ThreadBase> thread = mThread.promote();
+    if (thread != 0) {
+        Mutex::Autolock _l(thread->mLock);
+        if (mState > STOPPED) {
+            mState = STOPPED;
+            // If the track is not active (PAUSED and buffers full), flush buffers
+            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
+            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
+                reset();
+            }
+            LOGV("(> STOPPED) => STOPPED (%d)", mName);
         }
-        LOGV("(> STOPPED) => STOPPED (%d)", mName);
     }
 }
 
-void AudioFlinger::MixerThread::Track::pause()
+void AudioFlinger::PlaybackThread::Track::pause()
 {
     LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
-    Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
-    if (mState == ACTIVE || mState == RESUMING) {
-        mState = PAUSING;
-        LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
+    sp<ThreadBase> thread = mThread.promote();
+    if (thread != 0) {
+        Mutex::Autolock _l(thread->mLock);
+        if (mState == ACTIVE || mState == RESUMING) {
+            mState = PAUSING;
+            LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
+        }
     }
 }
 
-void AudioFlinger::MixerThread::Track::flush()
+void AudioFlinger::PlaybackThread::Track::flush()
 {
     LOGV("flush(%d)", mName);
-    Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
-    if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
-        return;
-    }
-    // No point remaining in PAUSED state after a flush => go to
-    // STOPPED state
-    mState = STOPPED;
+    sp<ThreadBase> thread = mThread.promote();
+    if (thread != 0) {
+        Mutex::Autolock _l(thread->mLock);
+        if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
+            return;
+        }
+        // No point remaining in PAUSED state after a flush => go to
+        // STOPPED state
+        mState = STOPPED;
 
-    mCblk->lock.lock();
-    // NOTE: reset() will reset cblk->user and cblk->server with
-    // the risk that at the same time, the AudioMixer is trying to read
-    // data. In this case, getNextBuffer() would return a NULL pointer
-    // as audio buffer => the AudioMixer code MUST always test that pointer
-    // returned by getNextBuffer() is not NULL!
-    reset();
-    mCblk->lock.unlock();
+        mCblk->lock.lock();
+        // NOTE: reset() will reset cblk->user and cblk->server with
+        // the risk that at the same time, the AudioMixer is trying to read
+        // data. In this case, getNextBuffer() would return a NULL pointer
+        // as audio buffer => the AudioMixer code MUST always test that pointer
+        // returned by getNextBuffer() is not NULL!
+        reset();
+        mCblk->lock.unlock();
+    }
 }
 
-void AudioFlinger::MixerThread::Track::reset()
+void AudioFlinger::PlaybackThread::Track::reset()
 {
     // Do not reset twice to avoid discarding data written just after a flush and before
     // the audioflinger thread detects the track is stopped.
@@ -1885,17 +2297,17 @@
         // written to buffer
         mCblk->flowControlFlag = 1;
         mCblk->forceReady = 0;
-        mFillingUpStatus = FS_FILLING;        
+        mFillingUpStatus = FS_FILLING;
         mResetDone = true;
     }
 }
 
-void AudioFlinger::MixerThread::Track::mute(bool muted)
+void AudioFlinger::PlaybackThread::Track::mute(bool muted)
 {
     mMute = muted;
 }
 
-void AudioFlinger::MixerThread::Track::setVolume(float left, float right)
+void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
 {
     mVolume[0] = left;
     mVolume[1] = right;
@@ -1904,28 +2316,33 @@
 // ----------------------------------------------------------------------------
 
 // RecordTrack constructor must be called with AudioFlinger::mLock held
-AudioFlinger::MixerThread::RecordTrack::RecordTrack(
-            const sp<MixerThread>& mixerThread,
+AudioFlinger::RecordThread::RecordTrack::RecordTrack(
+            const wp<ThreadBase>& thread,
             const sp<Client>& client,
-            int inputSource,
             uint32_t sampleRate,
             int format,
             int channelCount,
             int frameCount,
             uint32_t flags)
-    :   TrackBase(mixerThread, client, sampleRate, format,
+    :   TrackBase(thread, client, sampleRate, format,
                   channelCount, frameCount, flags, 0),
-        mOverflow(false), mInputSource(inputSource)
+        mOverflow(false)
+{
+   LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
+   if (format == AudioSystem::PCM_16_BIT) {
+       mCblk->frameSize = channelCount * sizeof(int16_t);
+   } else if (format == AudioSystem::PCM_8_BIT) {
+       mCblk->frameSize = channelCount * sizeof(int8_t);
+   } else {
+       mCblk->frameSize = sizeof(int8_t);
+   }
+}
+
+AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
 {
 }
 
-AudioFlinger::MixerThread::RecordTrack::~RecordTrack()
-{
-    Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
-    mMixerThread->deleteTrackName_l(mName);
-}
-
-status_t AudioFlinger::MixerThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
+status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
 {
     audio_track_cblk_t* cblk = this->cblk();
     uint32_t framesAvail;
@@ -1964,180 +2381,231 @@
     return NOT_ENOUGH_DATA;
 }
 
-status_t AudioFlinger::MixerThread::RecordTrack::start()
+status_t AudioFlinger::RecordThread::RecordTrack::start()
 {
-    return mMixerThread->mAudioFlinger->startRecord(this);
+    sp<ThreadBase> thread = mThread.promote();
+    if (thread != 0) {
+        RecordThread *recordThread = (RecordThread *)thread.get();
+        return recordThread->start(this);
+    }
+    return NO_INIT;
 }
 
-void AudioFlinger::MixerThread::RecordTrack::stop()
+void AudioFlinger::RecordThread::RecordTrack::stop()
 {
-    mMixerThread->mAudioFlinger->stopRecord(this);
-    TrackBase::reset();
-    // Force overerrun condition to avoid false overrun callback until first data is
-    // read from buffer
-    mCblk->flowControlFlag = 1;
+    sp<ThreadBase> thread = mThread.promote();
+    if (thread != 0) {
+        RecordThread *recordThread = (RecordThread *)thread.get();
+        recordThread->stop(this);
+        TrackBase::reset();
+        // Force overerrun condition to avoid false overrun callback until first data is
+        // read from buffer
+        mCblk->flowControlFlag = 1;
+    }
 }
 
 
 // ----------------------------------------------------------------------------
 
-AudioFlinger::MixerThread::OutputTrack::OutputTrack(
-            const sp<MixerThread>& mixerThread,
+AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
+            const wp<ThreadBase>& thread,
             uint32_t sampleRate,
             int format,
             int channelCount,
             int frameCount)
-    :   Track(mixerThread, NULL, AudioSystem::SYSTEM, sampleRate, format, channelCount, frameCount, NULL),
-    mOutputMixerThread(mixerThread)
+    :   Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
+    mActive(false)
 {
-                
+
+    PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
     mCblk->out = 1;
     mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
     mCblk->volume[0] = mCblk->volume[1] = 0x1000;
     mOutBuffer.frameCount = 0;
-    mCblk->bufferTimeoutMs = 10;
-    
-    LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p", 
-            mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd);
-    
+    mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
+
+    LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
+            mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
+
 }
 
-AudioFlinger::MixerThread::OutputTrack::~OutputTrack()
+AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
 {
     stop();
 }
 
-status_t AudioFlinger::MixerThread::OutputTrack::start()
+status_t AudioFlinger::PlaybackThread::OutputTrack::start()
 {
     status_t status = Track::start();
-    
+    if (status != NO_ERROR) {
+        return status;
+    }
+
+    mActive = true;
     mRetryCount = 127;
     return status;
 }
 
-void AudioFlinger::MixerThread::OutputTrack::stop()
+void AudioFlinger::PlaybackThread::OutputTrack::stop()
 {
     Track::stop();
     clearBufferQueue();
     mOutBuffer.frameCount = 0;
+    mActive = false;
 }
 
-void AudioFlinger::MixerThread::OutputTrack::write(int16_t* data, uint32_t frames)
+bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
 {
     Buffer *pInBuffer;
     Buffer inBuffer;
     uint32_t channels = mCblk->channels;
-        
+    bool outputBufferFull = false;
     inBuffer.frameCount = frames;
     inBuffer.i16 = data;
-    
-    if (mCblk->user == 0) {
-        mOutputMixerThread->mAudioFlinger->mLock.lock();
-        bool isMusicActive = mOutputMixerThread->isMusicActive_l();
-        mOutputMixerThread->mAudioFlinger->mLock.unlock();
-        if (isMusicActive) {
-            mCblk->forceReady = 1;
-            LOGV("OutputTrack::start() force ready");
-        } else if (mCblk->frameCount > frames){
-            if (mBufferQueue.size() < kMaxOutputTrackBuffers) {
-                uint32_t startFrames = (mCblk->frameCount - frames);
-                LOGV("OutputTrack::start() write %d frames", startFrames);
-                pInBuffer = new Buffer;
-                pInBuffer->mBuffer = new int16_t[startFrames * channels];
-                pInBuffer->frameCount = startFrames;
-                pInBuffer->i16 = pInBuffer->mBuffer;
-                memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
-                mBufferQueue.add(pInBuffer);                
-            } else {
-                LOGW ("OutputTrack::write() no more buffers");
+
+    uint32_t waitTimeLeftMs = mWaitTimeMs;
+
+    if (!mActive) {
+        start();
+        sp<ThreadBase> thread = mThread.promote();
+        if (thread != 0) {
+            MixerThread *mixerThread = (MixerThread *)thread.get();
+            if (mCblk->frameCount > frames){
+                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
+                    uint32_t startFrames = (mCblk->frameCount - frames);
+                    pInBuffer = new Buffer;
+                    pInBuffer->mBuffer = new int16_t[startFrames * channels];
+                    pInBuffer->frameCount = startFrames;
+                    pInBuffer->i16 = pInBuffer->mBuffer;
+                    memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
+                    mBufferQueue.add(pInBuffer);
+                } else {
+                    LOGW ("OutputTrack::write() %p no more buffers in queue", this);
+                }
             }
-        }        
+        }
     }
 
-    while (1) { 
+    while (waitTimeLeftMs) {
         // First write pending buffers, then new data
         if (mBufferQueue.size()) {
             pInBuffer = mBufferQueue.itemAt(0);
         } else {
             pInBuffer = &inBuffer;
         }
- 
+
         if (pInBuffer->frameCount == 0) {
             break;
         }
-        
+
         if (mOutBuffer.frameCount == 0) {
             mOutBuffer.frameCount = pInBuffer->frameCount;
-            if (obtainBuffer(&mOutBuffer) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
+            nsecs_t startTime = systemTime();
+            if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
+                LOGV ("OutputTrack::write() %p no more output buffers", this);
+                outputBufferFull = true;
                 break;
             }
+            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
+//            LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
+            if (waitTimeLeftMs >= waitTimeMs) {
+                waitTimeLeftMs -= waitTimeMs;
+            } else {
+                waitTimeLeftMs = 0;
+            }
         }
-            
+
         uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
         memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
         mCblk->stepUser(outFrames);
         pInBuffer->frameCount -= outFrames;
         pInBuffer->i16 += outFrames * channels;
         mOutBuffer.frameCount -= outFrames;
-        mOutBuffer.i16 += outFrames * channels;            
-        
+        mOutBuffer.i16 += outFrames * channels;
+
         if (pInBuffer->frameCount == 0) {
             if (mBufferQueue.size()) {
                 mBufferQueue.removeAt(0);
                 delete [] pInBuffer->mBuffer;
                 delete pInBuffer;
+                LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
             } else {
                 break;
             }
         }
     }
- 
+
     // If we could not write all frames, allocate a buffer and queue it for next time.
     if (inBuffer.frameCount) {
-        if (mBufferQueue.size() < kMaxOutputTrackBuffers) {
+        if (mBufferQueue.size() < kMaxOverFlowBuffers) {
             pInBuffer = new Buffer;
             pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
             pInBuffer->frameCount = inBuffer.frameCount;
             pInBuffer->i16 = pInBuffer->mBuffer;
             memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
             mBufferQueue.add(pInBuffer);
+            LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
         } else {
-            LOGW("OutputTrack::write() no more buffers");
+            LOGW("OutputTrack::write() %p no more overflow buffers", this);
         }
     }
-    
+
     // Calling write() with a 0 length buffer, means that no more data will be written:
-    // If no more buffers are pending, fill output track buffer to make sure it is started 
+    // If no more buffers are pending, fill output track buffer to make sure it is started
     // by output mixer.
-    if (frames == 0 && mBufferQueue.size() == 0 && mCblk->user < mCblk->frameCount) {
-        frames = mCblk->frameCount - mCblk->user;
-        pInBuffer = new Buffer;
-        pInBuffer->mBuffer = new int16_t[frames * channels];
-        pInBuffer->frameCount = frames;
-        pInBuffer->i16 = pInBuffer->mBuffer;
-        memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
-        mBufferQueue.add(pInBuffer);
+    if (frames == 0 && mBufferQueue.size() == 0) {
+        if (mCblk->user < mCblk->frameCount) {
+            frames = mCblk->frameCount - mCblk->user;
+            pInBuffer = new Buffer;
+            pInBuffer->mBuffer = new int16_t[frames * channels];
+            pInBuffer->frameCount = frames;
+            pInBuffer->i16 = pInBuffer->mBuffer;
+            memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
+            mBufferQueue.add(pInBuffer);
+        } else {
+            stop();
+        }
     }
 
+    return outputBufferFull;
 }
 
-status_t AudioFlinger::MixerThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer)
+status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
 {
     int active;
-    int timeout = 0;
     status_t result;
     audio_track_cblk_t* cblk = mCblk;
     uint32_t framesReq = buffer->frameCount;
 
-    LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
+//    LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
     buffer->frameCount  = 0;
-    
+
     uint32_t framesAvail = cblk->framesAvailable();
 
+
     if (framesAvail == 0) {
-        return AudioTrack::NO_MORE_BUFFERS;
+        Mutex::Autolock _l(cblk->lock);
+        goto start_loop_here;
+        while (framesAvail == 0) {
+            active = mActive;
+            if (UNLIKELY(!active)) {
+                LOGV("Not active and NO_MORE_BUFFERS");
+                return AudioTrack::NO_MORE_BUFFERS;
+            }
+            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
+            if (result != NO_ERROR) {
+                return AudioTrack::NO_MORE_BUFFERS;
+            }
+            // read the server count again
+        start_loop_here:
+            framesAvail = cblk->framesAvailable_l();
+        }
     }
 
+//    if (framesAvail < framesReq) {
+//        return AudioTrack::NO_MORE_BUFFERS;
+//    }
+
     if (framesReq > framesAvail) {
         framesReq = framesAvail;
     }
@@ -2155,11 +2623,11 @@
 }
 
 
-void AudioFlinger::MixerThread::OutputTrack::clearBufferQueue()
+void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
 {
     size_t size = mBufferQueue.size();
     Buffer *pBuffer;
-    
+
     for (size_t i = 0; i < size; i++) {
         pBuffer = mBufferQueue.itemAt(i);
         delete [] pBuffer->mBuffer;
@@ -2191,7 +2659,7 @@
 
 // ----------------------------------------------------------------------------
 
-AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::MixerThread::Track>& track)
+AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
     : BnAudioTrack(),
       mTrack(track)
 {
@@ -2243,7 +2711,7 @@
 
 sp<IAudioRecord> AudioFlinger::openRecord(
         pid_t pid,
-        int inputSource,
+        void *input,
         uint32_t sampleRate,
         int format,
         int channelCount,
@@ -2251,14 +2719,13 @@
         uint32_t flags,
         status_t *status)
 {
-    sp<MixerThread::RecordTrack> recordTrack;
+    sp<RecordThread::RecordTrack> recordTrack;
     sp<RecordHandle> recordHandle;
     sp<Client> client;
     wp<Client> wclient;
-    AudioStreamIn* input = 0;
-    int inFrameCount;
-    size_t inputBufferSize;
     status_t lStatus;
+    RecordThread *thread;
+    size_t inFrameCount;
 
     // check calling permissions
     if (!recordingAllowed()) {
@@ -2266,30 +2733,15 @@
         goto Exit;
     }
 
-    if (uint32_t(inputSource) >= AudioRecord::NUM_INPUT_SOURCES) {
-        LOGE("invalid stream type");
-        lStatus = BAD_VALUE;
-        goto Exit;
-    }
-
-    if (mAudioRecordThread == 0) {
-        LOGE("Audio record thread not started");
-        lStatus = NO_INIT;
-        goto Exit;
-    }
-
-
-    // Check that audio input stream accepts requested audio parameters 
-    inputBufferSize = mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
-    if (inputBufferSize == 0) {
-        lStatus = BAD_VALUE;
-        LOGE("Bad audio input parameters: sampling rate %u, format %d, channels %d",  sampleRate, format, channelCount);
-        goto Exit;
-    }
-
     // add client to list
     { // scope for mLock
         Mutex::Autolock _l(mLock);
+        thread = checkRecordThread_l(input);
+        if (thread == NULL) {
+            lStatus = BAD_VALUE;
+            goto Exit;
+        }
+
         wclient = mClients.valueFor(pid);
         if (wclient != NULL) {
             client = wclient.promote();
@@ -2298,12 +2750,8 @@
             mClients.add(pid, client);
         }
 
-        // frameCount must be a multiple of input buffer size
-        inFrameCount = inputBufferSize/channelCount/sizeof(short);
-        frameCount = ((frameCount - 1)/inFrameCount + 1) * inFrameCount;
-    
         // create new record track. The record track uses one track in mHardwareMixerThread by convention.
-        recordTrack = new MixerThread::RecordTrack(mHardwareMixerThread, client, inputSource, sampleRate,
+        recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
                                                    format, channelCount, frameCount, flags);
     }
     if (recordTrack->getCblk() == NULL) {
@@ -2323,22 +2771,9 @@
     return recordHandle;
 }
 
-status_t AudioFlinger::startRecord(MixerThread::RecordTrack* recordTrack) {
-    if (mAudioRecordThread != 0) {
-        return mAudioRecordThread->start(recordTrack);        
-    }
-    return NO_INIT;
-}
-
-void AudioFlinger::stopRecord(MixerThread::RecordTrack* recordTrack) {
-    if (mAudioRecordThread != 0) {
-        mAudioRecordThread->stop(recordTrack);
-    }
-}
-
 // ----------------------------------------------------------------------------
 
-AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::MixerThread::RecordTrack>& recordTrack)
+AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
     : BnAudioRecord(),
     mRecordTrack(recordTrack)
 {
@@ -2370,86 +2805,165 @@
 
 // ----------------------------------------------------------------------------
 
-AudioFlinger::AudioRecordThread::AudioRecordThread(AudioHardwareInterface* audioHardware,
-            const sp<AudioFlinger>& audioFlinger) :
-    mAudioHardware(audioHardware),
-    mAudioFlinger(audioFlinger),
-    mActive(false)
+AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
+    ThreadBase(audioFlinger),
+    mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
 {
+    mReqChannelCount = AudioSystem::popCount(channels);
+    mReqSampleRate = sampleRate;
+    readInputParameters();
+    sendConfigEvent(AudioSystem::INPUT_OPENED);
 }
 
-AudioFlinger::AudioRecordThread::~AudioRecordThread()
+
+AudioFlinger::RecordThread::~RecordThread()
 {
+    mAudioFlinger->mAudioHardware->closeInputStream(mInput);
+    delete[] mRsmpInBuffer;
+    if (mResampler != 0) {
+        delete mResampler;
+        delete[] mRsmpOutBuffer;
+    }
 }
 
-bool AudioFlinger::AudioRecordThread::threadLoop()
+void AudioFlinger::RecordThread::onFirstRef()
 {
-    LOGV("AudioRecordThread: start record loop");
+    const size_t SIZE = 256;
+    char buffer[SIZE];
+
+    snprintf(buffer, SIZE, "Record Thread %p", this);
+
+    run(buffer, PRIORITY_URGENT_AUDIO);
+}
+bool AudioFlinger::RecordThread::threadLoop()
+{
     AudioBufferProvider::Buffer buffer;
-    int inBufferSize = 0;
-    int inFrameCount = 0;
-    AudioStreamIn* input = 0;
+    sp<RecordTrack> activeTrack;
 
-    mActive = 0;
-    
     // start recording
     while (!exitPending()) {
-        if (!mActive) {
-            mLock.lock();
-            if (!mActive && !exitPending()) {
-                LOGV("AudioRecordThread: loop stopping");
-                if (input) {
-                    delete input;
-                    input = 0;
-                }
-                mRecordTrack.clear();
-                mStopped.signal();
 
+        processConfigEvents();
+
+        { // scope for mLock
+            Mutex::Autolock _l(mLock);
+            checkForNewParameters_l();
+            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
+                if (!mStandby) {
+                    mInput->standby();
+                    mStandby = true;
+                }
+
+                if (exitPending()) break;
+
+                LOGV("RecordThread: loop stopping");
+                // go to sleep
                 mWaitWorkCV.wait(mLock);
-               
-                LOGV("AudioRecordThread: loop starting");
-                if (mRecordTrack != 0) {
-                    input = mAudioHardware->openInputStream(
-                                    mRecordTrack->inputSource(),
-                                    mRecordTrack->format(), 
-                                    mRecordTrack->channelCount(), 
-                                    mRecordTrack->sampleRate(), 
-                                    &mStartStatus,
-                                    (AudioSystem::audio_in_acoustics)(mRecordTrack->mFlags >> 16));
-                    if (input != 0) {
-                        inBufferSize = input->bufferSize();
-                        inFrameCount = inBufferSize/input->frameSize();                        
+                LOGV("RecordThread: loop starting");
+                continue;
+            }
+            if (mActiveTrack != 0) {
+                if (mActiveTrack->mState == TrackBase::PAUSING) {
+                    mActiveTrack.clear();
+                    mStartStopCond.broadcast();
+                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
+                    mRsmpInIndex = mFrameCount;
+                    if (mReqChannelCount != mActiveTrack->channelCount()) {
+                        mActiveTrack.clear();
+                    } else {
+                        mActiveTrack->mState == TrackBase::ACTIVE;
+                    }
+                    mStartStopCond.broadcast();
+                }
+                mStandby = false;
+            }
+        }
+
+        if (mActiveTrack != 0) {
+            buffer.frameCount = mFrameCount;
+            if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
+                size_t framesOut = buffer.frameCount;
+                if (mResampler == 0) {
+                    // no resampling
+                    while (framesOut) {
+                        size_t framesIn = mFrameCount - mRsmpInIndex;
+                        if (framesIn) {
+                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
+                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
+                            if (framesIn > framesOut)
+                                framesIn = framesOut;
+                            mRsmpInIndex += framesIn;
+                            framesOut -= framesIn;
+                            if (mChannelCount == mReqChannelCount ||
+                                mFormat != AudioSystem::PCM_16_BIT) {
+                                memcpy(dst, src, framesIn * mFrameSize);
+                            } else {
+                                int16_t *src16 = (int16_t *)src;
+                                int16_t *dst16 = (int16_t *)dst;
+                                if (mChannelCount == 1) {
+                                    while (framesIn--) {
+                                        *dst16++ = *src16;
+                                        *dst16++ = *src16++;
+                                    }
+                                } else {
+                                    while (framesIn--) {
+                                        *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
+                                        src16 += 2;
+                                    }
+                                }
+                            }
+                        }
+                        if (framesOut && mFrameCount == mRsmpInIndex) {
+                            ssize_t bytesRead;
+                            if (framesOut == mFrameCount &&
+                                (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
+                                bytesRead = mInput->read(buffer.raw, mInputBytes);
+                                framesOut = 0;
+                            } else {
+                                bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
+                                mRsmpInIndex = 0;
+                            }
+                            if (bytesRead < 0) {
+                                LOGE("Error reading audio input");
+                                sleep(1);
+                                mRsmpInIndex = mFrameCount;
+                                framesOut = 0;
+                                buffer.frameCount = 0;
+                            }
+                        }
                     }
                 } else {
-                    mStartStatus = NO_INIT;
-                }
-                if (mStartStatus !=NO_ERROR) {
-                    LOGW("record start failed, status %d", mStartStatus);
-                    mActive = false;
-                    mRecordTrack.clear();                    
-                }
-                mWaitWorkCV.signal();
-            }
-            mLock.unlock();
-        } else if (mRecordTrack != 0) {
+                    // resampling
 
-            buffer.frameCount = inFrameCount;
-            if (LIKELY(mRecordTrack->getNextBuffer(&buffer) == NO_ERROR &&
-                       (int)buffer.frameCount == inFrameCount)) {
-                LOGV("AudioRecordThread read: %d frames", buffer.frameCount);
-                ssize_t bytesRead = input->read(buffer.raw, inBufferSize);
-                if (bytesRead < 0) {
-                    LOGE("Error reading audio input");
-                    sleep(1);
-                }
-                mRecordTrack->releaseBuffer(&buffer);
-                mRecordTrack->overflow();
-            }
+                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
+                    // alter output frame count as if we were expecting stereo samples
+                    if (mChannelCount == 1 && mReqChannelCount == 1) {
+                        framesOut >>= 1;
+                    }
+                    mResampler->resample(mRsmpOutBuffer, framesOut, this);
+                    // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
+                    // are 32 bit aligned which should be always true.
+                    if (mChannelCount == 2 && mReqChannelCount == 1) {
+                        AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
+                        // the resampler always outputs stereo samples: do post stereo to mono conversion
+                        int16_t *src = (int16_t *)mRsmpOutBuffer;
+                        int16_t *dst = buffer.i16;
+                        while (framesOut--) {
+                            *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
+                            src += 2;
+                        }
+                    } else {
+                        AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
+                    }
 
+                }
+                mActiveTrack->releaseBuffer(&buffer);
+                mActiveTrack->overflow();
+            }
             // client isn't retrieving buffers fast enough
             else {
-                if (!mRecordTrack->setOverflow())
-                    LOGW("AudioRecordThread: buffer overflow");
+                if (!mActiveTrack->setOverflow())
+                    LOGW("RecordThread: buffer overflow");
                 // Release the processor for a while before asking for a new buffer.
                 // This will give the application more chance to read from the buffer and
                 // clear the overflow.
@@ -2458,65 +2972,64 @@
         }
     }
 
-
-    if (input) {
-        delete input;
+    if (!mStandby) {
+        mInput->standby();
     }
-    mRecordTrack.clear();
-    
+    mActiveTrack.clear();
+
+    sendConfigEvent(AudioSystem::INPUT_CLOSED);
+    processConfigEvents();
+
+    LOGV("RecordThread %p exiting", this);
     return false;
 }
 
-status_t AudioFlinger::AudioRecordThread::start(MixerThread::RecordTrack* recordTrack)
+status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
 {
-    LOGV("AudioRecordThread::start");
+    LOGV("RecordThread::start");
     AutoMutex lock(&mLock);
-    mActive = true;
-    // If starting the active track, just reset mActive in case a stop
-    // was pending and exit
-    if (recordTrack == mRecordTrack.get()) return NO_ERROR;
 
-    if (mRecordTrack != 0) return -EBUSY;
+    if (mActiveTrack != 0) {
+        if (recordTrack != mActiveTrack.get()) return -EBUSY;
 
-    mRecordTrack = recordTrack;
+        if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
 
+        return NO_ERROR;
+    }
+
+    mActiveTrack = recordTrack;
+    mActiveTrack->mState = TrackBase::RESUMING;
     // signal thread to start
     LOGV("Signal record thread");
     mWaitWorkCV.signal();
-    mWaitWorkCV.wait(mLock);
-    LOGV("Record started, status %d", mStartStatus);
-    return mStartStatus;
+    mStartStopCond.wait(mLock);
+    if (mActiveTrack != 0) {
+        LOGV("Record started OK");
+        return NO_ERROR;
+    } else {
+        LOGV("Record failed to start");
+        return BAD_VALUE;
+    }
 }
 
-void AudioFlinger::AudioRecordThread::stop(MixerThread::RecordTrack* recordTrack) {
-    LOGV("AudioRecordThread::stop");
+void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
+    LOGV("RecordThread::stop");
     AutoMutex lock(&mLock);
-    if (mActive && (recordTrack == mRecordTrack.get())) {
-        mActive = false;
-        mStopped.wait(mLock);
+    if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
+        mActiveTrack->mState = TrackBase::PAUSING;
+        mStartStopCond.wait(mLock);
     }
 }
 
-void AudioFlinger::AudioRecordThread::exit()
-{
-    LOGV("AudioRecordThread::exit");
-    {
-        AutoMutex lock(&mLock);
-        requestExit();
-        mWaitWorkCV.signal();
-    }
-    requestExitAndWait();
-}
-
-status_t AudioFlinger::AudioRecordThread::dump(int fd, const Vector<String16>& args)
+status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
 {
     const size_t SIZE = 256;
     char buffer[SIZE];
     String8 result;
     pid_t pid = 0;
 
-    if (mRecordTrack != 0 && mRecordTrack->mClient != 0) {
-        snprintf(buffer, SIZE, "Record client pid: %d\n", mRecordTrack->mClient->pid());
+    if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
+        snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
         result.append(buffer);
     } else {
         result.append("No record client\n");
@@ -2525,6 +3038,463 @@
     return NO_ERROR;
 }
 
+status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
+{
+    size_t framesReq = buffer->frameCount;
+    size_t framesReady = mFrameCount - mRsmpInIndex;
+    int channelCount;
+
+    if (framesReady == 0) {
+        ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
+        if (bytesRead < 0) {
+            LOGE("RecordThread::getNextBuffer() Error reading audio input");
+            sleep(1);
+            buffer->raw = 0;
+            buffer->frameCount = 0;
+            return NOT_ENOUGH_DATA;
+        }
+        mRsmpInIndex = 0;
+        framesReady = mFrameCount;
+    }
+
+    if (framesReq > framesReady) {
+        framesReq = framesReady;
+    }
+
+    if (mChannelCount == 1 && mReqChannelCount == 2) {
+        channelCount = 1;
+    } else {
+        channelCount = 2;
+    }
+    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
+    buffer->frameCount = framesReq;
+    return NO_ERROR;
+}
+
+void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
+{
+    mRsmpInIndex += buffer->frameCount;
+    buffer->frameCount = 0;
+}
+
+bool AudioFlinger::RecordThread::checkForNewParameters_l()
+{
+    bool reconfig = false;
+
+    if (mNewParameters != "") {
+        status_t status = NO_ERROR;
+        AudioParameter param = AudioParameter(mNewParameters);
+        int value;
+        int reqFormat = mFormat;
+        int reqSamplingRate = mReqSampleRate;
+        int reqChannelCount = mReqChannelCount;
+        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
+            reqSamplingRate = value;
+            reconfig = true;
+        }
+        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
+            reqFormat = value;
+            reconfig = true;
+        }
+        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
+            reqChannelCount = AudioSystem::popCount(value);
+            reconfig = true;
+        }
+        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
+            // do not accept frame count changes if tracks are open as the track buffer
+            // size depends on frame count and correct behavior would not be garantied
+            // if frame count is changed after track creation
+            if (mActiveTrack != 0) {
+                status = INVALID_OPERATION;
+            } else {
+                reconfig = true;
+            }
+        }
+        if (status == NO_ERROR) {
+            status = mInput->setParameters(mNewParameters);
+            if (status == INVALID_OPERATION) {
+               mInput->standby();
+               status = mInput->setParameters(mNewParameters);
+            }
+            if (reconfig) {
+                if (status == BAD_VALUE &&
+                    reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
+                    ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
+                    (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
+                    status = NO_ERROR;
+                }
+                if (status == NO_ERROR) {
+                    readInputParameters();
+                    sendConfigEvent(AudioSystem::INPUT_CONFIG_CHANGED);
+                }
+            }
+        }
+        mNewParameters = "";
+        mParamStatus = status;
+        mParamCond.signal();
+    }
+    return reconfig;
+}
+
+String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
+{
+    return mInput->getParameters(keys);
+}
+
+void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
+    AudioSystem::OutputDescriptor desc;
+    void *param2 = 0;
+
+    switch (event) {
+    case AudioSystem::INPUT_OPENED:
+    case AudioSystem::INPUT_CONFIG_CHANGED:
+        desc.channels = mChannelCount;
+        desc.samplingRate = mSampleRate;
+        desc.format = mFormat;
+        desc.frameCount = mFrameCount;
+        desc.latency = 0;
+        param2 = &desc;
+        break;
+
+    case AudioSystem::INPUT_CLOSED:
+    default:
+        break;
+    }
+    mAudioFlinger->audioConfigChanged(event, this, param2);
+}
+
+void AudioFlinger::RecordThread::readInputParameters()
+{
+    if (mRsmpInBuffer) delete mRsmpInBuffer;
+    if (mRsmpOutBuffer) delete mRsmpOutBuffer;
+    if (mResampler) delete mResampler;
+    mResampler = 0;
+
+    mSampleRate = mInput->sampleRate();
+    mChannelCount = AudioSystem::popCount(mInput->channels());
+    mFormat = mInput->format();
+    mFrameSize = mInput->frameSize();
+    mInputBytes = mInput->bufferSize();
+    mFrameCount = mInputBytes / mFrameSize;
+    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
+
+    if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
+    {
+        int channelCount;
+         // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
+         // stereo to mono post process as the resampler always outputs stereo.
+        if (mChannelCount == 1 && mReqChannelCount == 2) {
+            channelCount = 1;
+        } else {
+            channelCount = 2;
+        }
+        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
+        mResampler->setSampleRate(mSampleRate);
+        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
+        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
+
+        // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
+        if (mChannelCount == 1 && mReqChannelCount == 1) {
+            mFrameCount >>= 1;
+        }
+
+    }
+    mRsmpInIndex = mFrameCount;
+}
+
+// ----------------------------------------------------------------------------
+
+void *AudioFlinger::openOutput(uint32_t *pDevices,
+                                uint32_t *pSamplingRate,
+                                uint32_t *pFormat,
+                                uint32_t *pChannels,
+                                uint32_t *pLatencyMs,
+                                uint32_t flags)
+{
+    status_t status;
+    PlaybackThread *thread = NULL;
+    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
+    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
+    uint32_t format = pFormat ? *pFormat : 0;
+    uint32_t channels = pChannels ? *pChannels : 0;
+    uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
+
+    LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
+            pDevices ? *pDevices : 0,
+            samplingRate,
+            format,
+            channels,
+            flags);
+
+    if (pDevices == NULL || *pDevices == 0) {
+        return NULL;
+    }
+    Mutex::Autolock _l(mLock);
+
+    AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
+                                                             (int *)&format,
+                                                             &channels,
+                                                             &samplingRate,
+                                                             &status);
+    LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
+            output,
+            samplingRate,
+            format,
+            channels,
+            status);
+
+    mHardwareStatus = AUDIO_HW_IDLE;
+    if (output != 0) {
+        if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
+            (format != AudioSystem::PCM_16_BIT) ||
+            (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
+            thread = new DirectOutputThread(this, output);
+            LOGV("openOutput() created direct output %p", thread);
+        } else {
+            thread = new MixerThread(this, output);
+            LOGV("openOutput() created mixer output %p", thread);
+        }
+        mPlaybackThreads.add(thread);
+
+        if (pSamplingRate) *pSamplingRate = samplingRate;
+        if (pFormat) *pFormat = format;
+        if (pChannels) *pChannels = channels;
+        if (pLatencyMs) *pLatencyMs = thread->latency();
+    }
+
+    return thread;
+}
+
+void *AudioFlinger::openDuplicateOutput(void *output1, void *output2)
+{
+    Mutex::Autolock _l(mLock);
+
+    if (checkMixerThread_l(output1) == NULL ||
+        checkMixerThread_l(output2) == NULL) {
+        LOGW("openDuplicateOutput() wrong output mixer type %p or %p", output1, output2);
+        return NULL;
+    }
+
+    DuplicatingThread *thread = new DuplicatingThread(this, (MixerThread *)output1);
+    thread->addOutputTrack( (MixerThread *)output2);
+    mPlaybackThreads.add(thread);
+    return thread;
+}
+
+status_t AudioFlinger::closeOutput(void *output)
+{
+    PlaybackThread *thread;
+    {
+        Mutex::Autolock _l(mLock);
+        thread = checkPlaybackThread_l(output);
+        if (thread == NULL) {
+            return BAD_VALUE;
+        }
+
+        LOGV("closeOutput() %p", thread);
+
+        if (thread->type() == PlaybackThread::MIXER) {
+            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
+                if (mPlaybackThreads[i]->type() == PlaybackThread::DUPLICATING) {
+                    DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads[i].get();
+                    dupThread->removeOutputTrack((MixerThread *)thread);
+                }
+            }
+        }
+        mPlaybackThreads.remove(thread);
+    }
+    thread->exit();
+
+    return NO_ERROR;
+}
+
+status_t AudioFlinger::suspendOutput(void *output)
+{
+    Mutex::Autolock _l(mLock);
+    PlaybackThread *thread = checkPlaybackThread_l(output);
+
+    if (thread == NULL) {
+        return BAD_VALUE;
+    }
+
+    LOGV("suspendOutput() %p", output);
+    thread->suspend();
+
+    return NO_ERROR;
+}
+
+status_t AudioFlinger::restoreOutput(void *output)
+{
+    Mutex::Autolock _l(mLock);
+    PlaybackThread *thread = checkPlaybackThread_l(output);
+
+    if (thread == NULL) {
+        return BAD_VALUE;
+    }
+
+    LOGV("restoreOutput() %p", output);
+
+    thread->restore();
+
+    return NO_ERROR;
+}
+
+void *AudioFlinger::openInput(uint32_t *pDevices,
+                                uint32_t *pSamplingRate,
+                                uint32_t *pFormat,
+                                uint32_t *pChannels,
+                                uint32_t acoustics)
+{
+    status_t status;
+    RecordThread *thread = NULL;
+    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
+    uint32_t format = pFormat ? *pFormat : 0;
+    uint32_t channels = pChannels ? *pChannels : 0;
+    uint32_t reqSamplingRate = samplingRate;
+    uint32_t reqFormat = format;
+    uint32_t reqChannels = channels;
+
+    if (pDevices == NULL || *pDevices == 0) {
+        return NULL;
+    }
+    Mutex::Autolock _l(mLock);
+
+    AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
+                                                             (int *)&format,
+                                                             &channels,
+                                                             &samplingRate,
+                                                             &status,
+                                                             (AudioSystem::audio_in_acoustics)acoustics);
+    LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
+            input,
+            samplingRate,
+            format,
+            channels,
+            acoustics,
+            status);
+
+    // If the input could not be opened with the requested parameters and we can handle the conversion internally,
+    // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
+    // or stereo to mono conversions on 16 bit PCM inputs.
+    if (input == 0 && status == BAD_VALUE &&
+        reqFormat == format && format == AudioSystem::PCM_16_BIT &&
+        (samplingRate <= 2 * reqSamplingRate) &&
+        (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
+        LOGV("openInput() reopening with proposed sampling rate and channels");
+        input = mAudioHardware->openInputStream(*pDevices,
+                                                 (int *)&format,
+                                                 &channels,
+                                                 &samplingRate,
+                                                 &status,
+                                                 (AudioSystem::audio_in_acoustics)acoustics);
+    }
+
+    if (input != 0) {
+         // Start record thread
+        thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
+        mRecordThreads.add(thread);
+
+        if (pSamplingRate) *pSamplingRate = reqSamplingRate;
+        if (pFormat) *pFormat = format;
+        if (pChannels) *pChannels = reqChannels;
+
+        input->standby();
+    }
+
+    return thread;
+}
+
+status_t AudioFlinger::closeInput(void *input)
+{
+    RecordThread *thread;
+    {
+        Mutex::Autolock _l(mLock);
+        thread = checkRecordThread_l(input);
+        if (thread == NULL) {
+            return BAD_VALUE;
+        }
+
+        LOGV("closeInput() %p", thread);
+        mRecordThreads.remove(thread);
+    }
+    thread->exit();
+
+    return NO_ERROR;
+}
+
+status_t AudioFlinger::setStreamOutput(uint32_t stream, void *output)
+{
+    Mutex::Autolock _l(mLock);
+    MixerThread *dstThread = checkMixerThread_l(output);
+    if (dstThread == NULL) {
+        LOGW("setStreamOutput() bad output thread %p", output);
+        return BAD_VALUE;
+    }
+
+    LOGV("setStreamOutput() stream %d to output %p", stream, dstThread);
+
+    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
+        PlaybackThread *thread = mPlaybackThreads[i].get();
+        if (thread != dstThread &&
+            thread->type() != PlaybackThread::DIRECT) {
+            MixerThread *srcThread = (MixerThread *)thread;
+            SortedVector < sp<MixerThread::Track> > tracks;
+            SortedVector < wp<MixerThread::Track> > activeTracks;
+            srcThread->getTracks(tracks, activeTracks, stream);
+            if (tracks.size()) {
+                dstThread->putTracks(tracks, activeTracks);
+                dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
+            }
+        }
+    }
+
+    return NO_ERROR;
+}
+
+// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
+AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(void *output) const
+{
+    PlaybackThread *thread = NULL;
+
+    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
+        if (mPlaybackThreads[i] == output) {
+            thread = (PlaybackThread *)output;
+            break;
+        }
+    }
+
+    return thread;
+}
+
+// checkMixerThread_l() must be called with AudioFlinger::mLock held
+AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(void *output) const
+{
+    PlaybackThread *thread = checkPlaybackThread_l(output);
+    if (thread != NULL) {
+        if (thread->type() == PlaybackThread::DIRECT) {
+            thread = NULL;
+        }
+    }
+    return (MixerThread *)thread;
+}
+
+// checkRecordThread_l() must be called with AudioFlinger::mLock held
+AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(void *input) const
+{
+    RecordThread *thread = NULL;
+
+    for (size_t i = 0; i < mRecordThreads.size(); i++) {
+        if (mRecordThreads[i] == input) {
+            thread = (RecordThread *)input;
+            break;
+        }
+    }
+
+    return thread;
+}
+
+// ----------------------------------------------------------------------------
+
 status_t AudioFlinger::onTransact(
         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
@@ -2532,6 +3502,7 @@
 }
 
 // ----------------------------------------------------------------------------
+
 void AudioFlinger::instantiate() {
     defaultServiceManager()->addService(
             String16("media.audio_flinger"), new AudioFlinger());
diff --git a/libs/audioflinger/AudioFlinger.h b/libs/audioflinger/AudioFlinger.h
index 634934e..06c5846 100644
--- a/libs/audioflinger/AudioFlinger.h
+++ b/libs/audioflinger/AudioFlinger.h
@@ -30,8 +30,7 @@
 #include <utils/Atomic.h>
 #include <utils/Errors.h>
 #include <utils/threads.h>
-#include <utils/MemoryDealer.h>
-#include <utils/KeyedVector.h>
+#include <binder/MemoryDealer.h>
 #include <utils/SortedVector.h>
 #include <utils/Vector.h>
 
@@ -44,6 +43,7 @@
 class audio_track_cblk_t;
 class AudioMixer;
 class AudioBuffer;
+class AudioResampler;
 
 
 // ----------------------------------------------------------------------------
@@ -56,7 +56,7 @@
 
 static const nsecs_t kStandbyTimeInNsecs = seconds(3);
 
-class AudioFlinger : public BnAudioFlinger, public IBinder::DeathRecipient 
+class AudioFlinger : public BnAudioFlinger, public IBinder::DeathRecipient
 {
 public:
     static void instantiate();
@@ -73,13 +73,14 @@
                                 int frameCount,
                                 uint32_t flags,
                                 const sp<IMemory>& sharedBuffer,
+                                void *output,
                                 status_t *status);
 
-    virtual     uint32_t    sampleRate(int output) const;
-    virtual     int         channelCount(int output) const;
-    virtual     int         format(int output) const;
-    virtual     size_t      frameCount(int output) const;
-    virtual     uint32_t    latency(int output) const;
+    virtual     uint32_t    sampleRate(void *output) const;
+    virtual     int         channelCount(void *output) const;
+    virtual     int         format(void *output) const;
+    virtual     size_t      frameCount(void *output) const;
+    virtual     uint32_t    latency(void *output) const;
 
     virtual     status_t    setMasterVolume(float value);
     virtual     status_t    setMasterMute(bool muted);
@@ -87,33 +88,51 @@
     virtual     float       masterVolume() const;
     virtual     bool        masterMute() const;
 
-    virtual     status_t    setStreamVolume(int stream, float value);
+    virtual     status_t    setStreamVolume(int stream, float value, void *output);
     virtual     status_t    setStreamMute(int stream, bool muted);
 
-    virtual     float       streamVolume(int stream) const;
+    virtual     float       streamVolume(int stream, void *output) const;
     virtual     bool        streamMute(int stream) const;
 
-    virtual     status_t    setRouting(int mode, uint32_t routes, uint32_t mask);
-    virtual     uint32_t    getRouting(int mode) const;
-
     virtual     status_t    setMode(int mode);
-    virtual     int         getMode() const;
 
     virtual     status_t    setMicMute(bool state);
     virtual     bool        getMicMute() const;
 
     virtual     bool        isMusicActive() const;
 
-    virtual     bool        isA2dpEnabled() const;
-
-    virtual     status_t    setParameter(const char* key, const char* value);
+    virtual     status_t    setParameters(void *ioHandle, const String8& keyValuePairs);
+    virtual     String8     getParameters(void *ioHandle, const String8& keys);
 
     virtual     void        registerClient(const sp<IAudioFlingerClient>& client);
-    
+
     virtual     size_t      getInputBufferSize(uint32_t sampleRate, int format, int channelCount);
-    
-    virtual     void        wakeUp()    { mWaitWorkCV.broadcast(); }
-    
+
+    virtual void *openOutput(uint32_t *pDevices,
+                                    uint32_t *pSamplingRate,
+                                    uint32_t *pFormat,
+                                    uint32_t *pChannels,
+                                    uint32_t *pLatencyMs,
+                                    uint32_t flags);
+
+    virtual void *openDuplicateOutput(void *output1, void *output2);
+
+    virtual status_t closeOutput(void *output);
+
+    virtual status_t suspendOutput(void *output);
+
+    virtual status_t restoreOutput(void *output);
+
+    virtual void *openInput(uint32_t *pDevices,
+                            uint32_t *pSamplingRate,
+                            uint32_t *pFormat,
+                            uint32_t *pChannels,
+                            uint32_t acoustics);
+
+    virtual status_t closeInput(void *input);
+
+    virtual status_t setStreamOutput(uint32_t stream, void *output);
+
     // IBinder::DeathRecipient
     virtual     void        binderDied(const wp<IBinder>& who);
 
@@ -139,7 +158,7 @@
     // record interface
     virtual sp<IAudioRecord> openRecord(
                                 pid_t pid,
-                                int inputSource,
+                                void *input,
                                 uint32_t sampleRate,
                                 int format,
                                 int channelCount,
@@ -153,30 +172,12 @@
                                 Parcel* reply,
                                 uint32_t flags);
 
+    void audioConfigChanged(int event, void *param1, void *param2);
+
 private:
                             AudioFlinger();
     virtual                 ~AudioFlinger();
-    
-    void                    setOutput(int outputType);
-    void                    doSetOutput(int outputType);
 
-#ifdef WITH_A2DP
-    void                    setA2dpEnabled_l(bool enable);
-    void                    checkA2dpEnabledChange_l();
-#endif
-    static bool             streamForcedToSpeaker(int streamType);
-    
-    // Management of forced route to speaker for certain track types.
-    enum force_speaker_command {
-        ACTIVE_TRACK_ADDED = 0,
-        ACTIVE_TRACK_REMOVED,
-        CHECK_ROUTE_RESTORE_TIME,
-        FORCE_ROUTE_RESTORE
-    };
-    void                    handleForcedSpeakerRoute(int command);
-#ifdef WITH_A2DP
-    void                    handleRouteDisablesA2dp_l(int routes);
-#endif
 
     // Internal dump utilites.
     status_t dumpPermissionDenial(int fd, const Vector<String16>& args);
@@ -201,14 +202,17 @@
 
     class TrackHandle;
     class RecordHandle;
-    class AudioRecordThread;
+    class RecordThread;
+    class PlaybackThread;
+    class MixerThread;
+    class DirectOutputThread;
+    class Track;
+    class RecordTrack;
 
-    
-    // --- MixerThread ---
-    class MixerThread : public Thread {
+    class ThreadBase : public Thread {
     public:
-        
-        // --- Track ---
+        ThreadBase (const sp<AudioFlinger>& audioFlinger);
+        virtual             ~ThreadBase();
 
         // base for record and playback
         class TrackBase : public AudioBufferProvider, public RefBase {
@@ -230,7 +234,7 @@
                 // The upper 16 bits are used for track-specific flags.
             };
 
-                                TrackBase(const sp<MixerThread>& mixerThread,
+                                TrackBase(const wp<ThreadBase>& thread,
                                         const sp<Client>& client,
                                         uint32_t sampleRate,
                                         int format,
@@ -245,9 +249,12 @@
                     sp<IMemory> getCblk() const;
 
         protected:
-            friend class MixerThread;
+            friend class ThreadBase;
             friend class RecordHandle;
-            friend class AudioRecordThread;
+            friend class PlaybackThread;
+            friend class RecordThread;
+            friend class MixerThread;
+            friend class DirectOutputThread;
 
                                 TrackBase(const TrackBase&);
                                 TrackBase& operator = (const TrackBase&);
@@ -269,10 +276,6 @@
 
             void* getBuffer(uint32_t offset, uint32_t frames) const;
 
-            int name() const {
-                return mName;
-            }
-
             bool isStopped() const {
                 return mState == STOPPED;
             }
@@ -284,14 +287,13 @@
             bool step();
             void reset();
 
-            sp<MixerThread>     mMixerThread;
+            wp<ThreadBase>      mThread;
             sp<Client>          mClient;
             sp<IMemory>         mCblkMemory;
             audio_track_cblk_t* mCblk;
             void*               mBuffer;
             void*               mBufferEnd;
             uint32_t            mFrameCount;
-            int                 mName;
             // we don't really need a lock for these
             int                 mState;
             int                 mClientTid;
@@ -299,10 +301,68 @@
             uint32_t            mFlags;
         };
 
+        class ConfigEvent {
+        public:
+            ConfigEvent() : mEvent(0), mParam(0) {}
+
+            int mEvent;
+            int mParam;
+        };
+
+                    uint32_t    sampleRate() const;
+                    int         channelCount() const;
+                    int         format() const;
+                    size_t      frameCount() const;
+                    void        wakeUp()    { mWaitWorkCV.broadcast(); }
+                    void        exit();
+        virtual     bool        checkForNewParameters_l() = 0;
+        virtual     status_t    setParameters(const String8& keyValuePairs);
+        virtual     String8     getParameters(const String8& keys) = 0;
+        virtual     void        audioConfigChanged(int event, int param = 0) = 0;
+                    void        sendConfigEvent(int event, int param = 0);
+                    void        processConfigEvents();
+
+        mutable     Mutex                   mLock;
+
+    protected:
+
+        friend class Track;
+        friend class TrackBase;
+        friend class PlaybackThread;
+        friend class MixerThread;
+        friend class DirectOutputThread;
+        friend class DuplicatingThread;
+        friend class RecordThread;
+        friend class RecordTrack;
+
+                    Condition               mWaitWorkCV;
+                    sp<AudioFlinger>        mAudioFlinger;
+                    uint32_t                mSampleRate;
+                    size_t                  mFrameCount;
+                    int                     mChannelCount;
+                    int                     mFormat;
+                    uint32_t                mFrameSize;
+                    Condition               mParamCond;
+                    String8                 mNewParameters;
+                    status_t                mParamStatus;
+                    Vector<ConfigEvent *>   mConfigEvents;
+                    bool                    mStandby;
+    };
+
+    // --- PlaybackThread ---
+    class PlaybackThread : public ThreadBase {
+    public:
+
+        enum type {
+            MIXER,
+            DIRECT,
+            DUPLICATING
+        };
+
         // playback track
         class Track : public TrackBase {
         public:
-                                Track(  const sp<MixerThread>& mixerThread,
+                                Track(  const wp<ThreadBase>& thread,
                                         const sp<Client>& client,
                                         int streamType,
                                         uint32_t sampleRate,
@@ -321,6 +381,9 @@
                     void        destroy();
                     void        mute(bool);
                     void        setVolume(float left, float right);
+                    int name() const {
+                        return mName;
+                    }
 
                     int type() const {
                         return mStreamType;
@@ -328,29 +391,25 @@
 
 
         protected:
-            friend class MixerThread;
+            friend class ThreadBase;
             friend class AudioFlinger;
-            friend class AudioFlinger::TrackHandle;
+            friend class TrackHandle;
+            friend class PlaybackThread;
+            friend class MixerThread;
+            friend class DirectOutputThread;
 
                                 Track(const Track&);
                                 Track& operator = (const Track&);
 
             virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
-
-            bool isMuted() const {
-                return (mMute || mMixerThread->mStreamTypes[mStreamType].mute);
-            }
-
+            bool isMuted() { return mMute; }
             bool isPausing() const {
                 return mState == PAUSING;
             }
-
             bool isPaused() const {
                 return mState == PAUSED;
             }
-
             bool isReady() const;
-
             void setPaused() { mState = PAUSED; }
             void reset();
 
@@ -364,54 +423,20 @@
             sp<IMemory>         mSharedBuffer;
             bool                mResetDone;
             int                 mStreamType;
+            int                 mName;
         };  // end of Track
 
-        // record track
-        class RecordTrack : public TrackBase {
-        public:
-                                RecordTrack(const sp<MixerThread>& mixerThread,
-                                        const sp<Client>& client,
-                                        int inputSource,
-                                        uint32_t sampleRate,
-                                        int format,
-                                        int channelCount,
-                                        int frameCount,
-                                        uint32_t flags);
-                                ~RecordTrack();
-
-            virtual status_t    start();
-            virtual void        stop();
-
-                    bool        overflow() { bool tmp = mOverflow; mOverflow = false; return tmp; }
-                    bool        setOverflow() { bool tmp = mOverflow; mOverflow = true; return tmp; }
-
-                    int         inputSource() const { return mInputSource; }
-
-        private:
-            friend class AudioFlinger;
-            friend class AudioFlinger::RecordHandle;
-            friend class AudioFlinger::AudioRecordThread;
-            friend class MixerThread;
-
-                                RecordTrack(const Track&);
-                                RecordTrack& operator = (const Track&);
-
-            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
-
-            bool                mOverflow;
-            int                 mInputSource;
-        };
 
         // playback track
         class OutputTrack : public Track {
         public:
-            
+
             class Buffer: public AudioBufferProvider::Buffer {
             public:
                 int16_t *mBuffer;
             };
-            
-                                OutputTrack(  const sp<MixerThread>& mixerThread,
+
+                                OutputTrack(  const wp<ThreadBase>& thread,
                                         uint32_t sampleRate,
                                         int format,
                                         int channelCount,
@@ -420,35 +445,35 @@
 
             virtual status_t    start();
             virtual void        stop();
-                    void        write(int16_t* data, uint32_t frames);
+                    bool        write(int16_t* data, uint32_t frames);
                     bool        bufferQueueEmpty() { return (mBufferQueue.size() == 0) ? true : false; }
+                    bool        isActive() { return mActive; }
+            wp<ThreadBase>&     thread()  { return mThread; }
 
         private:
 
-            status_t            obtainBuffer(AudioBufferProvider::Buffer* buffer);
+            status_t            obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs);
             void                clearBufferQueue();
-            
-            sp<MixerThread>             mOutputMixerThread;
+
+            // Maximum number of pending buffers allocated by OutputTrack::write()
+            static const uint8_t kMaxOverFlowBuffers = 3;
+
             Vector < Buffer* >          mBufferQueue;
             AudioBufferProvider::Buffer mOutBuffer;
-            uint32_t                    mFramesWritten;
-            
-         };  // end of OutputTrack
+            uint32_t                    mWaitTimeMs;
+            bool                        mActive;
 
-        MixerThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int outputType);
-        virtual             ~MixerThread();
+        };  // end of OutputTrack
+
+        PlaybackThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output);
+        virtual             ~PlaybackThread();
 
         virtual     status_t    dump(int fd, const Vector<String16>& args);
 
         // Thread virtuals
-        virtual     bool        threadLoop();
         virtual     status_t    readyToRun();
         virtual     void        onFirstRef();
 
-        virtual     uint32_t    sampleRate() const;
-        virtual     int         channelCount() const;
-        virtual     int         format() const;
-        virtual     size_t      frameCount() const;
         virtual     uint32_t    latency() const;
 
         virtual     status_t    setMasterVolume(float value);
@@ -463,9 +488,8 @@
         virtual     float       streamVolume(int stream) const;
         virtual     bool        streamMute(int stream) const;
 
-                    bool        isMusicActive_l() const;
-        
-                    
+                    bool        isMusicActive() const;
+
                     sp<Track>   createTrack_l(
                                     const sp<AudioFlinger::Client>& client,
                                     int streamType,
@@ -475,13 +499,15 @@
                                     int frameCount,
                                     const sp<IMemory>& sharedBuffer,
                                     status_t *status);
-                    
-                    void        getTracks_l(SortedVector < sp<Track> >& tracks,
-                                          SortedVector < wp<Track> >& activeTracks);
-                    void        putTracks_l(SortedVector < sp<Track> >& tracks,
-                                          SortedVector < wp<Track> >& activeTracks);
-                    void        setOuputTrack(OutputTrack *track) { mOutputTrack = track; }
-                    
+
+                    AudioStreamOut* getOutput() { return mOutput; }
+
+        virtual     int         type() const { return mType; }
+                    void        suspend() { mSuspended = true; }
+                    void        restore() { mSuspended = false; }
+        virtual     String8     getParameters(const String8& keys);
+        virtual     void        audioConfigChanged(int event, int param = 0);
+
         struct  stream_type_t {
             stream_type_t()
                 :   volume(1.0f),
@@ -492,56 +518,113 @@
             bool        mute;
         };
 
-    private:
+    protected:
+        int                             mType;
+        int16_t*                        mMixBuffer;
+        bool                            mSuspended;
+        int                             mBytesWritten;
+        bool                            mMasterMute;
+        SortedVector< wp<Track> >       mActiveTracks;
 
+    private:
 
         friend class AudioFlinger;
         friend class Track;
         friend class TrackBase;
-        friend class RecordTrack;
-        
-        MixerThread(const Client&);
-        MixerThread& operator = (const MixerThread&);
-  
+        friend class MixerThread;
+        friend class DirectOutputThread;
+        friend class DuplicatingThread;
+
+        PlaybackThread(const Client&);
+        PlaybackThread& operator = (const PlaybackThread&);
+
         status_t    addTrack_l(const sp<Track>& track);
         void        destroyTrack_l(const sp<Track>& track);
-        int         getTrackName_l();
-        void        deleteTrackName_l(int name);
-        void        addActiveTrack_l(const wp<Track>& t);
-        void        removeActiveTrack_l(const wp<Track>& t);
-        size_t      getOutputFrameCount();
+        virtual int         getTrackName_l() = 0;
+        virtual void        deleteTrackName_l(int name) = 0;
+        void        readOutputParameters();
 
-        status_t    dumpInternals(int fd, const Vector<String16>& args);
+        virtual status_t    dumpInternals(int fd, const Vector<String16>& args);
         status_t    dumpTracks(int fd, const Vector<String16>& args);
-        
-        sp<AudioFlinger>                mAudioFlinger;       
-        SortedVector< wp<Track> >       mActiveTracks;
+
         SortedVector< sp<Track> >       mTracks;
-        stream_type_t                   mStreamTypes[AudioSystem::NUM_STREAM_TYPES];
-        AudioMixer*                     mAudioMixer;
+        // mStreamTypes[] uses 1 additionnal stream type internally for the OutputTrack used by DuplicatingThread
+        stream_type_t                   mStreamTypes[AudioSystem::NUM_STREAM_TYPES + 1];
         AudioStreamOut*                 mOutput;
-        int                             mOutputType;
-        uint32_t                        mSampleRate;
-        size_t                          mFrameCount;
-        int                             mChannelCount;
-        int                             mFormat;
-        int16_t*                        mMixBuffer;
         float                           mMasterVolume;
-        bool                            mMasterMute;
         nsecs_t                         mLastWriteTime;
         int                             mNumWrites;
         int                             mNumDelayedWrites;
-        bool                            mStandby;
         bool                            mInWrite;
-        sp <OutputTrack>                mOutputTrack;
+        int                             mMinBytesToWrite;
     };
 
-    
+    class MixerThread : public PlaybackThread {
+    public:
+        MixerThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output);
+        virtual             ~MixerThread();
+
+        // Thread virtuals
+        virtual     bool        threadLoop();
+
+                    void        getTracks(SortedVector < sp<Track> >& tracks,
+                                      SortedVector < wp<Track> >& activeTracks,
+                                      int streamType);
+                    void        putTracks(SortedVector < sp<Track> >& tracks,
+                                      SortedVector < wp<Track> >& activeTracks);
+        virtual     int         getTrackName_l();
+        virtual     void        deleteTrackName_l(int name);
+        virtual     bool        checkForNewParameters_l();
+        virtual     status_t    dumpInternals(int fd, const Vector<String16>& args);
+
+    protected:
+        size_t prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove);
+
+        AudioMixer*                     mAudioMixer;
+    };
+
+    class DirectOutputThread : public PlaybackThread {
+    public:
+
+        DirectOutputThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output);
+        ~DirectOutputThread();
+
+        // Thread virtuals
+        virtual     bool        threadLoop();
+
+        virtual     int         getTrackName_l();
+        virtual     void        deleteTrackName_l(int name);
+        virtual     bool        checkForNewParameters_l();
+
+    private:
+        float mLeftVolume;
+        float mRightVolume;
+    };
+
+    class DuplicatingThread : public MixerThread {
+    public:
+        DuplicatingThread (const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread);
+        ~DuplicatingThread();
+
+        // Thread virtuals
+        virtual     bool        threadLoop();
+                    void        addOutputTrack(MixerThread* thread);
+                    void        removeOutputTrack(MixerThread* thread);
+
+    private:
+        SortedVector < sp<OutputTrack> >  mOutputTracks;
+    };
+
+              PlaybackThread *checkPlaybackThread_l(void *output) const;
+              MixerThread *checkMixerThread_l(void *output) const;
+              RecordThread *checkRecordThread_l(void *input) const;
+              float streamVolumeInternal(int stream) const { return mStreamTypes[stream].volume; }
+
     friend class AudioBuffer;
 
     class TrackHandle : public android::BnAudioTrack {
     public:
-                            TrackHandle(const sp<MixerThread::Track>& track);
+                            TrackHandle(const sp<PlaybackThread::Track>& track);
         virtual             ~TrackHandle();
         virtual status_t    start();
         virtual void        stop();
@@ -553,20 +636,91 @@
         virtual status_t onTransact(
             uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
     private:
-        sp<MixerThread::Track> mTrack;
+        sp<PlaybackThread::Track> mTrack;
     };
 
     friend class Client;
-    friend class MixerThread::Track;
+    friend class PlaybackThread::Track;
 
 
                 void        removeClient(pid_t pid);
 
 
+    // record thread
+    class RecordThread : public ThreadBase, public AudioBufferProvider
+    {
+    public:
+
+        // record track
+        class RecordTrack : public TrackBase {
+        public:
+                                RecordTrack(const wp<ThreadBase>& thread,
+                                        const sp<Client>& client,
+                                        uint32_t sampleRate,
+                                        int format,
+                                        int channelCount,
+                                        int frameCount,
+                                        uint32_t flags);
+                                ~RecordTrack();
+
+            virtual status_t    start();
+            virtual void        stop();
+
+                    bool        overflow() { bool tmp = mOverflow; mOverflow = false; return tmp; }
+                    bool        setOverflow() { bool tmp = mOverflow; mOverflow = true; return tmp; }
+
+        private:
+            friend class AudioFlinger;
+            friend class RecordThread;
+
+                                RecordTrack(const RecordTrack&);
+                                RecordTrack& operator = (const RecordTrack&);
+
+            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
+
+            bool                mOverflow;
+        };
+
+
+                RecordThread(const sp<AudioFlinger>& audioFlinger,
+                        AudioStreamIn *input,
+                        uint32_t sampleRate,
+                        uint32_t channels);
+                ~RecordThread();
+
+        virtual bool        threadLoop();
+        virtual status_t    readyToRun() { return NO_ERROR; }
+        virtual void        onFirstRef();
+
+                status_t    start(RecordTrack* recordTrack);
+                void        stop(RecordTrack* recordTrack);
+                status_t    dump(int fd, const Vector<String16>& args);
+                AudioStreamIn* getInput() { return mInput; }
+
+        virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer);
+        virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
+        virtual bool        checkForNewParameters_l();
+        virtual String8     getParameters(const String8& keys);
+        virtual void        audioConfigChanged(int event, int param = 0);
+                void        readInputParameters();
+
+    private:
+                RecordThread();
+                AudioStreamIn                       *mInput;
+                sp<RecordTrack>                     mActiveTrack;
+                Condition                           mStartStopCond;
+                AudioResampler                      *mResampler;
+                int32_t                             *mRsmpOutBuffer;
+                int16_t                             *mRsmpInBuffer;
+                size_t                              mRsmpInIndex;
+                size_t                              mInputBytes;
+                int                                 mReqChannelCount;
+                uint32_t                            mReqSampleRate;
+    };
 
     class RecordHandle : public android::BnAudioRecord {
     public:
-        RecordHandle(const sp<MixerThread::RecordTrack>& recordTrack);
+        RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack);
         virtual             ~RecordHandle();
         virtual status_t    start();
         virtual void        stop();
@@ -574,66 +728,30 @@
         virtual status_t onTransact(
             uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
     private:
-        sp<MixerThread::RecordTrack> mRecordTrack;
+        sp<RecordThread::RecordTrack> mRecordTrack;
     };
 
-    // record thread
-    class AudioRecordThread : public Thread
-    {
-    public:
-        AudioRecordThread(AudioHardwareInterface* audioHardware, const sp<AudioFlinger>& audioFlinger);
-        virtual             ~AudioRecordThread();
-        virtual bool        threadLoop();
-        virtual status_t    readyToRun() { return NO_ERROR; }
-        virtual void        onFirstRef() {}
+    friend class RecordThread;
+    friend class PlaybackThread;
 
-                status_t    start(MixerThread::RecordTrack* recordTrack);
-                void        stop(MixerThread::RecordTrack* recordTrack);
-                void        exit();
-                status_t    dump(int fd, const Vector<String16>& args);
 
-    private:
-                AudioRecordThread();
-                AudioHardwareInterface              *mAudioHardware;
-                sp<AudioFlinger>                    mAudioFlinger;
-                sp<MixerThread::RecordTrack>        mRecordTrack;
-                Mutex                               mLock;
-                Condition                           mWaitWorkCV;
-                Condition                           mStopped;
-                volatile bool                       mActive;
-                status_t                            mStartStatus;
-    };
-
-    friend class AudioRecordThread;
-    friend class MixerThread;
-
-                status_t    startRecord(MixerThread::RecordTrack* recordTrack);
-                void        stopRecord(MixerThread::RecordTrack* recordTrack);
-
-    mutable     Mutex                               mHardwareLock;
     mutable     Mutex                               mLock;
-    mutable     Condition                           mWaitWorkCV;
 
                 DefaultKeyedVector< pid_t, wp<Client> >     mClients;
 
-                sp<MixerThread>                     mA2dpMixerThread;
-                sp<MixerThread>                     mHardwareMixerThread;
+                mutable     Mutex                   mHardwareLock;
                 AudioHardwareInterface*             mAudioHardware;
-                AudioHardwareInterface*             mA2dpAudioInterface;
-                sp<AudioRecordThread>               mAudioRecordThread;
-                bool                                mA2dpEnabled;
-                bool                                mNotifyA2dpChange;
     mutable     int                                 mHardwareStatus;
-                SortedVector< wp<IBinder> >         mNotificationClients;
-                int                                 mForcedSpeakerCount;
-                int                                 mA2dpDisableCount;
 
-                // true if A2DP should resume when mA2dpDisableCount returns to zero
-                bool                                mA2dpSuppressed;
-                uint32_t                            mSavedRoute;
-                uint32_t                            mForcedRoute;
-                nsecs_t                             mRouteRestoreTime;
-                bool                                mMusicMuteSaved;
+
+                SortedVector< sp<PlaybackThread> >  mPlaybackThreads;
+                PlaybackThread::stream_type_t       mStreamTypes[AudioSystem::NUM_STREAM_TYPES];
+                float                               mMasterVolume;
+                bool                                mMasterMute;
+
+                SortedVector< sp<RecordThread> >    mRecordThreads;
+
+                SortedVector< sp<IBinder> >         mNotificationClients;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/libs/audioflinger/AudioHardwareGeneric.cpp b/libs/audioflinger/AudioHardwareGeneric.cpp
index 1e159b8..57874f3 100644
--- a/libs/audioflinger/AudioHardwareGeneric.cpp
+++ b/libs/audioflinger/AudioHardwareGeneric.cpp
@@ -49,8 +49,8 @@
 AudioHardwareGeneric::~AudioHardwareGeneric()
 {
     if (mFd >= 0) ::close(mFd);
-    delete mOutput;
-    delete mInput;
+    closeOutputStream((AudioStreamOut *)mOutput);
+    closeInputStream((AudioStreamIn *)mInput);
 }
 
 status_t AudioHardwareGeneric::initCheck()
@@ -63,7 +63,7 @@
 }
 
 AudioStreamOut* AudioHardwareGeneric::openOutputStream(
-        int format, int channelCount, uint32_t sampleRate, status_t *status)
+        uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status)
 {
     AutoMutex lock(mLock);
 
@@ -77,7 +77,7 @@
 
     // create new output stream
     AudioStreamOutGeneric* out = new AudioStreamOutGeneric();
-    status_t lStatus = out->set(this, mFd, format, channelCount, sampleRate);
+    status_t lStatus = out->set(this, mFd, devices, format, channels, sampleRate);
     if (status) {
         *status = lStatus;
     }
@@ -89,17 +89,19 @@
     return mOutput;
 }
 
-void AudioHardwareGeneric::closeOutputStream(AudioStreamOutGeneric* out) {
-    if (out == mOutput) mOutput = 0;
+void AudioHardwareGeneric::closeOutputStream(AudioStreamOut* out) {
+    if (mOutput && out == mOutput) {
+        delete mOutput;
+        mOutput = 0;
+    }
 }
 
 AudioStreamIn* AudioHardwareGeneric::openInputStream(
-        int inputSource, int format, int channelCount, uint32_t sampleRate,
+        uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate,
         status_t *status, AudioSystem::audio_in_acoustics acoustics)
 {
     // check for valid input source
-    if ((inputSource < AudioRecord::DEFAULT_INPUT) ||
-        (inputSource >= AudioRecord::NUM_INPUT_SOURCES)) {
+    if (!AudioSystem::isInputDevice((AudioSystem::audio_devices)devices)) {
         return 0;
     }
 
@@ -115,7 +117,7 @@
 
     // create new output stream
     AudioStreamInGeneric* in = new AudioStreamInGeneric();
-    status_t lStatus = in->set(this, mFd, format, channelCount, sampleRate, acoustics);
+    status_t lStatus = in->set(this, mFd, devices, format, channels, sampleRate, acoustics);
     if (status) {
         *status = lStatus;
     }
@@ -127,8 +129,11 @@
     return mInput;
 }
 
-void AudioHardwareGeneric::closeInputStream(AudioStreamInGeneric* in) {
-    if (in == mInput) mInput = 0;
+void AudioHardwareGeneric::closeInputStream(AudioStreamIn* in) {
+    if (mInput && in == mInput) {
+        delete mInput;
+        mInput = 0;
+    }
 }
 
 status_t AudioHardwareGeneric::setVoiceVolume(float v)
@@ -185,30 +190,42 @@
 status_t AudioStreamOutGeneric::set(
         AudioHardwareGeneric *hw,
         int fd,
-        int format,
-        int channels,
-        uint32_t rate)
+        uint32_t devices,
+        int *pFormat,
+        uint32_t *pChannels,
+        uint32_t *pRate)
 {
+    int lFormat = pFormat ? *pFormat : 0;
+    uint32_t lChannels = pChannels ? *pChannels : 0;
+    uint32_t lRate = pRate ? *pRate : 0;
+
     // fix up defaults
-    if (format == 0) format = AudioSystem::PCM_16_BIT;
-    if (channels == 0) channels = channelCount();
-    if (rate == 0) rate = sampleRate();
+    if (lFormat == 0) lFormat = format();
+    if (lChannels == 0) lChannels = channels();
+    if (lRate == 0) lRate = sampleRate();
 
     // check values
-    if ((format != AudioSystem::PCM_16_BIT) ||
-            (channels != channelCount()) ||
-            (rate != sampleRate()))
+    if ((lFormat != format()) ||
+            (lChannels != channels()) ||
+            (lRate != sampleRate())) {
+        if (pFormat) *pFormat = format();
+        if (pChannels) *pChannels = channels();
+        if (pRate) *pRate = sampleRate();
         return BAD_VALUE;
+    }
+
+    if (pFormat) *pFormat = lFormat;
+    if (pChannels) *pChannels = lChannels;
+    if (pRate) *pRate = lRate;
 
     mAudioHardware = hw;
     mFd = fd;
+    mDevice = devices;
     return NO_ERROR;
 }
 
 AudioStreamOutGeneric::~AudioStreamOutGeneric()
 {
-    if (mAudioHardware)
-        mAudioHardware->closeOutputStream(this);
 }
 
 ssize_t AudioStreamOutGeneric::write(const void* buffer, size_t bytes)
@@ -234,10 +251,12 @@
     result.append(buffer);
     snprintf(buffer, SIZE, "\tbuffer size: %d\n", bufferSize());
     result.append(buffer);
-    snprintf(buffer, SIZE, "\tchannel count: %d\n", channelCount());
+    snprintf(buffer, SIZE, "\tchannels: %d\n", channels());
     result.append(buffer);
     snprintf(buffer, SIZE, "\tformat: %d\n", format());
     result.append(buffer);
+    snprintf(buffer, SIZE, "\tdevice: %d\n", mDevice);
+    result.append(buffer);
     snprintf(buffer, SIZE, "\tmAudioHardware: %p\n", mAudioHardware);
     result.append(buffer);
     snprintf(buffer, SIZE, "\tmFd: %d\n", mFd);
@@ -246,29 +265,68 @@
     return NO_ERROR;
 }
 
+status_t AudioStreamOutGeneric::setParameters(const String8& keyValuePairs)
+{
+    AudioParameter param = AudioParameter(keyValuePairs);
+    String8 key = String8(AudioParameter::keyRouting);
+    status_t status = NO_ERROR;
+    int device;
+    LOGV("setParameters() %s", keyValuePairs.string());
+
+    if (param.getInt(key, device) == NO_ERROR) {
+        mDevice = device;
+        param.remove(key);
+    }
+
+    if (param.size()) {
+        status = BAD_VALUE;
+    }
+    return status;
+}
+
+String8 AudioStreamOutGeneric::getParameters(const String8& keys)
+{
+    AudioParameter param = AudioParameter(keys);
+    String8 value;
+    String8 key = String8(AudioParameter::keyRouting);
+
+    if (param.get(key, value) == NO_ERROR) {
+        param.addInt(key, (int)mDevice);
+    }
+
+    LOGV("getParameters() %s", param.toString().string());
+    return param.toString();
+}
+
 // ----------------------------------------------------------------------------
 
 // record functions
 status_t AudioStreamInGeneric::set(
         AudioHardwareGeneric *hw,
         int fd,
-        int format,
-        int channels,
-        uint32_t rate,
+        uint32_t devices,
+        int *pFormat,
+        uint32_t *pChannels,
+        uint32_t *pRate,
         AudioSystem::audio_in_acoustics acoustics)
 {
     // FIXME: remove logging
-    LOGD("AudioStreamInGeneric::set(%p, %d, %d, %d, %u)", hw, fd, format, channels, rate);
+    if (pFormat == 0 || pChannels == 0 || pRate == 0) return BAD_VALUE;
+    LOGD("AudioStreamInGeneric::set(%p, %d, %d, %d, %u)", hw, fd, *pFormat, *pChannels, *pRate);
     // check values
-    if ((format != AudioSystem::PCM_16_BIT) ||
-            (channels != channelCount()) ||
-            (rate != sampleRate())) {
+    if ((*pFormat != format()) ||
+        (*pChannels != channels()) ||
+        (*pRate != sampleRate())) {
         LOGE("Error opening input channel");
+        *pFormat = format();
+        *pChannels = channels();
+        *pRate = sampleRate();
         return BAD_VALUE;
     }
 
     mAudioHardware = hw;
     mFd = fd;
+    mDevice = devices;
     return NO_ERROR;
 }
 
@@ -276,14 +334,12 @@
 {
     // FIXME: remove logging
     LOGD("AudioStreamInGeneric destructor");
-    if (mAudioHardware)
-        mAudioHardware->closeInputStream(this);
 }
 
 ssize_t AudioStreamInGeneric::read(void* buffer, ssize_t bytes)
 {
     // FIXME: remove logging
-    LOGD("AudioStreamInGeneric::read(%p, %d) from fd %d", buffer, bytes, mFd);
+    LOGD("AudioStreamInGeneric::read(%p, %d) from fd %d", buffer, (int)bytes, mFd);
     AutoMutex lock(mLock);
     if (mFd < 0) {
         LOGE("Attempt to read from unopened device");
@@ -303,10 +359,12 @@
     result.append(buffer);
     snprintf(buffer, SIZE, "\tbuffer size: %d\n", bufferSize());
     result.append(buffer);
-    snprintf(buffer, SIZE, "\tchannel count: %d\n", channelCount());
+    snprintf(buffer, SIZE, "\tchannels: %d\n", channels());
     result.append(buffer);
     snprintf(buffer, SIZE, "\tformat: %d\n", format());
     result.append(buffer);
+    snprintf(buffer, SIZE, "\tdevice: %d\n", mDevice);
+    result.append(buffer);
     snprintf(buffer, SIZE, "\tmAudioHardware: %p\n", mAudioHardware);
     result.append(buffer);
     snprintf(buffer, SIZE, "\tmFd: %d\n", mFd);
@@ -315,6 +373,39 @@
     return NO_ERROR;
 }
 
+status_t AudioStreamInGeneric::setParameters(const String8& keyValuePairs)
+{
+    AudioParameter param = AudioParameter(keyValuePairs);
+    String8 key = String8(AudioParameter::keyRouting);
+    status_t status = NO_ERROR;
+    int device;
+    LOGV("setParameters() %s", keyValuePairs.string());
+
+    if (param.getInt(key, device) == NO_ERROR) {
+        mDevice = device;
+        param.remove(key);
+    }
+
+    if (param.size()) {
+        status = BAD_VALUE;
+    }
+    return status;
+}
+
+String8 AudioStreamInGeneric::getParameters(const String8& keys)
+{
+    AudioParameter param = AudioParameter(keys);
+    String8 value;
+    String8 key = String8(AudioParameter::keyRouting);
+
+    if (param.get(key, value) == NO_ERROR) {
+        param.addInt(key, (int)mDevice);
+    }
+
+    LOGV("getParameters() %s", param.toString().string());
+    return param.toString();
+}
+
 // ----------------------------------------------------------------------------
 
 }; // namespace android
diff --git a/libs/audioflinger/AudioHardwareGeneric.h b/libs/audioflinger/AudioHardwareGeneric.h
index c89df87..42da413 100644
--- a/libs/audioflinger/AudioHardwareGeneric.h
+++ b/libs/audioflinger/AudioHardwareGeneric.h
@@ -39,24 +39,28 @@
     virtual status_t    set(
             AudioHardwareGeneric *hw,
             int mFd,
-            int format,
-            int channelCount,
-            uint32_t sampleRate);
+            uint32_t devices,
+            int *pFormat,
+            uint32_t *pChannels,
+            uint32_t *pRate);
 
     virtual uint32_t    sampleRate() const { return 44100; }
     virtual size_t      bufferSize() const { return 4096; }
-    virtual int         channelCount() const { return 2; }
+    virtual uint32_t    channels() const { return AudioSystem::CHANNEL_OUT_STEREO; }
     virtual int         format() const { return AudioSystem::PCM_16_BIT; }
     virtual uint32_t    latency() const { return 20; }
-    virtual status_t    setVolume(float volume) { return INVALID_OPERATION; }
+    virtual status_t    setVolume(float left, float right) { return INVALID_OPERATION; }
     virtual ssize_t     write(const void* buffer, size_t bytes);
     virtual status_t    standby();
     virtual status_t    dump(int fd, const Vector<String16>& args);
+    virtual status_t    setParameters(const String8& keyValuePairs);
+    virtual String8     getParameters(const String8& keys);
 
 private:
     AudioHardwareGeneric *mAudioHardware;
     Mutex   mLock;
     int     mFd;
+    uint32_t mDevice;
 };
 
 class AudioStreamInGeneric : public AudioStreamIn {
@@ -67,24 +71,28 @@
     virtual status_t    set(
             AudioHardwareGeneric *hw,
             int mFd,
-            int format,
-            int channelCount,
-            uint32_t sampleRate,
+            uint32_t devices,
+            int *pFormat,
+            uint32_t *pChannels,
+            uint32_t *pRate,
             AudioSystem::audio_in_acoustics acoustics);
 
-    uint32_t    sampleRate() const { return 8000; }
+    virtual uint32_t    sampleRate() const { return 8000; }
     virtual size_t      bufferSize() const { return 320; }
-    virtual int         channelCount() const { return 1; }
+    virtual uint32_t    channels() const { return AudioSystem::CHANNEL_IN_MONO; }
     virtual int         format() const { return AudioSystem::PCM_16_BIT; }
     virtual status_t    setGain(float gain) { return INVALID_OPERATION; }
     virtual ssize_t     read(void* buffer, ssize_t bytes);
     virtual status_t    dump(int fd, const Vector<String16>& args);
     virtual status_t    standby() { return NO_ERROR; }
+    virtual status_t    setParameters(const String8& keyValuePairs);
+    virtual String8     getParameters(const String8& keys);
 
 private:
     AudioHardwareGeneric *mAudioHardware;
     Mutex   mLock;
     int     mFd;
+    uint32_t mDevice;
 };
 
 
@@ -101,28 +109,27 @@
     virtual status_t    setMicMute(bool state);
     virtual status_t    getMicMute(bool* state);
 
-    virtual status_t    setParameter(const char* key, const char* value)
-            { return NO_ERROR; }
-
     // create I/O streams
     virtual AudioStreamOut* openOutputStream(
-            int format=0,
-            int channelCount=0,
-            uint32_t sampleRate=0,
+            uint32_t devices,
+            int *format=0,
+            uint32_t *channels=0,
+            uint32_t *sampleRate=0,
             status_t *status=0);
+    virtual    void        closeOutputStream(AudioStreamOut* out);
 
     virtual AudioStreamIn* openInputStream(
-            int inputSource,
-            int format,
-            int channelCount,
-            uint32_t sampleRate,
+            uint32_t devices,
+            int *format,
+            uint32_t *channels,
+            uint32_t *sampleRate,
             status_t *status,
             AudioSystem::audio_in_acoustics acoustics);
+    virtual    void        closeInputStream(AudioStreamIn* in);
 
             void            closeOutputStream(AudioStreamOutGeneric* out);
             void            closeInputStream(AudioStreamInGeneric* in);
 protected:
-    virtual status_t        doRouting() { return NO_ERROR; }
     virtual status_t        dump(int fd, const Vector<String16>& args);
 
 private:
diff --git a/libs/audioflinger/AudioHardwareInterface.cpp b/libs/audioflinger/AudioHardwareInterface.cpp
index cc1bd8f..37be329 100644
--- a/libs/audioflinger/AudioHardwareInterface.cpp
+++ b/libs/audioflinger/AudioHardwareInterface.cpp
@@ -18,6 +18,7 @@
 #include <cutils/properties.h>
 #include <string.h>
 #include <unistd.h>
+//#define LOG_NDEBUG 0
 
 #define LOG_TAG "AudioHardwareInterface"
 #include <utils/Log.h>
@@ -25,15 +26,17 @@
 
 #include "AudioHardwareStub.h"
 #include "AudioHardwareGeneric.h"
+#ifdef WITH_A2DP
+#include "A2dpAudioInterface.h"
+#endif
 
-//#define DUMP_FLINGER_OUT        // if defined allows recording samples in a file
-#ifdef DUMP_FLINGER_OUT
+#ifdef ENABLE_AUDIO_DUMP
 #include "AudioDumpInterface.h"
 #endif
 
 
 // change to 1 to log routing calls
-#define LOG_ROUTING_CALLS 0
+#define LOG_ROUTING_CALLS 1
 
 namespace android {
 
@@ -48,14 +51,6 @@
     "IN_CALL"
 };
 
-static const char* routeStrings[] =
-{
-    "EARPIECE ",
-    "SPEAKER ",
-    "BLUETOOTH ",
-    "HEADSET ",
-    "BLUETOOTH_A2DP "
-};
 static const char* routeNone = "NONE";
 
 static const char* displayMode(int mode)
@@ -64,22 +59,6 @@
         return routingModeStrings[0];
     return routingModeStrings[mode+3];
 }
-
-static const char* displayRoutes(uint32_t routes)
-{
-    static char routeStr[80];
-    if (routes == 0)
-        return routeNone;
-    routeStr[0] = 0;
-    int bitMask = 1;
-    for (int i = 0; i < 4; ++i, bitMask <<= 1) {
-        if (routes & bitMask) {
-            strcat(routeStr, routeStrings[i]);
-        }
-    }
-    routeStr[strlen(routeStr)-1] = 0;
-    return routeStr;
-}
 #endif
 
 // ----------------------------------------------------------------------------
@@ -112,13 +91,17 @@
         hw = new AudioHardwareStub();
     }
     
-#ifdef DUMP_FLINGER_OUT
+#ifdef WITH_A2DP
+    hw = new A2dpAudioInterface(hw);
+#endif
+
+#ifdef ENABLE_AUDIO_DUMP
     // This code adds a record of buffers in a file to write calls made by AudioFlinger.
     // It replaces the current AudioHardwareInterface object by an intermediate one which
     // will record buffers in a file (after sending them to hardware) for testing purpose.
-    // This feature is enabled by defining symbol DUMP_FLINGER_OUT.
-    // The output file is FLINGER_DUMP_NAME. Pause are not recorded in the file.
-    
+    // This feature is enabled by defining symbol ENABLE_AUDIO_DUMP.
+    // The output file is set with setParameters("test_cmd_file_name=<name>"). Pause are not recorded in the file.
+    LOGV("opening PCM dump interface");
     hw = new AudioDumpInterface(hw);    // replace interface
 #endif
     return hw;
@@ -132,48 +115,9 @@
 
 AudioHardwareBase::AudioHardwareBase()
 {
-    // force a routing update on initialization
-    memset(&mRoutes, 0, sizeof(mRoutes));
     mMode = 0;
 }
 
-// generics for audio routing - the real work is done in doRouting
-status_t AudioHardwareBase::setRouting(int mode, uint32_t routes)
-{
-#if LOG_ROUTING_CALLS
-    LOGD("setRouting: mode=%s, routes=[%s]", displayMode(mode), displayRoutes(routes));
-#endif
-    if (mode == AudioSystem::MODE_CURRENT)
-        mode = mMode;
-    if ((mode < 0) || (mode >= AudioSystem::NUM_MODES))
-        return BAD_VALUE;
-    uint32_t old = mRoutes[mode];
-    mRoutes[mode] = routes;
-    if ((mode != mMode) || (old == routes))
-        return NO_ERROR;
-#if LOG_ROUTING_CALLS
-    const char* oldRouteStr = strdup(displayRoutes(old));
-    LOGD("doRouting: mode=%s, old route=[%s], new route=[%s]",
-           displayMode(mode), oldRouteStr, displayRoutes(routes));
-    delete oldRouteStr;
-#endif
-    return doRouting();
-}
-
-status_t AudioHardwareBase::getRouting(int mode, uint32_t* routes)
-{
-    if (mode == AudioSystem::MODE_CURRENT)
-        mode = mMode;
-    if ((mode < 0) || (mode >= AudioSystem::NUM_MODES))
-        return BAD_VALUE;
-    *routes = mRoutes[mode];
-#if LOG_ROUTING_CALLS
-    LOGD("getRouting: mode=%s, routes=[%s]",
-           displayMode(mode), displayRoutes(*routes));
-#endif
-    return NO_ERROR;
-}
-
 status_t AudioHardwareBase::setMode(int mode)
 {
 #if LOG_ROUTING_CALLS
@@ -182,28 +126,23 @@
     if ((mode < 0) || (mode >= AudioSystem::NUM_MODES))
         return BAD_VALUE;
     if (mMode == mode)
-        return NO_ERROR;
-#if LOG_ROUTING_CALLS
-    LOGD("doRouting: old mode=%s, new mode=%s route=[%s]",
-            displayMode(mMode), displayMode(mode), displayRoutes(mRoutes[mode]));
-#endif
+        return ALREADY_EXISTS;
     mMode = mode;
-    return doRouting();
-}
-
-status_t AudioHardwareBase::getMode(int* mode)
-{
-    // Implement: set audio routing
-    *mode = mMode;
     return NO_ERROR;
 }
 
-status_t AudioHardwareBase::setParameter(const char* key, const char* value)
+// default implementation
+status_t AudioHardwareBase::setParameters(const String8& keyValuePairs)
 {
-    // default implementation is to ignore
     return NO_ERROR;
 }
 
+// default implementation
+String8 AudioHardwareBase::getParameters(const String8& keys)
+{
+    String8 result = String8("");
+    return result;
+}
 
 // default implementation
 size_t AudioHardwareBase::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
@@ -233,10 +172,6 @@
     result.append(buffer);
     snprintf(buffer, SIZE, "\tmMode: %d\n", mMode);
     result.append(buffer);
-    for (int i = 0, n = AudioSystem::NUM_MODES; i < n; ++i) {
-        snprintf(buffer, SIZE, "\tmRoutes[%d]: %d\n", i, mRoutes[i]);
-        result.append(buffer);
-    }
     ::write(fd, result.string(), result.size());
     dump(fd, args);  // Dump the state of the concrete child.
     return NO_ERROR;
diff --git a/libs/audioflinger/AudioHardwareStub.cpp b/libs/audioflinger/AudioHardwareStub.cpp
index 0ab4c60..1a03059 100644
--- a/libs/audioflinger/AudioHardwareStub.cpp
+++ b/libs/audioflinger/AudioHardwareStub.cpp
@@ -43,10 +43,10 @@
 }
 
 AudioStreamOut* AudioHardwareStub::openOutputStream(
-        int format, int channelCount, uint32_t sampleRate, status_t *status)
+        uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status)
 {
     AudioStreamOutStub* out = new AudioStreamOutStub();
-    status_t lStatus = out->set(format, channelCount, sampleRate);
+    status_t lStatus = out->set(format, channels, sampleRate);
     if (status) {
         *status = lStatus;
     }
@@ -56,18 +56,22 @@
     return 0;
 }
 
+void AudioHardwareStub::closeOutputStream(AudioStreamOut* out)
+{
+    delete out;
+}
+
 AudioStreamIn* AudioHardwareStub::openInputStream(
-        int inputSource, int format, int channelCount, uint32_t sampleRate,
+        uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate,
         status_t *status, AudioSystem::audio_in_acoustics acoustics)
 {
     // check for valid input source
-    if ((inputSource < AudioRecord::DEFAULT_INPUT) ||
-        (inputSource >= AudioRecord::NUM_INPUT_SOURCES)) {
+    if (!AudioSystem::isInputDevice((AudioSystem::audio_devices)devices)) {
         return 0;
     }
 
     AudioStreamInStub* in = new AudioStreamInStub();
-    status_t lStatus = in->set(format, channelCount, sampleRate, acoustics);
+    status_t lStatus = in->set(format, channels, sampleRate, acoustics);
     if (status) {
         *status = lStatus;
     }
@@ -77,6 +81,11 @@
     return 0;
 }
 
+void AudioHardwareStub::closeInputStream(AudioStreamIn* in)
+{
+    delete in;
+}
+
 status_t AudioHardwareStub::setVoiceVolume(float volume)
 {
     return NO_ERROR;
@@ -107,24 +116,19 @@
 
 // ----------------------------------------------------------------------------
 
-status_t AudioStreamOutStub::set(int format, int channels, uint32_t rate)
+status_t AudioStreamOutStub::set(int *pFormat, uint32_t *pChannels, uint32_t *pRate)
 {
-    // fix up defaults
-    if (format == 0) format = AudioSystem::PCM_16_BIT;
-    if (channels == 0) channels = channelCount();
-    if (rate == 0) rate = sampleRate();
+    if (pFormat) *pFormat = format();
+    if (pChannels) *pChannels = channels();
+    if (pRate) *pRate = sampleRate();
 
-    if ((format == AudioSystem::PCM_16_BIT) &&
-            (channels == channelCount()) &&
-            (rate == sampleRate()))
-        return NO_ERROR;
-    return BAD_VALUE;
+    return NO_ERROR;
 }
 
 ssize_t AudioStreamOutStub::write(const void* buffer, size_t bytes)
 {
     // fake timing for audio output
-    usleep(bytes * 1000000 / sizeof(int16_t) / channelCount() / sampleRate());
+    usleep(bytes * 1000000 / sizeof(int16_t) / AudioSystem::popCount(channels()) / sampleRate());
     return bytes;
 }
 
@@ -141,7 +145,7 @@
     snprintf(buffer, SIZE, "AudioStreamOutStub::dump\n");
     snprintf(buffer, SIZE, "\tsample rate: %d\n", sampleRate());
     snprintf(buffer, SIZE, "\tbuffer size: %d\n", bufferSize());
-    snprintf(buffer, SIZE, "\tchannel count: %d\n", channelCount());
+    snprintf(buffer, SIZE, "\tchannels: %d\n", channels());
     snprintf(buffer, SIZE, "\tformat: %d\n", format());
     result.append(buffer);
     ::write(fd, result.string(), result.size());
@@ -150,20 +154,16 @@
 
 // ----------------------------------------------------------------------------
 
-status_t AudioStreamInStub::set(int format, int channels, uint32_t rate,
+status_t AudioStreamInStub::set(int *pFormat, uint32_t *pChannels, uint32_t *pRate,
 				AudioSystem::audio_in_acoustics acoustics)
 {
-    if ((format == AudioSystem::PCM_16_BIT) &&
-            (channels == channelCount()) &&
-            (rate == sampleRate()))
-        return NO_ERROR;
-    return BAD_VALUE;
+    return NO_ERROR;
 }
 
 ssize_t AudioStreamInStub::read(void* buffer, ssize_t bytes)
 {
     // fake timing for audio input
-    usleep(bytes * 1000000 / sizeof(int16_t) / channelCount() / sampleRate());
+    usleep(bytes * 1000000 / sizeof(int16_t) / AudioSystem::popCount(channels()) / sampleRate());
     memset(buffer, 0, bytes);
     return bytes;
 }
@@ -179,7 +179,7 @@
     result.append(buffer);
     snprintf(buffer, SIZE, "\tbuffer size: %d\n", bufferSize());
     result.append(buffer);
-    snprintf(buffer, SIZE, "\tchannel count: %d\n", channelCount());
+    snprintf(buffer, SIZE, "\tchannels: %d\n", channels());
     result.append(buffer);
     snprintf(buffer, SIZE, "\tformat: %d\n", format());
     result.append(buffer);
diff --git a/libs/audioflinger/AudioHardwareStub.h b/libs/audioflinger/AudioHardwareStub.h
index bf63cc5..8f43259 100644
--- a/libs/audioflinger/AudioHardwareStub.h
+++ b/libs/audioflinger/AudioHardwareStub.h
@@ -29,29 +29,33 @@
 
 class AudioStreamOutStub : public AudioStreamOut {
 public:
-    virtual status_t    set(int format, int channelCount, uint32_t sampleRate);
+    virtual status_t    set(int *pFormat, uint32_t *pChannels, uint32_t *pRate);
     virtual uint32_t    sampleRate() const { return 44100; }
     virtual size_t      bufferSize() const { return 4096; }
-    virtual int         channelCount() const { return 2; }
+    virtual uint32_t    channels() const { return AudioSystem::CHANNEL_OUT_STEREO; }
     virtual int         format() const { return AudioSystem::PCM_16_BIT; }
     virtual uint32_t    latency() const { return 0; }
-    virtual status_t    setVolume(float volume) { return NO_ERROR; }
+    virtual status_t    setVolume(float left, float right) { return NO_ERROR; }
     virtual ssize_t     write(const void* buffer, size_t bytes);
     virtual status_t    standby();
     virtual status_t    dump(int fd, const Vector<String16>& args);
+    virtual status_t    setParameters(const String8& keyValuePairs) { return NO_ERROR;}
+    virtual String8     getParameters(const String8& keys) {String8 result = String8(""); return result;}
 };
 
 class AudioStreamInStub : public AudioStreamIn {
 public:
-    virtual status_t    set(int format, int channelCount, uint32_t sampleRate, AudioSystem::audio_in_acoustics acoustics);
+    virtual status_t    set(int *pFormat, uint32_t *pChannels, uint32_t *pRate, AudioSystem::audio_in_acoustics acoustics);
     virtual uint32_t    sampleRate() const { return 8000; }
     virtual size_t      bufferSize() const { return 320; }
-    virtual int         channelCount() const { return 1; }
+    virtual uint32_t    channels() const { return AudioSystem::CHANNEL_IN_MONO; }
     virtual int         format() const { return AudioSystem::PCM_16_BIT; }
     virtual status_t    setGain(float gain) { return NO_ERROR; }
     virtual ssize_t     read(void* buffer, ssize_t bytes);
     virtual status_t    dump(int fd, const Vector<String16>& args);
     virtual status_t    standby() { return NO_ERROR; }
+    virtual status_t    setParameters(const String8& keyValuePairs) { return NO_ERROR;}
+    virtual String8     getParameters(const String8& keys) {String8 result = String8(""); return result;}
 };
 
 class AudioHardwareStub : public  AudioHardwareBase
@@ -67,26 +71,25 @@
     virtual status_t    setMicMute(bool state) { mMicMute = state;  return  NO_ERROR; }
     virtual status_t    getMicMute(bool* state) { *state = mMicMute ; return NO_ERROR; }
 
-    virtual status_t    setParameter(const char* key, const char* value)
-            { return NO_ERROR; }
-
     // create I/O streams
     virtual AudioStreamOut* openOutputStream(
-                                int format=0,
-                                int channelCount=0,
-                                uint32_t sampleRate=0,
+                                uint32_t devices,
+                                int *format=0,
+                                uint32_t *channels=0,
+                                uint32_t *sampleRate=0,
                                 status_t *status=0);
+    virtual    void        closeOutputStream(AudioStreamOut* out);
 
     virtual AudioStreamIn* openInputStream(
-                                int inputSource,
-                                int format,
-                                int channelCount,
-                                uint32_t sampleRate,
+                                uint32_t devices,
+                                int *format,
+                                uint32_t *channels,
+                                uint32_t *sampleRate,
                                 status_t *status,
-				AudioSystem::audio_in_acoustics acoustics);
+                                AudioSystem::audio_in_acoustics acoustics);
+    virtual    void        closeInputStream(AudioStreamIn* in);
 
 protected:
-    virtual status_t    doRouting() { return NO_ERROR; }
     virtual status_t    dump(int fd, const Vector<String16>& args);
 
             bool        mMicMute;
diff --git a/libs/audioflinger/AudioMixer.cpp b/libs/audioflinger/AudioMixer.cpp
index b02efcc..19a442a 100644
--- a/libs/audioflinger/AudioMixer.cpp
+++ b/libs/audioflinger/AudioMixer.cpp
@@ -610,7 +610,6 @@
     t->in = in;
 }
 
-inline
 void AudioMixer::ditherAndClamp(int32_t* out, int32_t const *sums, size_t c)
 {
     for (size_t i=0 ; i<c ; i++) {
diff --git a/libs/audioflinger/AudioMixer.h b/libs/audioflinger/AudioMixer.h
index 72ca28a..15766cd 100644
--- a/libs/audioflinger/AudioMixer.h
+++ b/libs/audioflinger/AudioMixer.h
@@ -85,6 +85,8 @@
 
     uint32_t    trackNames() const { return mTrackNames; }
 
+    static void ditherAndClamp(int32_t* out, int32_t const *sums, size_t c);
+
 private:
 
     enum {
@@ -176,7 +178,6 @@
     static void volumeRampStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp);
     static void track__16BitsStereo(track_t* t, int32_t* out, size_t numFrames, int32_t* temp);
     static void track__16BitsMono(track_t* t, int32_t* out, size_t numFrames, int32_t* temp);
-    static void ditherAndClamp(int32_t* out, int32_t const *sums, size_t c);
 
     static void process__validate(state_t* state, void* output);
     static void process__nop(state_t* state, void* output);
diff --git a/libs/audioflinger/AudioPolicyManagerGeneric.cpp b/libs/audioflinger/AudioPolicyManagerGeneric.cpp
new file mode 100644
index 0000000..4b31815
--- /dev/null
+++ b/libs/audioflinger/AudioPolicyManagerGeneric.cpp
@@ -0,0 +1,753 @@
+/*
+ * 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 "AudioPolicyManagerGeneric"
+//#define LOG_NDEBUG 0
+#include <utils/Log.h>
+#include "AudioPolicyManagerGeneric.h"
+#include <media/mediarecorder.h>
+
+namespace android {
+
+
+// ----------------------------------------------------------------------------
+// AudioPolicyInterface implementation
+// ----------------------------------------------------------------------------
+
+
+status_t AudioPolicyManagerGeneric::setDeviceConnectionState(AudioSystem::audio_devices device,
+                                                  AudioSystem::device_connection_state state,
+                                                  const char *device_address)
+{
+
+    LOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
+
+    // connect/disconnect only 1 device at a time
+    if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
+
+    if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
+        LOGE("setDeviceConnectionState() invalid address: %s", device_address);
+        return BAD_VALUE;
+    }
+
+    // handle output devices
+    if (AudioSystem::isOutputDevice(device)) {
+        switch (state)
+        {
+        // handle output device connection
+        case AudioSystem::DEVICE_STATE_AVAILABLE:
+            if (mAvailableOutputDevices & device) {
+                LOGW("setDeviceConnectionState() device already connected: %x", device);
+                return INVALID_OPERATION;
+            }
+            LOGV("setDeviceConnectionState() connecting device %x", device);
+
+            // register new device as available
+            mAvailableOutputDevices |= device;
+            break;
+        // handle output device disconnection
+        case AudioSystem::DEVICE_STATE_UNAVAILABLE:
+            if (!(mAvailableOutputDevices & device)) {
+                LOGW("setDeviceConnectionState() device not connected: %x", device);
+                return INVALID_OPERATION;
+            }
+            LOGV("setDeviceConnectionState() disconnecting device %x", device);
+            // remove device from available output devices
+            mAvailableOutputDevices &= ~device;
+            break;
+
+        default:
+            LOGE("setDeviceConnectionState() invalid state: %x", state);
+            return BAD_VALUE;
+        }
+        return NO_ERROR;
+    }
+    // handle input devices
+    if (AudioSystem::isInputDevice(device)) {
+        switch (state)
+        {
+        // handle input device connection
+        case AudioSystem::DEVICE_STATE_AVAILABLE:
+            if (mAvailableInputDevices & device) {
+                LOGW("setDeviceConnectionState() device already connected: %d", device);
+                return INVALID_OPERATION;
+            }
+            mAvailableInputDevices |= device;
+            break;
+
+        // handle input device disconnection
+        case AudioSystem::DEVICE_STATE_UNAVAILABLE:
+            if (!(mAvailableInputDevices & device)) {
+                LOGW("setDeviceConnectionState() device not connected: %d", device);
+                return INVALID_OPERATION;
+            }
+            mAvailableInputDevices &= ~device;
+            break;
+
+        default:
+            LOGE("setDeviceConnectionState() invalid state: %x", state);
+            return BAD_VALUE;
+        }
+        return NO_ERROR;
+    }
+
+    LOGW("setDeviceConnectionState() invalid device: %x", device);
+    return BAD_VALUE;
+}
+
+AudioSystem::device_connection_state AudioPolicyManagerGeneric::getDeviceConnectionState(AudioSystem::audio_devices device,
+                                                  const char *device_address)
+{
+    AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
+    String8 address = String8(device_address);
+    if (AudioSystem::isOutputDevice(device)) {
+        if (device & mAvailableOutputDevices) {
+            state = AudioSystem::DEVICE_STATE_AVAILABLE;
+        }
+    } else if (AudioSystem::isInputDevice(device)) {
+        if (device & mAvailableInputDevices) {
+            state = AudioSystem::DEVICE_STATE_AVAILABLE;
+        }
+    }
+
+    return state;
+}
+
+void AudioPolicyManagerGeneric::setPhoneState(int state)
+{
+    LOGV("setPhoneState() state %d", state);
+    uint32_t newDevice = 0;
+    if (state < 0 || state >= AudioSystem::NUM_MODES) {
+        LOGW("setPhoneState() invalid state %d", state);
+        return;
+    }
+
+    if (state == mPhoneState ) {
+        LOGW("setPhoneState() setting same state %d", state);
+        return;
+    }
+    // store previous phone state for management of sonification strategy below
+    int oldState = mPhoneState;
+    mPhoneState = state;
+
+    // if leaving or entering in call state, handle special case of active streams
+    // pertaining to sonification strategy see handleIncallSonification()
+    if (state == AudioSystem::MODE_IN_CALL ||
+        oldState == AudioSystem::MODE_IN_CALL) {
+        bool starting = (state == AudioSystem::MODE_IN_CALL) ? true : false;
+        LOGV("setPhoneState() in call state management: new state is %d", state);
+        for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
+            handleIncallSonification(stream, starting);
+        }
+    }
+}
+
+void AudioPolicyManagerGeneric::setRingerMode(uint32_t mode, uint32_t mask)
+{
+    LOGV("setRingerMode() mode %x, mask %x", mode, mask);
+
+    mRingerMode = mode;
+}
+
+void AudioPolicyManagerGeneric::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
+{
+    LOGV("setForceUse) usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
+    mForceUse[usage] = config;
+}
+
+AudioSystem::forced_config AudioPolicyManagerGeneric::getForceUse(AudioSystem::force_use usage)
+{
+    return mForceUse[usage];
+}
+
+void AudioPolicyManagerGeneric::setSystemProperty(const char* property, const char* value)
+{
+    LOGV("setSystemProperty() property %s, value %s", property, value);
+    if (strcmp(property, "ro.camera.sound.forced") == 0) {
+        if (atoi(value)) {
+            LOGV("ENFORCED_AUDIBLE cannot be muted");
+            mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
+        } else {
+            LOGV("ENFORCED_AUDIBLE can be muted");
+            mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
+        }
+    }
+}
+
+audio_io_handle_t AudioPolicyManagerGeneric::getOutput(AudioSystem::stream_type stream,
+                                    uint32_t samplingRate,
+                                    uint32_t format,
+                                    uint32_t channels,
+                                    AudioSystem::output_flags flags)
+{
+    LOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags);
+
+#ifdef AUDIO_POLICY_TEST
+    if (mCurOutput != 0) {
+        LOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelcount %d, mDirectOutput %d",
+                mCurOutput, mTestSamplingRate, mTestFormat, mTestChannelcount, mDirectOutput);
+
+        if (mTestOutputs[mCurOutput] == 0) {
+            LOGV("getOutput() opening test output");
+            AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
+            outputDesc->mDevice = mTestDevice;
+            outputDesc->mSamplingRate = mTestSamplingRate;
+            outputDesc->mFormat = mTestFormat;
+            outputDesc->mChannels = (mTestChannelcount == 1) ? AudioSystem::CHANNEL_OUT_MONO : AudioSystem::CHANNEL_OUT_STEREO;
+            outputDesc->mLatency = mTestLatencyMs;
+            outputDesc->mFlags = (AudioSystem::output_flags)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
+            outputDesc->mRefCount[stream] = 0;
+            mTestOutputs[mCurOutput] = mpClientInterface->openOutput(&outputDesc->mDevice,
+                                            &outputDesc->mSamplingRate,
+                                            &outputDesc->mFormat,
+                                            &outputDesc->mChannels,
+                                            &outputDesc->mLatency,
+                                            outputDesc->mFlags);
+            mOutputs.add(mTestOutputs[mCurOutput], outputDesc);
+        }
+        return mTestOutputs[mCurOutput];
+    }
+#endif //AUDIO_POLICY_TEST
+    if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
+        (format != 0 && !AudioSystem::isLinearPCM(format)) ||
+        (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO && channels != AudioSystem::CHANNEL_OUT_STEREO)) {
+        return NULL;
+    }
+
+    return mHardwareOutput;
+}
+
+status_t AudioPolicyManagerGeneric::startOutput(audio_io_handle_t output, AudioSystem::stream_type stream)
+{
+    LOGV("startOutput() output %p, stream %d", output, stream);
+    ssize_t index = mOutputs.indexOfKey(output);
+    if (index < 0) {
+        LOGW("startOutput() unknow output %p", output);
+        return BAD_VALUE;
+    }
+
+    AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
+
+    // handle special case for sonification while in call
+    if (mPhoneState == AudioSystem::MODE_IN_CALL) {
+        handleIncallSonification(stream, true);
+    }
+
+    // incremenent usage count for this stream on the requested output:
+    outputDesc->changeRefCount(stream, 1);
+    return NO_ERROR;
+}
+
+status_t AudioPolicyManagerGeneric::stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream)
+{
+    LOGV("stopOutput() output %p, stream %d", output, stream);
+    ssize_t index = mOutputs.indexOfKey(output);
+    if (index < 0) {
+        LOGW("stopOutput() unknow output %p", output);
+        return BAD_VALUE;
+    }
+
+    AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
+
+    // handle special case for sonification while in call
+    if (mPhoneState == AudioSystem::MODE_IN_CALL) {
+        handleIncallSonification(stream, false);
+    }
+
+    if (outputDesc->isUsedByStream(stream)) {
+        // decrement usage count of this stream on the output
+        outputDesc->changeRefCount(stream, -1);
+        return NO_ERROR;
+    } else {
+        LOGW("stopOutput() refcount is already 0 for output %p", output);
+        return INVALID_OPERATION;
+    }
+}
+
+void AudioPolicyManagerGeneric::releaseOutput(audio_io_handle_t output)
+{
+    LOGV("releaseOutput() %p", output);
+    ssize_t index = mOutputs.indexOfKey(output);
+    if (index < 0) {
+        LOGW("releaseOutput() releasing unknown output %p", output);
+        return;
+    }
+
+#ifdef AUDIO_POLICY_TEST
+    int testIndex = testOutputIndex(output);
+    if (testIndex != 0) {
+        AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
+        if (outputDesc->refCount() == 0) {
+            mpClientInterface->closeOutput(output);
+            delete mOutputs.valueAt(index);
+            mOutputs.removeItem(output);
+            mTestOutputs[testIndex] = 0;
+        }
+    }
+#endif //AUDIO_POLICY_TEST
+}
+
+audio_io_handle_t AudioPolicyManagerGeneric::getInput(int inputSource,
+                                    uint32_t samplingRate,
+                                    uint32_t format,
+                                    uint32_t channels,
+                                    AudioSystem::audio_in_acoustics acoustics)
+{
+    audio_io_handle_t input = 0;
+    uint32_t device;
+
+    LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
+
+    AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
+    inputDesc->mDevice = AudioSystem::DEVICE_IN_BUILTIN_MIC;
+    inputDesc->mSamplingRate = samplingRate;
+    inputDesc->mFormat = format;
+    inputDesc->mChannels = channels;
+    inputDesc->mAcoustics = acoustics;
+    inputDesc->mRefCount = 0;
+    input = mpClientInterface->openInput(&inputDesc->mDevice,
+                                    &inputDesc->mSamplingRate,
+                                    &inputDesc->mFormat,
+                                    &inputDesc->mChannels,
+                                    inputDesc->mAcoustics);
+
+    // only accept input with the exact requested set of parameters
+    if ((samplingRate != inputDesc->mSamplingRate) ||
+        (format != inputDesc->mFormat) ||
+        (channels != inputDesc->mChannels)) {
+        LOGV("getOutput() failed opening input: samplingRate %d, format %d, channels %d",
+                samplingRate, format, channels);
+        mpClientInterface->closeInput(input);
+        delete inputDesc;
+        return NULL;
+    }
+    mInputs.add(input, inputDesc);
+    return input;
+}
+
+status_t AudioPolicyManagerGeneric::startInput(audio_io_handle_t input)
+{
+    LOGV("startInput() input %p", input);
+    ssize_t index = mInputs.indexOfKey(input);
+    if (index < 0) {
+        LOGW("startInput() unknow input %p", input);
+        return BAD_VALUE;
+    }
+    AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
+
+#ifdef AUDIO_POLICY_TEST
+    if (mTestInput == 0)
+#endif //AUDIO_POLICY_TEST
+    {
+        // refuse 2 active AudioRecord clients at the same time
+        for (size_t i = 0; i < mInputs.size(); i++) {
+            if (mInputs.valueAt(i)->mRefCount > 0) {
+                LOGW("startInput() input %p, other input %p already started", input, mInputs.keyAt(i));
+                return INVALID_OPERATION;
+            }
+        }
+    }
+
+    inputDesc->mRefCount = 1;
+    return NO_ERROR;
+}
+
+status_t AudioPolicyManagerGeneric::stopInput(audio_io_handle_t input)
+{
+    LOGV("stopInput() input %p", input);
+    ssize_t index = mInputs.indexOfKey(input);
+    if (index < 0) {
+        LOGW("stopInput() unknow input %p", input);
+        return BAD_VALUE;
+    }
+    AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
+
+    if (inputDesc->mRefCount == 0) {
+        LOGW("stopInput() input %p already stopped", input);
+        return INVALID_OPERATION;
+    } else {
+        inputDesc->mRefCount = 0;
+        return NO_ERROR;
+    }
+}
+
+void AudioPolicyManagerGeneric::releaseInput(audio_io_handle_t input)
+{
+    LOGV("releaseInput() %p", input);
+    ssize_t index = mInputs.indexOfKey(input);
+    if (index < 0) {
+        LOGW("releaseInput() releasing unknown input %p", input);
+        return;
+    }
+    mpClientInterface->closeInput(input);
+    delete mInputs.valueAt(index);
+    mInputs.removeItem(input);
+}
+
+
+
+void AudioPolicyManagerGeneric::initStreamVolume(AudioSystem::stream_type stream,
+                                            int indexMin,
+                                            int indexMax)
+{
+    LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
+    mStreams[stream].mIndexMin = indexMin;
+    mStreams[stream].mIndexMax = indexMax;
+}
+
+status_t AudioPolicyManagerGeneric::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
+{
+
+    if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
+        return BAD_VALUE;
+    }
+
+    LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
+    mStreams[stream].mIndexCur = index;
+
+    // do not change actual stream volume if the stream is muted
+    if (mStreams[stream].mMuteCount != 0) {
+        return NO_ERROR;
+    }
+
+    // Do not changed in call volume if bluetooth is connected and vice versa
+    if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
+        (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
+        LOGV("setStreamVolumeIndex() cannot set stream %d volume with force use = %d for comm",
+             stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
+        return INVALID_OPERATION;
+    }
+
+    // compute and apply stream volume on all outputs according to connected device
+    for (size_t i = 0; i < mOutputs.size(); i++) {
+        AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
+        uint32_t device = outputDesc->device();
+
+        float volume = computeVolume((int)stream, index, device);
+
+        LOGV("setStreamVolume() for output %p stream %d, volume %f", mOutputs.keyAt(i), stream, volume);
+        mpClientInterface->setStreamVolume(stream, volume, mOutputs.keyAt(i));
+    }
+    return NO_ERROR;
+}
+
+status_t AudioPolicyManagerGeneric::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
+{
+    if (index == 0) {
+        return BAD_VALUE;
+    }
+    LOGV("getStreamVolumeIndex() stream %d", stream);
+    *index =  mStreams[stream].mIndexCur;
+    return NO_ERROR;
+}
+
+// ----------------------------------------------------------------------------
+// AudioPolicyManagerGeneric
+// ----------------------------------------------------------------------------
+
+// ---  class factory
+
+AudioPolicyManagerGeneric::AudioPolicyManagerGeneric(AudioPolicyClientInterface *clientInterface)
+    :
+#ifdef AUDIO_POLICY_TEST
+    Thread(false),
+#endif //AUDIO_POLICY_TEST
+    mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0)
+{
+    mpClientInterface = clientInterface;
+
+    for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
+        mForceUse[i] = AudioSystem::FORCE_NONE;
+    }
+
+    // devices available by default are speaker, ear piece and microphone
+    mAvailableOutputDevices = AudioSystem::DEVICE_OUT_SPEAKER;
+    mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
+
+    // open hardware output
+    AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
+    outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
+    mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
+                                    &outputDesc->mSamplingRate,
+                                    &outputDesc->mFormat,
+                                    &outputDesc->mChannels,
+                                    &outputDesc->mLatency,
+                                    outputDesc->mFlags);
+
+    if (mHardwareOutput == 0) {
+        LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
+                outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
+    } else {
+        mOutputs.add(mHardwareOutput, outputDesc);
+    }
+
+#ifdef AUDIO_POLICY_TEST
+    mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
+    mTestSamplingRate = 44100;
+    mTestFormat = AudioSystem::PCM_16_BIT;
+    mTestChannelcount = 2;
+    mTestLatencyMs = 0;
+    mCurOutput = 0;
+    mDirectOutput = false;
+    for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
+        mTestOutputs[i] = 0;
+    }
+
+    const size_t SIZE = 256;
+    char buffer[SIZE];
+    snprintf(buffer, SIZE, "AudioPolicyManagerTest");
+    run(buffer, ANDROID_PRIORITY_AUDIO);
+#endif //AUDIO_POLICY_TEST
+}
+
+AudioPolicyManagerGeneric::~AudioPolicyManagerGeneric()
+{
+#ifdef AUDIO_POLICY_TEST
+    exit();
+#endif //AUDIO_POLICY_TEST
+
+   for (size_t i = 0; i < mOutputs.size(); i++) {
+        mpClientInterface->closeOutput(mOutputs.keyAt(i));
+        delete mOutputs.valueAt(i);
+   }
+   mOutputs.clear();
+   for (size_t i = 0; i < mInputs.size(); i++) {
+        mpClientInterface->closeInput(mInputs.keyAt(i));
+        delete mInputs.valueAt(i);
+   }
+   mInputs.clear();
+}
+
+#ifdef AUDIO_POLICY_TEST
+bool AudioPolicyManagerGeneric::threadLoop()
+{
+    LOGV("entering threadLoop()");
+    while (!exitPending())
+    {
+        Mutex::Autolock _l(mLock);
+        mWaitWorkCV.waitRelative(mLock, milliseconds(50));
+        String8 command;
+        command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
+        if (command != "") {
+            LOGV("Test command %s received", command.string());
+            AudioParameter param = AudioParameter(command);
+            int valueInt;
+            String8 value;
+            if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
+                param.remove(String8("test_cmd_policy_output"));
+                mCurOutput = valueInt;
+            }
+            if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
+                param.remove(String8("test_cmd_policy_direct"));
+                if (value == "false") {
+                    mDirectOutput = false;
+                } else if (value == "true") {
+                    mDirectOutput = true;
+                }
+            }
+            if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
+                param.remove(String8("test_cmd_policy_input"));
+                mTestInput = valueInt;
+            }
+
+            if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
+                param.remove(String8("test_cmd_policy_format"));
+                if (value == "PCM 16 bits") {
+                    mTestFormat = AudioSystem::PCM_16_BIT;
+                } else if (value == "PCM 8 bits") {
+                    mTestFormat = AudioSystem::PCM_8_BIT;
+                } else if (value == "Compressed MP3") {
+                    mTestFormat = AudioSystem::MP3;
+                }
+            }
+            if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
+                param.remove(String8("test_cmd_policy_channels"));
+                if (value == "Channels Stereo") {
+                    mTestChannelcount = 2;
+                } else if (value == "Channels Mono") {
+                    mTestChannelcount = 1;
+                }
+            }
+            if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
+                param.remove(String8("test_cmd_policy_sampleRate"));
+                if (valueInt >= 0 && valueInt <= 96000) {
+                    mTestSamplingRate = valueInt;
+                }
+            }
+            mpClientInterface->setParameters(0, String8("test_cmd_policy="));
+        }
+    }
+    return false;
+}
+
+void AudioPolicyManagerGeneric::exit()
+{
+    {
+        AutoMutex _l(mLock);
+        requestExit();
+        mWaitWorkCV.signal();
+    }
+    requestExitAndWait();
+}
+
+int AudioPolicyManagerGeneric::testOutputIndex(audio_io_handle_t output)
+{
+    for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
+        if (output == mTestOutputs[i]) return i;
+    }
+    return 0;
+}
+#endif //AUDIO_POLICY_TEST
+
+// ---
+
+AudioPolicyManagerGeneric::routing_strategy AudioPolicyManagerGeneric::getStrategy(AudioSystem::stream_type stream)
+{
+    // stream to strategy mapping
+    switch (stream) {
+    case AudioSystem::VOICE_CALL:
+    case AudioSystem::BLUETOOTH_SCO:
+        return STRATEGY_PHONE;
+    case AudioSystem::RING:
+    case AudioSystem::NOTIFICATION:
+    case AudioSystem::ALARM:
+    case AudioSystem::ENFORCED_AUDIBLE:
+        return STRATEGY_SONIFICATION;
+    case AudioSystem::DTMF:
+        return STRATEGY_DTMF;
+    default:
+        LOGE("unknown stream type");
+    case AudioSystem::SYSTEM:
+        // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
+        // while key clicks are played produces a poor result
+    case AudioSystem::TTS:
+    case AudioSystem::MUSIC:
+        return STRATEGY_MEDIA;
+    }
+}
+
+
+float AudioPolicyManagerGeneric::computeVolume(int stream, int index, uint32_t device)
+{
+    float volume = 1.0;
+
+    StreamDescriptor &streamDesc = mStreams[stream];
+
+    // Force max volume if stream cannot be muted
+    if (!streamDesc.mCanBeMuted) index = streamDesc.mIndexMax;
+
+    int volInt = (100 * (index - streamDesc.mIndexMin)) / (streamDesc.mIndexMax - streamDesc.mIndexMin);
+    volume = AudioSystem::linearToLog(volInt);
+
+    return volume;
+}
+
+void AudioPolicyManagerGeneric::setStreamMute(int stream, bool on, audio_io_handle_t output)
+{
+    LOGV("setStreamMute() stream %d, mute %d, output %p", stream, on, output);
+
+    StreamDescriptor &streamDesc = mStreams[stream];
+
+    if (on) {
+        if (streamDesc.mMuteCount++ == 0) {
+            if (streamDesc.mCanBeMuted) {
+                mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, 0, output);
+            }
+        }
+    } else {
+        if (streamDesc.mMuteCount == 0) {
+            LOGW("setStreamMute() unmuting non muted stream!");
+            return;
+        }
+        if (--streamDesc.mMuteCount == 0) {
+            uint32_t device = mOutputs.valueFor(output)->mDevice;
+            float volume = computeVolume(stream, streamDesc.mIndexCur, device);
+            mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output);
+        }
+    }
+}
+
+void AudioPolicyManagerGeneric::handleIncallSonification(int stream, bool starting)
+{
+    // if the stream pertains to sonification strategy and we are in call we must
+    // mute the stream if it is low visibility. If it is high visibility, we must play a tone
+    // in the device used for phone strategy and play the tone if the selected device does not
+    // interfere with the device used for phone strategy
+    if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
+        AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
+        LOGV("handleIncallSonification() stream %d starting %d device %x", stream, starting, outputDesc->mDevice);
+        if (outputDesc->isUsedByStream((AudioSystem::stream_type)stream)) {
+            if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
+                LOGV("handleIncallSonification() low visibility");
+                setStreamMute(stream, starting, mHardwareOutput);
+            } else {
+                if (starting) {
+                    mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
+                } else {
+                    mpClientInterface->stopTone();
+                }
+            }
+        }
+    }
+}
+
+
+// --- AudioOutputDescriptor class implementation
+
+AudioPolicyManagerGeneric::AudioOutputDescriptor::AudioOutputDescriptor()
+    : mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
+    mFlags((AudioSystem::output_flags)0), mDevice(0)
+{
+    // clear usage count for all stream types
+    for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
+        mRefCount[i] = 0;
+    }
+}
+
+uint32_t AudioPolicyManagerGeneric::AudioOutputDescriptor::device()
+{
+    return mDevice;
+}
+
+void AudioPolicyManagerGeneric::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
+{
+    if ((delta + (int)mRefCount[stream]) < 0) {
+        LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
+        mRefCount[stream] = 0;
+        return;
+    }
+    mRefCount[stream] += delta;
+    LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
+}
+
+uint32_t AudioPolicyManagerGeneric::AudioOutputDescriptor::refCount()
+{
+    uint32_t refcount = 0;
+    for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
+        refcount += mRefCount[i];
+    }
+    return refcount;
+}
+
+// --- AudioInputDescriptor class implementation
+
+AudioPolicyManagerGeneric::AudioInputDescriptor::AudioInputDescriptor()
+    : mSamplingRate(0), mFormat(0), mChannels(0),
+     mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0)
+{
+}
+
+}; // namespace android
diff --git a/libs/audioflinger/AudioPolicyManagerGeneric.h b/libs/audioflinger/AudioPolicyManagerGeneric.h
new file mode 100644
index 0000000..ddcb306
--- /dev/null
+++ b/libs/audioflinger/AudioPolicyManagerGeneric.h
@@ -0,0 +1,189 @@
+/*
+ * 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.
+ */
+
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/KeyedVector.h>
+#include <hardware_legacy/AudioPolicyInterface.h>
+#include <utils/threads.h>
+
+
+namespace android {
+
+// ----------------------------------------------------------------------------
+
+#define MAX_DEVICE_ADDRESS_LEN 20
+#define NUM_TEST_OUTPUTS 5
+
+class AudioPolicyManagerGeneric: public AudioPolicyInterface
+#ifdef AUDIO_POLICY_TEST
+    , public Thread
+#endif //AUDIO_POLICY_TEST
+{
+
+public:
+                AudioPolicyManagerGeneric(AudioPolicyClientInterface *clientInterface);
+        virtual ~AudioPolicyManagerGeneric();
+
+        // AudioPolicyInterface
+        virtual status_t setDeviceConnectionState(AudioSystem::audio_devices device,
+                                                          AudioSystem::device_connection_state state,
+                                                          const char *device_address);
+        virtual AudioSystem::device_connection_state getDeviceConnectionState(AudioSystem::audio_devices device,
+                                                                              const char *device_address);
+        virtual void setPhoneState(int state);
+        virtual void setRingerMode(uint32_t mode, uint32_t mask);
+        virtual void setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config);
+        virtual AudioSystem::forced_config getForceUse(AudioSystem::force_use usage);
+        virtual void setSystemProperty(const char* property, const char* value);
+        virtual audio_io_handle_t getOutput(AudioSystem::stream_type stream,
+                                            uint32_t samplingRate,
+                                            uint32_t format,
+                                            uint32_t channels,
+                                            AudioSystem::output_flags flags);
+        virtual status_t startOutput(audio_io_handle_t output, AudioSystem::stream_type stream);
+        virtual status_t stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream);
+        virtual void releaseOutput(audio_io_handle_t output);
+        virtual audio_io_handle_t getInput(int inputSource,
+                                            uint32_t samplingRate,
+                                            uint32_t format,
+                                            uint32_t channels,
+                                            AudioSystem::audio_in_acoustics acoustics);
+        // indicates to the audio policy manager that the input starts being used.
+        virtual status_t startInput(audio_io_handle_t input);
+        // indicates to the audio policy manager that the input stops being used.
+        virtual status_t stopInput(audio_io_handle_t input);
+        virtual void releaseInput(audio_io_handle_t input);
+        virtual void initStreamVolume(AudioSystem::stream_type stream,
+                                                    int indexMin,
+                                                    int indexMax);
+        virtual status_t setStreamVolumeIndex(AudioSystem::stream_type stream, int index);
+        virtual status_t getStreamVolumeIndex(AudioSystem::stream_type stream, int *index);
+
+private:
+
+        enum routing_strategy {
+            STRATEGY_MEDIA,
+            STRATEGY_PHONE,
+            STRATEGY_SONIFICATION,
+            STRATEGY_DTMF,
+            NUM_STRATEGIES
+        };
+
+        // descriptor for audio outputs. Used to maintain current configuration of each opened audio output
+        // and keep track of the usage of this output by each audio stream type.
+        class AudioOutputDescriptor
+        {
+        public:
+            AudioOutputDescriptor();
+
+
+            uint32_t device();
+            void changeRefCount(AudioSystem::stream_type, int delta);
+            bool isUsedByStream(AudioSystem::stream_type stream) { return mRefCount[stream] > 0 ? true : false; }
+            uint32_t refCount();
+
+            uint32_t mSamplingRate;             //
+            uint32_t mFormat;                   //
+            uint32_t mChannels;                 // output configuration
+            uint32_t mLatency;                  //
+            AudioSystem::output_flags mFlags;   //
+            uint32_t mDevice;                   // current device this output is routed to
+            uint32_t mRefCount[AudioSystem::NUM_STREAM_TYPES]; // number of streams of each type using this output
+        };
+
+        // descriptor for audio inputs. Used to maintain current configuration of each opened audio input
+        // and keep track of the usage of this input.
+        class AudioInputDescriptor
+        {
+        public:
+            AudioInputDescriptor();
+
+            uint32_t mSamplingRate;                     //
+            uint32_t mFormat;                           // input configuration
+            uint32_t mChannels;                         //
+            AudioSystem::audio_in_acoustics mAcoustics; //
+            uint32_t mDevice;                           // current device this input is routed to
+            uint32_t mRefCount;                         // number of AudioRecord clients using this output
+        };
+
+        // stream descriptor used for volume control
+        class StreamDescriptor
+        {
+        public:
+            StreamDescriptor()
+            :   mIndexMin(0), mIndexMax(1), mIndexCur(1), mMuteCount(0), mCanBeMuted(true) {}
+
+            int mIndexMin;      // min volume index
+            int mIndexMax;      // max volume index
+            int mIndexCur;      // current volume index
+            int mMuteCount;     // mute request counter
+            bool mCanBeMuted;   // true is the stream can be muted
+        };
+
+        // return the strategy corresponding to a given stream type
+        static routing_strategy getStrategy(AudioSystem::stream_type stream);
+        // return the output handle of an output routed to the specified device, 0 if no output
+        // is routed to the device
+        float computeVolume(int stream, int index, uint32_t device);
+        // Mute or unmute the stream on the specified output
+        void setStreamMute(int stream, bool on, audio_io_handle_t output);
+        // handle special cases for sonification strategy while in call: mute streams or replace by
+        // a special tone in the device used for communication
+        void handleIncallSonification(int stream, bool starting);
+
+
+#ifdef AUDIO_POLICY_TEST
+        virtual     bool        threadLoop();
+                    void        exit();
+        int testOutputIndex(audio_io_handle_t output);
+#endif //AUDIO_POLICY_TEST
+
+
+        AudioPolicyClientInterface *mpClientInterface;  // audio policy client interface
+        audio_io_handle_t mHardwareOutput;              // hardware output handler
+
+        KeyedVector<audio_io_handle_t, AudioOutputDescriptor *> mOutputs;   // list ot output descritors
+        KeyedVector<audio_io_handle_t, AudioInputDescriptor *> mInputs;     // list of input descriptors
+        uint32_t mAvailableOutputDevices;                                   // bit field of all available output devices
+        uint32_t mAvailableInputDevices;                                    // bit field of all available input devices
+        int mPhoneState;                                                    // current phone state
+        uint32_t                 mRingerMode;                               // current ringer mode
+        AudioSystem::forced_config mForceUse[AudioSystem::NUM_FORCE_USE];   // current forced use configuration
+
+        StreamDescriptor mStreams[AudioSystem::NUM_STREAM_TYPES];           // stream descriptors for volume control
+
+#ifdef AUDIO_POLICY_TEST
+        Mutex   mLock;
+        Condition mWaitWorkCV;
+
+        int             mCurOutput;
+        bool            mDirectOutput;
+        audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS];
+        int             mTestInput;
+        uint32_t        mTestDevice;
+        uint32_t        mTestSamplingRate;
+        uint32_t        mTestFormat;
+        uint32_t        mTestChannelcount;
+        uint32_t        mTestLatencyMs;
+#endif //AUDIO_POLICY_TEST
+
+};
+
+};
diff --git a/libs/audioflinger/AudioPolicyService.cpp b/libs/audioflinger/AudioPolicyService.cpp
new file mode 100644
index 0000000..7f6c4ed
--- /dev/null
+++ b/libs/audioflinger/AudioPolicyService.cpp
@@ -0,0 +1,650 @@
+/*
+ * 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 "AudioPolicyService"
+//#define LOG_NDEBUG 0
+#include <binder/IServiceManager.h>
+#include <utils/Log.h>
+#include <cutils/properties.h>
+#include <binder/IPCThreadState.h>
+#include <utils/String16.h>
+#include <utils/threads.h>
+#include "AudioPolicyService.h"
+#include "AudioPolicyManagerGeneric.h"
+#include <cutils/properties.h>
+#include <dlfcn.h>
+
+// ----------------------------------------------------------------------------
+// the sim build doesn't have gettid
+
+#ifndef HAVE_GETTID
+# define gettid getpid
+#endif
+
+namespace android {
+
+static bool checkPermission() {
+#ifndef HAVE_ANDROID_OS
+    return true;
+#endif
+    if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
+    bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
+    if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
+    return ok;
+}
+
+// ----------------------------------------------------------------------------
+
+AudioPolicyService::AudioPolicyService()
+    : BnAudioPolicyService() , mpPolicyManager(NULL)
+{
+    char value[PROPERTY_VALUE_MAX];
+
+    // start tone playback thread
+    mTonePlaybacThread = new AudioCommandThread();
+    // start audio commands thread
+    mAudioCommandThread = new AudioCommandThread();
+
+#if (defined GENERIC_AUDIO) || (defined AUDIO_POLICY_TEST)
+    mpPolicyManager = new AudioPolicyManagerGeneric(this);
+    LOGV("build for GENERIC_AUDIO - using generic audio policy");
+#else
+    // if running in emulation - use the emulator driver
+    if (property_get("ro.kernel.qemu", value, 0)) {
+        LOGV("Running in emulation - using generic audio policy");
+        mpPolicyManager = new AudioPolicyManagerGeneric(this);
+    }
+    else {
+        LOGV("Using hardware specific audio policy");
+        mpPolicyManager = createAudioPolicyManager(this);
+    }
+#endif
+
+    // load properties
+    property_get("ro.camera.sound.forced", value, "0");
+    mpPolicyManager->setSystemProperty("ro.camera.sound.forced", value);
+}
+
+AudioPolicyService::~AudioPolicyService()
+{
+    mTonePlaybacThread->exit();
+    mTonePlaybacThread.clear();
+    mAudioCommandThread->exit();
+    mAudioCommandThread.clear();
+
+    if (mpPolicyManager) {
+        delete mpPolicyManager;
+    }
+}
+
+
+status_t AudioPolicyService::setDeviceConnectionState(AudioSystem::audio_devices device,
+                                                  AudioSystem::device_connection_state state,
+                                                  const char *device_address)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    if (!checkPermission()) {
+        return PERMISSION_DENIED;
+    }
+    if (!AudioSystem::isOutputDevice(device) && !AudioSystem::isInputDevice(device)) {
+        return BAD_VALUE;
+    }
+    if (state != AudioSystem::DEVICE_STATE_AVAILABLE && state != AudioSystem::DEVICE_STATE_UNAVAILABLE) {
+        return BAD_VALUE;
+    }
+
+    LOGV("setDeviceConnectionState() tid %d", gettid());
+    Mutex::Autolock _l(mLock);
+    return mpPolicyManager->setDeviceConnectionState(device, state, device_address);
+}
+
+AudioSystem::device_connection_state AudioPolicyService::getDeviceConnectionState(AudioSystem::audio_devices device,
+                                                  const char *device_address)
+{
+    if (mpPolicyManager == NULL) {
+        return AudioSystem::DEVICE_STATE_UNAVAILABLE;
+    }
+    if (!checkPermission()) {
+        return AudioSystem::DEVICE_STATE_UNAVAILABLE;
+    }
+    return mpPolicyManager->getDeviceConnectionState(device, device_address);
+}
+
+status_t AudioPolicyService::setPhoneState(int state)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    if (!checkPermission()) {
+        return PERMISSION_DENIED;
+    }
+    if (state < 0 || state >= AudioSystem::NUM_MODES) {
+        return BAD_VALUE;
+    }
+
+    LOGV("setPhoneState() tid %d", gettid());
+
+    // TODO: check if it is more appropriate to do it in platform specific policy manager
+    AudioSystem::setMode(state);
+
+    Mutex::Autolock _l(mLock);
+    mpPolicyManager->setPhoneState(state);
+    return NO_ERROR;
+}
+
+status_t AudioPolicyService::setRingerMode(uint32_t mode, uint32_t mask)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    if (!checkPermission()) {
+        return PERMISSION_DENIED;
+    }
+
+    mpPolicyManager->setRingerMode(mode, mask);
+    return NO_ERROR;
+}
+
+status_t AudioPolicyService::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    if (!checkPermission()) {
+        return PERMISSION_DENIED;
+    }
+    if (usage < 0 || usage >= AudioSystem::NUM_FORCE_USE) {
+        return BAD_VALUE;
+    }
+    if (config < 0 || config >= AudioSystem::NUM_FORCE_CONFIG) {
+        return BAD_VALUE;
+    }
+    LOGV("setForceUse() tid %d", gettid());
+    Mutex::Autolock _l(mLock);
+    mpPolicyManager->setForceUse(usage, config);
+    return NO_ERROR;
+}
+
+AudioSystem::forced_config AudioPolicyService::getForceUse(AudioSystem::force_use usage)
+{
+    if (mpPolicyManager == NULL) {
+        return AudioSystem::FORCE_NONE;
+    }
+    if (!checkPermission()) {
+        return AudioSystem::FORCE_NONE;
+    }
+    if (usage < 0 || usage >= AudioSystem::NUM_FORCE_USE) {
+        return AudioSystem::FORCE_NONE;
+    }
+    return mpPolicyManager->getForceUse(usage);
+}
+
+audio_io_handle_t AudioPolicyService::getOutput(AudioSystem::stream_type stream,
+                                    uint32_t samplingRate,
+                                    uint32_t format,
+                                    uint32_t channels,
+                                    AudioSystem::output_flags flags)
+{
+    if (mpPolicyManager == NULL) {
+        return NULL;
+    }
+    LOGV("getOutput() tid %d", gettid());
+    Mutex::Autolock _l(mLock);
+    return mpPolicyManager->getOutput(stream, samplingRate, format, channels, flags);
+}
+
+status_t AudioPolicyService::startOutput(audio_io_handle_t output, AudioSystem::stream_type stream)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    LOGV("startOutput() tid %d", gettid());
+    Mutex::Autolock _l(mLock);
+    return mpPolicyManager->startOutput(output, stream);
+}
+
+status_t AudioPolicyService::stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    LOGV("stopOutput() tid %d", gettid());
+    Mutex::Autolock _l(mLock);
+    return mpPolicyManager->stopOutput(output, stream);
+}
+
+void AudioPolicyService::releaseOutput(audio_io_handle_t output)
+{
+    if (mpPolicyManager == NULL) {
+        return;
+    }
+    LOGV("releaseOutput() tid %d", gettid());
+    Mutex::Autolock _l(mLock);
+    mpPolicyManager->releaseOutput(output);
+}
+
+audio_io_handle_t AudioPolicyService::getInput(int inputSource,
+                                    uint32_t samplingRate,
+                                    uint32_t format,
+                                    uint32_t channels,
+                                    AudioSystem::audio_in_acoustics acoustics)
+{
+    if (mpPolicyManager == NULL) {
+        return NULL;
+    }
+    Mutex::Autolock _l(mLock);
+    return mpPolicyManager->getInput(inputSource, samplingRate, format, channels, acoustics);
+}
+
+status_t AudioPolicyService::startInput(audio_io_handle_t input)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    Mutex::Autolock _l(mLock);
+    return mpPolicyManager->startInput(input);
+}
+
+status_t AudioPolicyService::stopInput(audio_io_handle_t input)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    Mutex::Autolock _l(mLock);
+    return mpPolicyManager->stopInput(input);
+}
+
+void AudioPolicyService::releaseInput(audio_io_handle_t input)
+{
+    if (mpPolicyManager == NULL) {
+        return;
+    }
+    Mutex::Autolock _l(mLock);
+    mpPolicyManager->releaseInput(input);
+}
+
+status_t AudioPolicyService::initStreamVolume(AudioSystem::stream_type stream,
+                                            int indexMin,
+                                            int indexMax)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    if (!checkPermission()) {
+        return PERMISSION_DENIED;
+    }
+    if (stream < 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
+        return BAD_VALUE;
+    }
+    mpPolicyManager->initStreamVolume(stream, indexMin, indexMax);
+    return NO_ERROR;
+}
+
+status_t AudioPolicyService::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    if (!checkPermission()) {
+        return PERMISSION_DENIED;
+    }
+    if (stream < 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
+        return BAD_VALUE;
+    }
+
+    return mpPolicyManager->setStreamVolumeIndex(stream, index);
+}
+
+status_t AudioPolicyService::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
+{
+    if (mpPolicyManager == NULL) {
+        return NO_INIT;
+    }
+    if (!checkPermission()) {
+        return PERMISSION_DENIED;
+    }
+    if (stream < 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
+        return BAD_VALUE;
+    }
+    return mpPolicyManager->getStreamVolumeIndex(stream, index);
+}
+
+void AudioPolicyService::binderDied(const wp<IBinder>& who) {
+    LOGW("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
+}
+
+status_t AudioPolicyService::dump(int fd, const Vector<String16>& args)
+{
+    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
+        dumpPermissionDenial(fd, args);
+    } else {
+
+    }
+    return NO_ERROR;
+}
+
+status_t AudioPolicyService::dumpPermissionDenial(int fd, const Vector<String16>& args)
+{
+    const size_t SIZE = 256;
+    char buffer[SIZE];
+    String8 result;
+    snprintf(buffer, SIZE, "Permission Denial: "
+            "can't dump AudioPolicyService from pid=%d, uid=%d\n",
+            IPCThreadState::self()->getCallingPid(),
+            IPCThreadState::self()->getCallingUid());
+    result.append(buffer);
+    write(fd, result.string(), result.size());
+    return NO_ERROR;
+}
+
+status_t AudioPolicyService::onTransact(
+        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
+{
+    return BnAudioPolicyService::onTransact(code, data, reply, flags);
+}
+
+
+// ----------------------------------------------------------------------------
+void AudioPolicyService::instantiate() {
+    defaultServiceManager()->addService(
+            String16("media.audio_policy"), new AudioPolicyService());
+}
+
+
+// ----------------------------------------------------------------------------
+// AudioPolicyClientInterface implementation
+// ----------------------------------------------------------------------------
+
+
+audio_io_handle_t AudioPolicyService::openOutput(uint32_t *pDevices,
+                                uint32_t *pSamplingRate,
+                                uint32_t *pFormat,
+                                uint32_t *pChannels,
+                                uint32_t *pLatencyMs,
+                                AudioSystem::output_flags flags)
+{
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (af == 0) {
+        LOGW("openOutput() could not get AudioFlinger");
+        return NULL;
+    }
+
+    return af->openOutput(pDevices, pSamplingRate, (uint32_t *)pFormat, pChannels, pLatencyMs, flags);
+}
+
+audio_io_handle_t AudioPolicyService::openDuplicateOutput(audio_io_handle_t output1, audio_io_handle_t output2)
+{
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (af == 0) {
+        LOGW("openDuplicateOutput() could not get AudioFlinger");
+        return NULL;
+    }
+    return af->openDuplicateOutput(output1, output2);
+}
+
+status_t AudioPolicyService::closeOutput(audio_io_handle_t output)
+{
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (af == 0) return PERMISSION_DENIED;
+
+    return af->closeOutput(output);
+}
+
+
+status_t AudioPolicyService::suspendOutput(audio_io_handle_t output)
+{
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (af == 0) {
+        LOGW("suspendOutput() could not get AudioFlinger");
+        return PERMISSION_DENIED;
+    }
+
+    return af->suspendOutput(output);
+}
+
+status_t AudioPolicyService::restoreOutput(audio_io_handle_t output)
+{
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (af == 0) {
+        LOGW("restoreOutput() could not get AudioFlinger");
+        return PERMISSION_DENIED;
+    }
+
+    return af->restoreOutput(output);
+}
+
+audio_io_handle_t AudioPolicyService::openInput(uint32_t *pDevices,
+                                uint32_t *pSamplingRate,
+                                uint32_t *pFormat,
+                                uint32_t *pChannels,
+                                uint32_t acoustics)
+{
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (af == 0) {
+        LOGW("openInput() could not get AudioFlinger");
+        return NULL;
+    }
+
+    return af->openInput(pDevices, pSamplingRate, (uint32_t *)pFormat, pChannels, acoustics);
+}
+
+status_t AudioPolicyService::closeInput(audio_io_handle_t input)
+{
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (af == 0) return PERMISSION_DENIED;
+
+    return af->closeInput(input);
+}
+
+status_t AudioPolicyService::setStreamVolume(AudioSystem::stream_type stream, float volume, audio_io_handle_t output)
+{
+    return mAudioCommandThread->volumeCommand((int)stream, volume, (void *)output);
+}
+
+status_t AudioPolicyService::setStreamOutput(AudioSystem::stream_type stream, audio_io_handle_t output)
+{
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (af == 0) return PERMISSION_DENIED;
+
+    return af->setStreamOutput(stream, output);
+}
+
+
+void AudioPolicyService::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
+{
+    mAudioCommandThread->parametersCommand((void *)ioHandle, keyValuePairs);
+}
+
+String8 AudioPolicyService::getParameters(audio_io_handle_t ioHandle, const String8& keys)
+{
+    String8 result = AudioSystem::getParameters(ioHandle, keys);
+    return result;
+}
+
+status_t AudioPolicyService::startTone(ToneGenerator::tone_type tone, AudioSystem::stream_type stream)
+{
+    mTonePlaybacThread->startToneCommand(tone, stream);
+    return NO_ERROR;
+}
+
+status_t AudioPolicyService::stopTone()
+{
+    mTonePlaybacThread->stopToneCommand();
+    return NO_ERROR;
+}
+
+
+// -----------  AudioPolicyService::AudioCommandThread implementation ----------
+
+AudioPolicyService::AudioCommandThread::AudioCommandThread()
+    :   Thread(false)
+{
+    mpToneGenerator = NULL;
+}
+
+
+AudioPolicyService::AudioCommandThread::~AudioCommandThread()
+{
+    mAudioCommands.clear();
+    if (mpToneGenerator != NULL) delete mpToneGenerator;
+}
+
+void AudioPolicyService::AudioCommandThread::onFirstRef()
+{
+    const size_t SIZE = 256;
+    char buffer[SIZE];
+
+    snprintf(buffer, SIZE, "AudioCommandThread");
+
+    run(buffer, ANDROID_PRIORITY_AUDIO);
+}
+
+bool AudioPolicyService::AudioCommandThread::threadLoop()
+{
+    mLock.lock();
+    while (!exitPending())
+    {
+        while(!mAudioCommands.isEmpty()) {
+            AudioCommand *command = mAudioCommands[0];
+            mAudioCommands.removeAt(0);
+            switch (command->mCommand) {
+            case START_TONE: {
+                mLock.unlock();
+                ToneData *data = (ToneData *)command->mParam;
+                LOGV("AudioCommandThread() processing start tone %d on stream %d",
+                        data->mType, data->mStream);
+                if (mpToneGenerator != NULL)
+                    delete mpToneGenerator;
+                mpToneGenerator = new ToneGenerator(data->mStream, 1.0);
+                mpToneGenerator->startTone(data->mType);
+                delete data;
+                mLock.lock();
+                }break;
+            case STOP_TONE: {
+                mLock.unlock();
+                LOGV("AudioCommandThread() processing stop tone");
+                if (mpToneGenerator != NULL) {
+                    mpToneGenerator->stopTone();
+                    delete mpToneGenerator;
+                    mpToneGenerator = NULL;
+                }
+                mLock.lock();
+                }break;
+            case SET_VOLUME: {
+                VolumeData *data = (VolumeData *)command->mParam;
+                LOGV("AudioCommandThread() processing set volume stream %d, volume %f, output %p", data->mStream, data->mVolume, data->mIO);
+                mCommandStatus = AudioSystem::setStreamVolume(data->mStream, data->mVolume, data->mIO);
+                mCommandCond.signal();
+                mWaitWorkCV.wait(mLock);
+                delete data;
+                }break;
+            case SET_PARAMETERS: {
+                 ParametersData *data = (ParametersData *)command->mParam;
+                 LOGV("AudioCommandThread() processing set parameters string %s, io %p", data->mKeyValuePairs.string(), data->mIO);
+                 mCommandStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
+                 mCommandCond.signal();
+                 mWaitWorkCV.wait(mLock);
+                 delete data;
+                 }break;
+            default:
+                LOGW("AudioCommandThread() unknown command %d", command->mCommand);
+            }
+            delete command;
+        }
+        LOGV("AudioCommandThread() going to sleep");
+        mWaitWorkCV.wait(mLock);
+        LOGV("AudioCommandThread() waking up");
+    }
+    mLock.unlock();
+    return false;
+}
+
+void AudioPolicyService::AudioCommandThread::startToneCommand(int type, int stream)
+{
+    Mutex::Autolock _l(mLock);
+    AudioCommand *command = new AudioCommand();
+    command->mCommand = START_TONE;
+    ToneData *data = new ToneData();
+    data->mType = type;
+    data->mStream = stream;
+    command->mParam = (void *)data;
+    mAudioCommands.add(command);
+    LOGV("AudioCommandThread() adding tone start type %d, stream %d", type, stream);
+    mWaitWorkCV.signal();
+}
+
+void AudioPolicyService::AudioCommandThread::stopToneCommand()
+{
+    Mutex::Autolock _l(mLock);
+    AudioCommand *command = new AudioCommand();
+    command->mCommand = STOP_TONE;
+    command->mParam = NULL;
+    mAudioCommands.add(command);
+    LOGV("AudioCommandThread() adding tone stop");
+    mWaitWorkCV.signal();
+}
+
+status_t AudioPolicyService::AudioCommandThread::volumeCommand(int stream, float volume, void *output)
+{
+    Mutex::Autolock _l(mLock);
+    AudioCommand *command = new AudioCommand();
+    command->mCommand = SET_VOLUME;
+    VolumeData *data = new VolumeData();
+    data->mStream = stream;
+    data->mVolume = volume;
+    data->mIO = output;
+    command->mParam = data;
+    mAudioCommands.add(command);
+    LOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %p", stream, volume, output);
+    mWaitWorkCV.signal();
+    mCommandCond.wait(mLock);
+    status_t status =  mCommandStatus;
+    mWaitWorkCV.signal();
+    return status;
+}
+
+status_t AudioPolicyService::AudioCommandThread::parametersCommand(void *ioHandle, const String8& keyValuePairs)
+{
+    Mutex::Autolock _l(mLock);
+    AudioCommand *command = new AudioCommand();
+    command->mCommand = SET_PARAMETERS;
+    ParametersData *data = new ParametersData();
+    data->mIO = ioHandle;
+    data->mKeyValuePairs = keyValuePairs;
+    command->mParam = data;
+    mAudioCommands.add(command);
+    LOGV("AudioCommandThread() adding set parameter string %s, io %p", keyValuePairs.string(), ioHandle);
+    mWaitWorkCV.signal();
+    mCommandCond.wait(mLock);
+    status_t status =  mCommandStatus;
+    mWaitWorkCV.signal();
+    return status;
+}
+
+void AudioPolicyService::AudioCommandThread::exit()
+{
+    LOGV("AudioCommandThread::exit");
+    {
+        AutoMutex _l(mLock);
+        requestExit();
+        mWaitWorkCV.signal();
+    }
+    requestExitAndWait();
+}
+
+}; // namespace android
diff --git a/libs/audioflinger/AudioPolicyService.h b/libs/audioflinger/AudioPolicyService.h
new file mode 100644
index 0000000..1c46975
--- /dev/null
+++ b/libs/audioflinger/AudioPolicyService.h
@@ -0,0 +1,198 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_AUDIOPOLICYSERVICE_H
+#define ANDROID_AUDIOPOLICYSERVICE_H
+
+#include <media/IAudioPolicyService.h>
+#include <hardware_legacy/AudioPolicyInterface.h>
+#include <media/ToneGenerator.h>
+
+namespace android {
+
+class String8;
+
+// ----------------------------------------------------------------------------
+
+class AudioPolicyService: public BnAudioPolicyService, public AudioPolicyClientInterface, public IBinder::DeathRecipient
+{
+
+public:
+    static  void        instantiate();
+
+    virtual status_t    dump(int fd, const Vector<String16>& args);
+
+    //
+    // BnAudioPolicyService (see AudioPolicyInterface for method descriptions)
+    //
+
+    virtual status_t setDeviceConnectionState(AudioSystem::audio_devices device,
+                                              AudioSystem::device_connection_state state,
+                                              const char *device_address);
+    virtual AudioSystem::device_connection_state getDeviceConnectionState(AudioSystem::audio_devices device,
+                                                                          const char *device_address);
+    virtual status_t setPhoneState(int state);
+    virtual status_t setRingerMode(uint32_t mode, uint32_t mask);
+    virtual status_t setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config);
+    virtual AudioSystem::forced_config getForceUse(AudioSystem::force_use usage);
+    virtual audio_io_handle_t getOutput(AudioSystem::stream_type stream,
+                                        uint32_t samplingRate = 0,
+                                        uint32_t format = AudioSystem::FORMAT_DEFAULT,
+                                        uint32_t channels = 0,
+                                        AudioSystem::output_flags flags = AudioSystem::OUTPUT_FLAG_INDIRECT);
+    virtual status_t startOutput(audio_io_handle_t output, AudioSystem::stream_type stream);
+    virtual status_t stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream);
+    virtual void releaseOutput(audio_io_handle_t output);
+    virtual audio_io_handle_t getInput(int inputSource,
+                                    uint32_t samplingRate = 0,
+                                    uint32_t format = AudioSystem::FORMAT_DEFAULT,
+                                    uint32_t channels = 0,
+                                    AudioSystem::audio_in_acoustics acoustics = (AudioSystem::audio_in_acoustics)0);
+    virtual status_t startInput(audio_io_handle_t input);
+    virtual status_t stopInput(audio_io_handle_t input);
+    virtual void releaseInput(audio_io_handle_t input);
+    virtual status_t initStreamVolume(AudioSystem::stream_type stream,
+                                      int indexMin,
+                                      int indexMax);
+    virtual status_t setStreamVolumeIndex(AudioSystem::stream_type stream, int index);
+    virtual status_t getStreamVolumeIndex(AudioSystem::stream_type stream, int *index);
+
+    virtual     status_t    onTransact(
+                                uint32_t code,
+                                const Parcel& data,
+                                Parcel* reply,
+                                uint32_t flags);
+
+    // IBinder::DeathRecipient
+    virtual     void        binderDied(const wp<IBinder>& who);
+
+    //
+    // AudioPolicyClientInterface
+    //
+    virtual audio_io_handle_t openOutput(uint32_t *pDevices,
+                                    uint32_t *pSamplingRate,
+                                    uint32_t *pFormat,
+                                    uint32_t *pChannels,
+                                    uint32_t *pLatencyMs,
+                                    AudioSystem::output_flags flags);
+    virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1, audio_io_handle_t output2);
+    virtual status_t closeOutput(audio_io_handle_t output);
+    virtual status_t suspendOutput(audio_io_handle_t output);
+    virtual status_t restoreOutput(audio_io_handle_t output);
+    virtual audio_io_handle_t openInput(uint32_t *pDevices,
+                                    uint32_t *pSamplingRate,
+                                    uint32_t *pFormat,
+                                    uint32_t *pChannels,
+                                    uint32_t acoustics);
+    virtual status_t closeInput(audio_io_handle_t input);
+    virtual status_t setStreamVolume(AudioSystem::stream_type stream, float volume, audio_io_handle_t output);
+    virtual status_t setStreamOutput(AudioSystem::stream_type stream, audio_io_handle_t output);
+    virtual void setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
+    virtual String8 getParameters(audio_io_handle_t ioHandle, const String8& keys);
+    virtual status_t startTone(ToneGenerator::tone_type tone, AudioSystem::stream_type stream);
+    virtual status_t stopTone();
+
+private:
+                        AudioPolicyService();
+    virtual             ~AudioPolicyService();
+
+    // Thread used for tone playback and to send audio config commands to audio flinger
+    // For tone playback, using a separate thread is necessary to avoid deadlock with mLock because startTone()
+    // and stopTone() are normally called with mLock locked and requesting a tone start or stop will cause
+    // calls to AudioPolicyService and an attempt to lock mLock.
+    // For audio config commands, it is necessary because audio flinger requires that the calling process (user)
+    // has permission to modify audio settings.
+    class AudioCommandThread : public Thread {
+    public:
+
+        // commands for tone AudioCommand
+        enum {
+            START_TONE,
+            STOP_TONE,
+            SET_VOLUME,
+            SET_PARAMETERS
+        };
+
+        AudioCommandThread ();
+        virtual             ~AudioCommandThread();
+
+        // Thread virtuals
+        virtual     void        onFirstRef();
+        virtual     bool        threadLoop();
+
+                    void        exit();
+                    void        startToneCommand(int type = 0, int stream = 0);
+                    void        stopToneCommand();
+                    status_t    volumeCommand(int stream, float volume, void *output);
+                    status_t    parametersCommand(void *ioHandle, const String8& keyValuePairs);
+
+    private:
+        // descriptor for requested tone playback event
+        class AudioCommand {
+        public:
+            int mCommand;   // START_TONE, STOP_TONE ...
+            void *mParam;
+        };
+
+        class ToneData {
+        public:
+            int mType;      // tone type (START_TONE only)
+            int mStream;    // stream type (START_TONE only)
+        };
+
+        class VolumeData {
+        public:
+            int mStream;
+            float mVolume;
+            void *mIO;
+        };
+        class ParametersData {
+        public:
+            void *mIO;
+            String8 mKeyValuePairs;
+        };
+
+
+        Mutex   mLock;
+        Condition mWaitWorkCV;
+        Vector<AudioCommand *> mAudioCommands;    // list of pending tone events
+        Condition              mCommandCond;
+        status_t               mCommandStatus;
+        ToneGenerator *mpToneGenerator;     // the tone generator
+    };
+
+    // Internal dump utilities.
+    status_t dumpPermissionDenial(int fd, const Vector<String16>& args);
+
+
+    Mutex   mLock;      // prevents concurrent access to AudioPolicy manager functions changing device
+                        // connection stated our routing
+    AudioPolicyInterface* mpPolicyManager;          // the platform specific policy manager
+    sp <AudioCommandThread> mAudioCommandThread;    // audio commands thread
+    sp <AudioCommandThread> mTonePlaybacThread;     // tone playback thread
+};
+
+}; // namespace android
+
+#endif // ANDROID_AUDIOPOLICYSERVICE_H
+
+
+
+
+
+
+
+
diff --git a/libs/binder/Android.mk b/libs/binder/Android.mk
new file mode 100644
index 0000000..2df6775
--- /dev/null
+++ b/libs/binder/Android.mk
@@ -0,0 +1,45 @@
+# 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.
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+# we have the common sources, plus some device-specific stuff
+LOCAL_SRC_FILES:= \
+	Binder.cpp \
+	BpBinder.cpp \
+	IInterface.cpp \
+	IMemory.cpp \
+	IPCThreadState.cpp \
+	IPermissionController.cpp \
+	IServiceManager.cpp \
+	MemoryDealer.cpp \
+    MemoryBase.cpp \
+    MemoryHeapBase.cpp \
+    MemoryHeapPmem.cpp \
+	Parcel.cpp \
+	Permission.cpp \
+	ProcessState.cpp \
+	Static.cpp
+
+LOCAL_LDLIBS += -lpthread
+
+LOCAL_SHARED_LIBRARIES := \
+	liblog \
+	libcutils \
+	libutils
+
+LOCAL_MODULE:= libbinder
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/libs/utils/Binder.cpp b/libs/binder/Binder.cpp
similarity index 92%
rename from libs/utils/Binder.cpp
rename to libs/binder/Binder.cpp
index 37e4685..0dd7622 100644
--- a/libs/utils/Binder.cpp
+++ b/libs/binder/Binder.cpp
@@ -14,12 +14,12 @@
  * limitations under the License.
  */
 
-#include <utils/Binder.h>
+#include <binder/Binder.h>
 
 #include <utils/Atomic.h>
-#include <utils/BpBinder.h>
-#include <utils/IInterface.h>
-#include <utils/Parcel.h>
+#include <binder/BpBinder.h>
+#include <binder/IInterface.h>
+#include <binder/Parcel.h>
 
 #include <stdio.h>
 
@@ -27,6 +27,17 @@
 
 // ---------------------------------------------------------------------------
 
+IBinder::IBinder()
+    : RefBase()
+{
+}
+
+IBinder::~IBinder()
+{
+}
+
+// ---------------------------------------------------------------------------
+
 sp<IInterface>  IBinder::queryLocalInterface(const String16& descriptor)
 {
     return NULL;
@@ -58,6 +69,8 @@
 
 // ---------------------------------------------------------------------------
 
+String16 BBinder::sEmptyDescriptor;
+
 BBinder::BBinder()
     : mExtras(NULL)
 {
@@ -73,10 +86,10 @@
     return NO_ERROR;
 }
 
-String16 BBinder::getInterfaceDescriptor() const
+const String16& BBinder::getInterfaceDescriptor() const
 {
     LOGW("reached BBinder::getInterfaceDescriptor (this=%p)", this);
-    return String16();
+    return sEmptyDescriptor;
 }
 
 status_t BBinder::transact(
diff --git a/libs/utils/BpBinder.cpp b/libs/binder/BpBinder.cpp
similarity index 89%
rename from libs/utils/BpBinder.cpp
rename to libs/binder/BpBinder.cpp
index 69ab195..5de87ec 100644
--- a/libs/utils/BpBinder.cpp
+++ b/libs/binder/BpBinder.cpp
@@ -17,9 +17,9 @@
 #define LOG_TAG "BpBinder"
 //#define LOG_NDEBUG 0
 
-#include <utils/BpBinder.h>
+#include <binder/BpBinder.h>
 
-#include <utils/IPCThreadState.h>
+#include <binder/IPCThreadState.h>
 #include <utils/Log.h>
 
 #include <stdio.h>
@@ -98,16 +98,33 @@
     IPCThreadState::self()->incWeakHandle(handle);
 }
 
-String16 BpBinder::getInterfaceDescriptor() const
+bool BpBinder::isDescriptorCached() const {
+    Mutex::Autolock _l(mLock);
+    return mDescriptorCache.size() ? true : false;
+}
+
+const String16& BpBinder::getInterfaceDescriptor() const
 {
-    String16 res;
-    Parcel send, reply;
-    status_t err = const_cast<BpBinder*>(this)->transact(
-            INTERFACE_TRANSACTION, send, &reply);
-    if (err == NO_ERROR) {
-        res = reply.readString16();
+    if (isDescriptorCached() == false) {
+        Parcel send, reply;
+        // do the IPC without a lock held.
+        status_t err = const_cast<BpBinder*>(this)->transact(
+                INTERFACE_TRANSACTION, send, &reply);
+        if (err == NO_ERROR) {
+            String16 res(reply.readString16());
+            Mutex::Autolock _l(mLock);
+            // mDescriptorCache could have been assigned while the lock was
+            // released.
+            if (mDescriptorCache.size() == 0)
+                mDescriptorCache = res;
+        }
     }
-    return res;
+    
+    // we're returning a reference to a non-static object here. Usually this
+    // is not something smart to do, however, with binder objects it is 
+    // (usually) safe because they are reference-counted.
+    
+    return mDescriptorCache;
 }
 
 bool BpBinder::isBinderAlive() const
diff --git a/libs/utils/IInterface.cpp b/libs/binder/IInterface.cpp
similarity index 90%
rename from libs/utils/IInterface.cpp
rename to libs/binder/IInterface.cpp
index 6ea8178..29acf5d 100644
--- a/libs/utils/IInterface.cpp
+++ b/libs/binder/IInterface.cpp
@@ -14,12 +14,19 @@
  * limitations under the License.
  */
 
-#include <utils/IInterface.h>
+#include <binder/IInterface.h>
 
 namespace android {
 
 // ---------------------------------------------------------------------------
 
+IInterface::IInterface() 
+    : RefBase() {
+}
+
+IInterface::~IInterface() {
+}
+
 sp<IBinder> IInterface::asBinder()
 {
     return this ? onAsBinder() : NULL;
diff --git a/libs/utils/IMemory.cpp b/libs/binder/IMemory.cpp
similarity index 96%
rename from libs/utils/IMemory.cpp
rename to libs/binder/IMemory.cpp
index 429bc2b..6c1d225 100644
--- a/libs/utils/IMemory.cpp
+++ b/libs/binder/IMemory.cpp
@@ -25,11 +25,11 @@
 #include <sys/types.h>
 #include <sys/mman.h>
 
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 #include <utils/KeyedVector.h>
 #include <utils/threads.h>
 #include <utils/Atomic.h>
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 #include <utils/CallStack.h>
 
 #define VERBOSE   0
@@ -205,11 +205,11 @@
 
 IMPLEMENT_META_INTERFACE(Memory, "android.utils.IMemory");
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
+BnMemory::BnMemory() {
+}
+
+BnMemory::~BnMemory() { 
+}
 
 status_t BnMemory::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
@@ -299,11 +299,11 @@
         ssize_t size = reply.readInt32();
         uint32_t flags = reply.readInt32();
 
-        LOGE_IF(err, "binder=%p transaction failed fd=%d, size=%d, err=%d (%s)",
+        LOGE_IF(err, "binder=%p transaction failed fd=%d, size=%ld, err=%d (%s)",
                 asBinder().get(), parcel_fd, size, err, strerror(-err));
 
         int fd = dup( parcel_fd );
-        LOGE_IF(fd==-1, "cannot dup fd=%d, size=%d, err=%d (%s)",
+        LOGE_IF(fd==-1, "cannot dup fd=%d, size=%ld, err=%d (%s)",
                 parcel_fd, size, err, strerror(errno));
 
         int access = PROT_READ;
@@ -316,7 +316,7 @@
             mRealHeap = true;
             mBase = mmap(0, size, access, MAP_SHARED, fd, 0);
             if (mBase == MAP_FAILED) {
-                LOGE("cannot map BpMemoryHeap (binder=%p), size=%d, fd=%d (%s)",
+                LOGE("cannot map BpMemoryHeap (binder=%p), size=%ld, fd=%d (%s)",
                         asBinder().get(), size, fd, strerror(errno));
                 close(fd);
             } else {
@@ -357,8 +357,14 @@
 
 IMPLEMENT_META_INTERFACE(MemoryHeap, "android.utils.IMemoryHeap");
 
+BnMemoryHeap::BnMemoryHeap() { 
+}
+
+BnMemoryHeap::~BnMemoryHeap() { 
+}
+
 status_t BnMemoryHeap::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
+        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
     switch(code) {
        case HEAP_ID: {
diff --git a/libs/utils/IPCThreadState.cpp b/libs/binder/IPCThreadState.cpp
similarity index 98%
rename from libs/utils/IPCThreadState.cpp
rename to libs/binder/IPCThreadState.cpp
index 04ae142..c371a23 100644
--- a/libs/utils/IPCThreadState.cpp
+++ b/libs/binder/IPCThreadState.cpp
@@ -14,17 +14,17 @@
  * limitations under the License.
  */
 
-#include <utils/IPCThreadState.h>
+#include <binder/IPCThreadState.h>
 
-#include <utils/Binder.h>
-#include <utils/BpBinder.h>
+#include <binder/Binder.h>
+#include <binder/BpBinder.h>
 #include <utils/Debug.h>
 #include <utils/Log.h>
 #include <utils/TextOutput.h>
 #include <utils/threads.h>
 
-#include <private/utils/binder_module.h>
-#include <private/utils/Static.h>
+#include <private/binder/binder_module.h>
+#include <private/binder/Static.h>
 
 #include <sys/ioctl.h>
 #include <signal.h>
@@ -366,13 +366,8 @@
 
 void IPCThreadState::clearCaller()
 {
-    if (mProcess->supportsProcesses()) {
-        mCallingPid = getpid();
-        mCallingUid = getuid();
-    } else {
-        mCallingPid = -1;
-        mCallingUid = -1;
-    }
+    mCallingPid = getpid();
+    mCallingUid = getuid();
 }
 
 void IPCThreadState::flushCommands()
diff --git a/libs/utils/IPermissionController.cpp b/libs/binder/IPermissionController.cpp
similarity index 87%
rename from libs/utils/IPermissionController.cpp
rename to libs/binder/IPermissionController.cpp
index f01d38f..bff4c9b 100644
--- a/libs/utils/IPermissionController.cpp
+++ b/libs/binder/IPermissionController.cpp
@@ -16,14 +16,14 @@
 
 #define LOG_TAG "PermissionController"
 
-#include <utils/IPermissionController.h>
+#include <binder/IPermissionController.h>
 
 #include <utils/Debug.h>
 #include <utils/Log.h>
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 #include <utils/String8.h>
 
-#include <private/utils/Static.h>
+#include <private/binder/Static.h>
 
 namespace android {
 
@@ -55,12 +55,6 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnPermissionController::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/libs/utils/IServiceManager.cpp b/libs/binder/IServiceManager.cpp
similarity index 93%
rename from libs/utils/IServiceManager.cpp
rename to libs/binder/IServiceManager.cpp
index 9beeadd..0cf4158 100644
--- a/libs/utils/IServiceManager.cpp
+++ b/libs/binder/IServiceManager.cpp
@@ -16,16 +16,16 @@
 
 #define LOG_TAG "ServiceManager"
 
-#include <utils/IServiceManager.h>
+#include <binder/IServiceManager.h>
 
 #include <utils/Debug.h>
-#include <utils/IPCThreadState.h>
 #include <utils/Log.h>
-#include <utils/Parcel.h>
+#include <binder/IPCThreadState.h>
+#include <binder/Parcel.h>
 #include <utils/String8.h>
 #include <utils/SystemClock.h>
 
-#include <private/utils/Static.h>
+#include <private/binder/Static.h>
 
 #include <unistd.h>
 
@@ -53,14 +53,19 @@
 
 static String16 _permission("permission");
 
+
 bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
 {
     IPCThreadState* ipcState = IPCThreadState::self();
-    int32_t pid = ipcState->getCallingPid();
-    int32_t uid = ipcState->getCallingUid();
+    pid_t pid = ipcState->getCallingPid();
+    uid_t uid = ipcState->getCallingUid();
     if (outPid) *outPid = pid;
-    if (outUid) *outUid= uid;
-    
+    if (outUid) *outUid = uid;
+    return checkPermission(permission, pid, uid);
+}
+
+bool checkPermission(const String16& permission, pid_t pid, uid_t uid)
+{
     sp<IPermissionController> pc;
     gDefaultServiceManagerLock.lock();
     pc = gPermissionController;
@@ -178,12 +183,6 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnServiceManager::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/libs/utils/MemoryBase.cpp b/libs/binder/MemoryBase.cpp
similarity index 97%
rename from libs/utils/MemoryBase.cpp
rename to libs/binder/MemoryBase.cpp
index f25e11c..033066b 100644
--- a/libs/utils/MemoryBase.cpp
+++ b/libs/binder/MemoryBase.cpp
@@ -18,7 +18,7 @@
 #include <stdlib.h>
 #include <stdint.h>
 
-#include <utils/MemoryBase.h>
+#include <binder/MemoryBase.h>
 
 
 namespace android {
diff --git a/libs/utils/MemoryDealer.cpp b/libs/binder/MemoryDealer.cpp
similarity index 94%
rename from libs/utils/MemoryDealer.cpp
rename to libs/binder/MemoryDealer.cpp
index cf8201b..d5ffe7f 100644
--- a/libs/utils/MemoryDealer.cpp
+++ b/libs/binder/MemoryDealer.cpp
@@ -16,13 +16,13 @@
 
 #define LOG_TAG "MemoryDealer"
 
-#include <utils/MemoryDealer.h>
+#include <binder/MemoryDealer.h>
 
 #include <utils/Log.h>
-#include <utils/IPCThreadState.h>
+#include <binder/IPCThreadState.h>
 #include <utils/SortedVector.h>
 #include <utils/String8.h>
-#include <utils/MemoryBase.h>
+#include <binder/MemoryBase.h>
 
 #include <stdint.h>
 #include <stdio.h>
@@ -38,7 +38,15 @@
 #include <sys/file.h>
 
 namespace android {
+// ----------------------------------------------------------------------------
 
+HeapInterface::HeapInterface() { }
+HeapInterface::~HeapInterface() { }
+
+// ----------------------------------------------------------------------------
+
+AllocatorInterface::AllocatorInterface() { }
+AllocatorInterface::~AllocatorInterface() { }
 
 // ----------------------------------------------------------------------------
 
@@ -107,7 +115,7 @@
         if (new_memory != 0) {
             memory = new Allocation(this, offset, size, new_memory);
         } else {
-            LOGE("couldn't map [%8x, %d]", offset, size);
+            LOGE("couldn't map [%8lx, %u]", offset, size);
             if (size) {
                 /* NOTE: it's VERY important to not free allocations of size 0
                  * because they're special as they don't have any record in the 
@@ -339,6 +347,10 @@
         
 // ----------------------------------------------------------------------------
 
+SharedHeap::SharedHeap() 
+    : HeapInterface(), MemoryHeapBase() 
+{ 
+}
 
 SharedHeap::SharedHeap(size_t size, uint32_t flags, char const * name)
     : MemoryHeapBase(size, flags, name)
diff --git a/libs/utils/MemoryHeapBase.cpp b/libs/binder/MemoryHeapBase.cpp
similarity index 98%
rename from libs/utils/MemoryHeapBase.cpp
rename to libs/binder/MemoryHeapBase.cpp
index 8251728..ac38f51 100644
--- a/libs/utils/MemoryHeapBase.cpp
+++ b/libs/binder/MemoryHeapBase.cpp
@@ -29,7 +29,7 @@
 #include <cutils/ashmem.h>
 #include <cutils/atomic.h>
 
-#include <utils/MemoryHeapBase.h>
+#include <binder/MemoryHeapBase.h>
 
 #if HAVE_ANDROID_OS
 #include <linux/android_pmem.h>
diff --git a/libs/utils/MemoryHeapPmem.cpp b/libs/binder/MemoryHeapPmem.cpp
similarity index 98%
rename from libs/utils/MemoryHeapPmem.cpp
rename to libs/binder/MemoryHeapPmem.cpp
index eba2b30..3806a42 100644
--- a/libs/utils/MemoryHeapPmem.cpp
+++ b/libs/binder/MemoryHeapPmem.cpp
@@ -27,8 +27,8 @@
 
 #include <cutils/log.h>
 
-#include <utils/MemoryHeapPmem.h>
-#include <utils/MemoryHeapBase.h>
+#include <binder/MemoryHeapPmem.h>
+#include <binder/MemoryHeapBase.h>
 
 #if HAVE_ANDROID_OS
 #include <linux/android_pmem.h>
@@ -108,7 +108,7 @@
     // promote() it.
     
 #if HAVE_ANDROID_OS
-    if (mSize != NULL) {
+    if (mSize != 0) {
         const sp<MemoryHeapPmem>& heap(getHeap());
         int our_fd = heap->heapID();
         struct pmem_region sub;
diff --git a/libs/utils/Parcel.cpp b/libs/binder/Parcel.cpp
similarity index 98%
rename from libs/utils/Parcel.cpp
rename to libs/binder/Parcel.cpp
index b0e3750..f40e4bd 100644
--- a/libs/utils/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -17,19 +17,19 @@
 #define LOG_TAG "Parcel"
 //#define LOG_NDEBUG 0
 
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 
-#include <utils/Binder.h>
-#include <utils/BpBinder.h>
+#include <binder/Binder.h>
+#include <binder/BpBinder.h>
 #include <utils/Debug.h>
-#include <utils/ProcessState.h>
+#include <binder/ProcessState.h>
 #include <utils/Log.h>
 #include <utils/String8.h>
 #include <utils/String16.h>
 #include <utils/TextOutput.h>
 #include <utils/misc.h>
 
-#include <private/utils/binder_module.h>
+#include <private/binder/binder_module.h>
 
 #include <stdio.h>
 #include <stdlib.h>
@@ -441,9 +441,14 @@
     return writeString16(interface);
 }
 
+bool Parcel::checkInterface(IBinder* binder) const
+{
+    return enforceInterface(binder->getInterfaceDescriptor()); 
+}
+
 bool Parcel::enforceInterface(const String16& interface) const
 {
-    String16 str = readString16();
+    const String16 str(readString16());
     if (str == interface) {
         return true;
     } else {
diff --git a/libs/binder/Permission.cpp b/libs/binder/Permission.cpp
new file mode 100644
index 0000000..fd8fe69
--- /dev/null
+++ b/libs/binder/Permission.cpp
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+
+#include <stdint.h>
+#include <utils/Log.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/Permission.h>
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+Permission::Permission(char const* name)
+    : mPermissionName(name), mPid(getpid())
+{
+}
+
+Permission::Permission(const String16& name)
+    : mPermissionName(name), mPid(getpid())
+{
+}
+
+Permission::Permission(const Permission& rhs)
+    : mPermissionName(rhs.mPermissionName),
+    mGranted(rhs.mGranted),
+    mPid(rhs.mPid)
+{
+}
+
+Permission::~Permission()
+{
+}
+
+bool Permission::operator < (const Permission& rhs) const
+{
+    return mPermissionName < rhs.mPermissionName;
+}
+
+bool Permission::checkCalling() const
+{
+    IPCThreadState* ipcState = IPCThreadState::self();
+    pid_t pid = ipcState->getCallingPid();
+    uid_t uid = ipcState->getCallingUid();
+    return doCheckPermission(pid, uid);
+}
+
+bool Permission::check(pid_t pid, uid_t uid) const
+{
+    return doCheckPermission(pid, uid);
+}
+
+bool Permission::doCheckPermission(pid_t pid, uid_t uid) const
+{
+    if ((uid == 0) || (pid == mPid)) {
+        // root and ourselves is always okay
+        return true;
+    } else {
+        // see if we already granted this permission for this uid
+        Mutex::Autolock _l(mLock);
+        if (mGranted.indexOf(uid) >= 0)
+            return true;
+    }
+
+    bool granted = checkPermission(mPermissionName, pid, uid);
+    if (granted) {
+        Mutex::Autolock _l(mLock);
+        // no need to check again, the old item will be replaced if it is
+        // already there.
+        mGranted.add(uid);
+    }
+    return granted;
+}
+
+// ---------------------------------------------------------------------------
+}; // namespace android
diff --git a/libs/utils/ProcessState.cpp b/libs/binder/ProcessState.cpp
similarity index 97%
rename from libs/utils/ProcessState.cpp
rename to libs/binder/ProcessState.cpp
index 4567df6..d7daf73 100644
--- a/libs/utils/ProcessState.cpp
+++ b/libs/binder/ProcessState.cpp
@@ -18,19 +18,19 @@
 
 #include <cutils/process_name.h>
 
-#include <utils/ProcessState.h>
+#include <binder/ProcessState.h>
 
 #include <utils/Atomic.h>
-#include <utils/BpBinder.h>
-#include <utils/IPCThreadState.h>
+#include <binder/BpBinder.h>
+#include <binder/IPCThreadState.h>
 #include <utils/Log.h>
 #include <utils/String8.h>
-#include <utils/IServiceManager.h>
+#include <binder/IServiceManager.h>
 #include <utils/String8.h>
 #include <utils/threads.h>
 
-#include <private/utils/binder_module.h>
-#include <private/utils/Static.h>
+#include <private/binder/binder_module.h>
+#include <private/binder/Static.h>
 
 #include <errno.h>
 #include <fcntl.h>
diff --git a/libs/binder/Static.cpp b/libs/binder/Static.cpp
new file mode 100644
index 0000000..12b0308
--- /dev/null
+++ b/libs/binder/Static.cpp
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2008 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.
+ */
+
+// All static variables go here, to control initialization and
+// destruction order in the library.
+
+#include <private/binder/Static.h>
+
+#include <binder/IPCThreadState.h>
+#include <utils/Log.h>
+
+namespace android {
+
+// ------------ ProcessState.cpp
+
+Mutex gProcessMutex;
+sp<ProcessState> gProcess;
+
+class LibUtilsIPCtStatics
+{
+public:
+    LibUtilsIPCtStatics()
+    {
+    }
+    
+    ~LibUtilsIPCtStatics()
+    {
+        IPCThreadState::shutdown();
+    }
+};
+
+static LibUtilsIPCtStatics gIPCStatics;
+
+// ------------ ServiceManager.cpp
+
+Mutex gDefaultServiceManagerLock;
+sp<IServiceManager> gDefaultServiceManager;
+sp<IPermissionController> gPermissionController;
+
+}   // namespace android
diff --git a/libs/rs/Android.mk b/libs/rs/Android.mk
new file mode 100644
index 0000000..6b11a25
--- /dev/null
+++ b/libs/rs/Android.mk
@@ -0,0 +1,117 @@
+ifeq ($(BUILD_RENDERSCRIPT),true)
+
+LOCAL_PATH:=$(call my-dir)
+
+
+# Build rsg-generator ====================
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := rsg-generator
+
+# These symbols are normally defined by BUILD_XXX, but we need to define them
+# here so that local-intermediates-dir works.
+
+LOCAL_IS_HOST_MODULE := true
+LOCAL_MODULE_CLASS := EXECUTABLES
+intermediates := $(local-intermediates-dir)
+
+GEN := $(addprefix $(intermediates)/, \
+            lex.yy.c \
+        )
+$(GEN):	PRIVATE_CUSTOM_TOOL = flex -o $@ $<
+
+$(intermediates)/lex.yy.c : $(LOCAL_PATH)/spec.lex
+	$(transform-generated-source)
+
+$(LOCAL_PATH)/rsg_generator.c : $(intermediates)/lex.yy.c
+
+LOCAL_SRC_FILES:= \
+    rsg_generator.c
+
+include $(BUILD_HOST_EXECUTABLE)
+
+# TODO: This should go into build/core/config.mk
+RSG_GENERATOR:=$(LOCAL_BUILT_MODULE)
+
+
+
+# Build render script lib ====================
+include $(CLEAR_VARS)
+LOCAL_MODULE := libRS
+
+LOCAL_MODULE_CLASS := SHARED_LIBRARIES
+intermediates:= $(local-intermediates-dir)
+
+# Generate custom headers
+
+GEN := $(addprefix $(intermediates)/, \
+            rsgApiStructs.h \
+            rsgApiFuncDecl.h \
+        )
+
+$(GEN) : PRIVATE_PATH := $(LOCAL_PATH)
+$(GEN) : PRIVATE_CUSTOM_TOOL = $(RSG_GENERATOR) $< $@ <$(PRIVATE_PATH)/rs.spec
+$(GEN) : $(RSG_GENERATOR) $(LOCAL_PATH)/rs.spec
+$(GEN): $(intermediates)/%.h : $(LOCAL_PATH)/%.h.rsg
+	$(transform-generated-source)
+
+# used in jni/Android.mk
+rs_generated_source += $(GEN)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+# Generate custom source files
+
+GEN := $(addprefix $(intermediates)/, \
+            rsgApi.cpp \
+            rsgApiReplay.cpp \
+        )
+
+$(GEN) : PRIVATE_PATH := $(LOCAL_PATH)
+$(GEN) : PRIVATE_CUSTOM_TOOL = $(RSG_GENERATOR) $< $@ <$(PRIVATE_PATH)/rs.spec
+$(GEN) : $(RSG_GENERATOR) $(LOCAL_PATH)/rs.spec
+$(GEN): $(intermediates)/%.cpp : $(LOCAL_PATH)/%.cpp.rsg
+	$(transform-generated-source)
+
+# used in jni/Android.mk
+rs_generated_source += $(GEN)
+
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+LOCAL_SRC_FILES:= \
+	rsAdapter.cpp \
+	rsAllocation.cpp \
+	rsComponent.cpp \
+	rsContext.cpp \
+	rsDevice.cpp \
+	rsElement.cpp \
+        rsFileA3D.cpp \
+	rsLight.cpp \
+	rsLocklessFifo.cpp \
+	rsObjectBase.cpp \
+	rsMatrix.cpp \
+        rsMesh.cpp \
+	rsProgram.cpp \
+	rsProgramFragment.cpp \
+	rsProgramFragmentStore.cpp \
+	rsProgramVertex.cpp \
+	rsSampler.cpp \
+	rsScript.cpp \
+	rsScriptC.cpp \
+	rsScriptC_Lib.cpp \
+	rsThreadIO.cpp \
+	rsType.cpp \
+	rsTriangleMesh.cpp
+
+LOCAL_SHARED_LIBRARIES += libcutils libutils libEGL libGLESv1_CM libui libacc
+LOCAL_LDLIBS := -lpthread -ldl
+LOCAL_MODULE:= libRS
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
+
+# Include the subdirectories ====================
+include $(addprefix $(LOCAL_PATH)/,$(addsuffix /Android.mk,\
+            java \
+    	))
+
+endif
\ No newline at end of file
diff --git a/libs/rs/RenderScript.h b/libs/rs/RenderScript.h
new file mode 100644
index 0000000..855ea63
--- /dev/null
+++ b/libs/rs/RenderScript.h
@@ -0,0 +1,196 @@
+/*
+ * 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.
+ */
+
+#ifndef RENDER_SCRIPT_H
+#define RENDER_SCRIPT_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//////////////////////////////////////////////////////
+// 
+
+typedef void * RsAdapter1D;
+typedef void * RsAdapter2D;
+typedef void * RsAllocation;
+typedef void * RsContext;
+typedef void * RsDevice;
+typedef void * RsElement;
+typedef void * RsFile;
+typedef void * RsSampler;
+typedef void * RsScript;
+typedef void * RsScriptBasicTemp;
+typedef void * RsTriangleMesh;
+typedef void * RsType;
+typedef void * RsLight;
+
+typedef void * RsProgramVertex;
+typedef void * RsProgramFragment;
+typedef void * RsProgramFragmentStore;
+
+RsDevice rsDeviceCreate();
+void rsDeviceDestroy(RsDevice);
+
+RsContext rsContextCreate(RsDevice, void *, uint32_t version);
+void rsContextDestroy(RsContext);
+
+enum RsDataType {
+    RS_TYPE_FLOAT,
+    RS_TYPE_UNSIGNED,
+    RS_TYPE_SIGNED
+};
+
+enum RsDataKind {
+    RS_KIND_USER,
+    RS_KIND_RED, 
+    RS_KIND_GREEN, 
+    RS_KIND_BLUE, 
+    RS_KIND_ALPHA, 
+    RS_KIND_LUMINANCE, 
+    RS_KIND_INTENSITY,
+    RS_KIND_X, 
+    RS_KIND_Y, 
+    RS_KIND_Z, 
+    RS_KIND_W,
+    RS_KIND_S, 
+    RS_KIND_T, 
+    RS_KIND_Q, 
+    RS_KIND_R,
+    RS_KIND_NX, 
+    RS_KIND_NY, 
+    RS_KIND_NZ,
+    RS_KIND_INDEX
+};
+
+enum RsElementPredefined {
+    RS_ELEMENT_USER_U8,
+    RS_ELEMENT_USER_I8,
+    RS_ELEMENT_USER_U16,
+    RS_ELEMENT_USER_I16,
+    RS_ELEMENT_USER_U32,
+    RS_ELEMENT_USER_I32,
+    RS_ELEMENT_USER_FLOAT, 
+
+    RS_ELEMENT_A_8,          // 7
+    RS_ELEMENT_RGB_565,      // 8
+    RS_ELEMENT_RGBA_5551,    // 9
+    RS_ELEMENT_RGBA_4444,    // 10
+    RS_ELEMENT_RGB_888,      // 11
+    RS_ELEMENT_RGBA_8888,    // 12
+
+    RS_ELEMENT_INDEX_16, //13
+    RS_ELEMENT_INDEX_32, 
+    RS_ELEMENT_XY_F32, 
+    RS_ELEMENT_XYZ_F32, 
+    RS_ELEMENT_ST_XY_F32, 
+    RS_ELEMENT_ST_XYZ_F32, 
+    RS_ELEMENT_NORM_XYZ_F32,
+    RS_ELEMENT_NORM_ST_XYZ_F32,
+};  
+
+enum RsSamplerParam {
+    RS_SAMPLER_MIN_FILTER,
+    RS_SAMPLER_MAG_FILTER,
+    RS_SAMPLER_WRAP_S,
+    RS_SAMPLER_WRAP_T,
+    RS_SAMPLER_WRAP_R
+};  
+
+enum RsSamplerValue {
+    RS_SAMPLER_NEAREST,
+    RS_SAMPLER_LINEAR,
+    RS_SAMPLER_LINEAR_MIP_LINEAR,
+    RS_SAMPLER_WRAP,
+    RS_SAMPLER_CLAMP
+};  
+
+enum RsDimension {
+    RS_DIMENSION_X,
+    RS_DIMENSION_Y,
+    RS_DIMENSION_Z,
+    RS_DIMENSION_LOD,
+    RS_DIMENSION_FACE,
+
+    RS_DIMENSION_ARRAY_0 = 100, 
+    RS_DIMENSION_ARRAY_1, 
+    RS_DIMENSION_ARRAY_2, 
+    RS_DIMENSION_ARRAY_3,
+    RS_DIMENSION_MAX = RS_DIMENSION_ARRAY_3
+};
+
+enum RsDepthFunc {
+    RS_DEPTH_FUNC_ALWAYS,
+    RS_DEPTH_FUNC_LESS,
+    RS_DEPTH_FUNC_LEQUAL,
+    RS_DEPTH_FUNC_GREATER,
+    RS_DEPTH_FUNC_GEQUAL,
+    RS_DEPTH_FUNC_EQUAL,
+    RS_DEPTH_FUNC_NOTEQUAL
+};
+
+enum RsBlendSrcFunc {
+    RS_BLEND_SRC_ZERO, 
+    RS_BLEND_SRC_ONE, 
+    RS_BLEND_SRC_DST_COLOR, 
+    RS_BLEND_SRC_ONE_MINUS_DST_COLOR, 
+    RS_BLEND_SRC_SRC_ALPHA, 
+    RS_BLEND_SRC_ONE_MINUS_SRC_ALPHA, 
+    RS_BLEND_SRC_DST_ALPHA, 
+    RS_BLEND_SRC_ONE_MINUS_DST_ALPHA, 
+    RS_BLEND_SRC_SRC_ALPHA_SATURATE
+};
+
+enum RsBlendDstFunc {
+    RS_BLEND_DST_ZERO, 
+    RS_BLEND_DST_ONE, 
+    RS_BLEND_DST_SRC_COLOR, 
+    RS_BLEND_DST_ONE_MINUS_SRC_COLOR, 
+    RS_BLEND_DST_SRC_ALPHA, 
+    RS_BLEND_DST_ONE_MINUS_SRC_ALPHA, 
+    RS_BLEND_DST_DST_ALPHA, 
+    RS_BLEND_DST_ONE_MINUS_DST_ALPHA
+};
+
+enum RsTexEnvMode {
+    RS_TEX_ENV_MODE_REPLACE,
+    RS_TEX_ENV_MODE_MODULATE,
+    RS_TEX_ENV_MODE_DECAL
+};
+
+enum RsPrimitive {
+    RS_PRIMITIVE_POINT,
+    RS_PRIMITIVE_LINE,
+    RS_PRIMITIVE_LINE_STRIP,
+    RS_PRIMITIVE_TRIANGLE,
+    RS_PRIMITIVE_TRIANGLE_STRIP,
+    RS_PRIMITIVE_TRIANGLE_FAN
+};
+
+
+#include "rsgApiFuncDecl.h"
+
+#ifdef __cplusplus
+};
+#endif
+
+#endif // RENDER_SCRIPT_H
+
+
+
diff --git a/libs/rs/RenderScriptEnv.h b/libs/rs/RenderScriptEnv.h
new file mode 100644
index 0000000..0789301
--- /dev/null
+++ b/libs/rs/RenderScriptEnv.h
@@ -0,0 +1,40 @@
+#include <stdint.h>
+
+
+typedef void * RsAdapter1D;
+typedef void * RsAdapter2D;
+typedef void * RsAllocation;
+typedef void * RsContext;
+typedef void * RsDevice;
+typedef void * RsElement;
+typedef void * RsSampler;
+typedef void * RsScript;
+typedef void * RsScriptBasicTemp;
+typedef void * RsTriangleMesh;
+typedef void * RsType;
+typedef void * RsProgramFragment;
+typedef void * RsProgramFragmentStore;
+typedef void * RsLight;
+
+
+typedef struct {
+    float m[16];
+} rsc_Matrix;
+
+
+typedef struct {
+    float v[4];
+} rsc_Vector4;
+
+#define RS_PROGRAM_VERTEX_MODELVIEW_OFFSET 0
+#define RS_PROGRAM_VERTEX_PROJECTION_OFFSET 16
+#define RS_PROGRAM_VERTEX_TEXTURE_OFFSET 32
+
+//typedef int (*rsc_RunScript)(uint32_t launchIndex, const rsc_FunctionTable *);
+
+
+/* EnableCap */
+#define GL_LIGHTING                       0x0B50
+
+/* LightName */
+#define GL_LIGHT0                         0x4000
diff --git a/libs/rs/java/Android.mk b/libs/rs/java/Android.mk
new file mode 100644
index 0000000..5053e7d
--- /dev/null
+++ b/libs/rs/java/Android.mk
@@ -0,0 +1 @@
+include $(call all-subdir-makefiles)
diff --git a/libs/rs/java/Film/Android.mk b/libs/rs/java/Film/Android.mk
new file mode 100644
index 0000000..b7f98fc
--- /dev/null
+++ b/libs/rs/java/Film/Android.mk
@@ -0,0 +1,25 @@
+#
+# Copyright (C) 2008 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+#LOCAL_STATIC_JAVA_LIBRARIES := android.renderscript
+
+LOCAL_PACKAGE_NAME := Film
+
+include $(BUILD_PACKAGE)
diff --git a/libs/rs/java/Film/AndroidManifest.xml b/libs/rs/java/Film/AndroidManifest.xml
new file mode 100644
index 0000000..a5ce8a1
--- /dev/null
+++ b/libs/rs/java/Film/AndroidManifest.xml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.film">
+    <application android:label="Film">
+        <activity android:name="Film"
+                  android:screenOrientation="portrait"
+                  android:theme="@android:style/Theme.Black.NoTitleBar">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/libs/rs/java/Film/res/raw/filmimage.c b/libs/rs/java/Film/res/raw/filmimage.c
new file mode 100644
index 0000000..3bd9496
--- /dev/null
+++ b/libs/rs/java/Film/res/raw/filmimage.c
@@ -0,0 +1,110 @@
+// Fountain test script
+
+#pragma version(1)
+#pragma stateVertex(orthoWindow)
+#pragma stateRaster(flat)
+#pragma stateFragment(PgmFragBackground)
+#pragma stateFragmentStore(MyBlend)
+
+
+int main(void* con, int ft, int launchID) {
+    int count, touch, x, y, rate, maxLife, lifeShift;
+    int life;
+    int ct, ct2;
+    int newPart;
+    int drawCount;
+    int dx, dy, idx;
+    int posx,posy;
+    int c;
+    int srcIdx;
+    int dstIdx;
+
+    count = loadI32(con, 0, 1);
+    touch = loadI32(con, 0, 2);
+    x = loadI32(con, 0, 3);
+    y = loadI32(con, 0, 4);
+
+    rate = 4;
+    maxLife = (count / rate) - 1;
+    lifeShift = 0;
+    {
+        life = maxLife;
+        while (life > 255) {
+            life = life >> 1;
+            lifeShift ++;
+        }
+    }
+
+    drawRect(con, 0, 256, 0, 512);
+    contextBindProgramFragment(con, NAMED_PgmFragParts);
+
+    if (touch) {
+        newPart = loadI32(con, 2, 0);
+        for (ct2=0; ct2<rate; ct2++) {
+            dx = scriptRand(con, 0x10000) - 0x8000;
+            dy = scriptRand(con, 0x10000) - 0x8000;
+
+            idx = newPart * 5 + 1;
+            storeI32(con, 2, idx, dx);
+            storeI32(con, 2, idx + 1, dy);
+            storeI32(con, 2, idx + 2, maxLife);
+            storeI32(con, 2, idx + 3, x << 16);
+            storeI32(con, 2, idx + 4, y << 16);
+
+            newPart++;
+            if (newPart >= count) {
+                newPart = 0;
+            }
+        }
+        storeI32(con, 2, 0, newPart);
+    }
+
+    drawCount = 0;
+    for (ct=0; ct < count; ct++) {
+        srcIdx = ct * 5 + 1;
+
+        dx = loadI32(con, 2, srcIdx);
+        dy = loadI32(con, 2, srcIdx + 1);
+        life = loadI32(con, 2, srcIdx + 2);
+        posx = loadI32(con, 2, srcIdx + 3);
+        posy = loadI32(con, 2, srcIdx + 4);
+
+        if (life) {
+            if (posy < (480 << 16)) {
+                dstIdx = drawCount * 9;
+                c = 0xffafcf | ((life >> lifeShift) << 24);
+
+                storeU32(con, 1, dstIdx, c);
+                storeI32(con, 1, dstIdx + 1, posx);
+                storeI32(con, 1, dstIdx + 2, posy);
+
+                storeU32(con, 1, dstIdx + 3, c);
+                storeI32(con, 1, dstIdx + 4, posx + 0x10000);
+                storeI32(con, 1, dstIdx + 5, posy + dy * 4);
+
+                storeU32(con, 1, dstIdx + 6, c);
+                storeI32(con, 1, dstIdx + 7, posx - 0x10000);
+                storeI32(con, 1, dstIdx + 8, posy + dy * 4);
+                drawCount ++;
+            } else {
+                if (dy > 0) {
+                    dy = (-dy) >> 1;
+                }
+            }
+
+            posx = posx + dx;
+            posy = posy + dy;
+            dy = dy + 0x400;
+            life --;
+
+            //storeI32(con, 2, srcIdx, dx);
+            storeI32(con, 2, srcIdx + 1, dy);
+            storeI32(con, 2, srcIdx + 2, life);
+            storeI32(con, 2, srcIdx + 3, posx);
+            storeI32(con, 2, srcIdx + 4, posy);
+        }
+    }
+
+    drawTriangleArray(con, NAMED_PartBuffer, drawCount);
+    return 1;
+}
diff --git a/libs/rs/java/Film/res/raw/filmstrip.c b/libs/rs/java/Film/res/raw/filmstrip.c
new file mode 100644
index 0000000..6885251
--- /dev/null
+++ b/libs/rs/java/Film/res/raw/filmstrip.c
@@ -0,0 +1,114 @@
+// Fountain test script
+
+#pragma version(1)
+#pragma stateVertex(PVBackground)
+#pragma stateFragment(PFBackground)
+#pragma stateFragmentStore(PFSBackground)
+
+/*
+typedef struct FilmScriptUserEnvRec {
+    RsAllocation tex[13];
+    int32_t triangleOffsets[64];
+    float triangleOffsetsTex[64];
+    int32_t triangleOffsetsCount;
+} FilmScriptUserEnv; 
+*/ 
+
+// The script enviroment has 3 env allocations.
+// bank0: (r) The enviroment structure
+// bank1: (r) The position information
+// bank2: (rw) The temporary texture state
+
+int main(int index) 
+{
+    int f1,f2,f3,f4, f5,f6,f7,f8, f9,f10,f11,f12, f13,f14,f15,f16;
+    int g1,g2,g3,g4, g5,g6,g7,g8, g9,g10,g11,g12, g13,g14,g15,g16;
+    float trans;
+    float rot;
+    int x;
+    float focusPos;  // float
+    int focusID;
+    int lastFocusID;
+    int imgCount;
+
+    trans = loadF(1, 0);
+    rot = loadF(1, 1);
+
+    matrixLoadScale(&f16, 2.f, 2.f, 2.f);
+    matrixTranslate(&f16, 0.f, 0.f, trans);
+    matrixRotate(&f16, 90.f, 0.f, 0.f, 1.f);
+    matrixRotate(&f16, rot, 1.f, 0.f, 0.f);
+    storeMatrix(3, 0, &f16);
+
+    //materialDiffuse(con, 0.0f, 0.0f, 0.0f, 1.0f);
+    //materialSpecular(con, 0.5f, 0.5f, 0.5f, 0.5f);
+    //materialShininess(intToFloat(20));
+    drawTriangleMesh(NAMED_mesh);
+
+
+
+    //int imgId = 0;
+
+    bindProgramFragmentStore(NAMED_PFImages);
+    bindProgramFragment(NAMED_PFSImages);
+    bindProgramVertex(NAMED_PVImages);
+
+    //focusPos = loadF(1, 2);
+    //focusID = 0;
+    //lastFocusID = loadI32(2, 0);
+    //imgCount = 13;
+
+    /*
+    disable(GL_LIGHTING);
+
+
+    if (trans > (-.3)) {
+        focusID = -1.0 - focusPos;
+        if (focusID >= imgCount) {
+            focusID = -1;
+        }
+    } else {
+        focusID = -1;
+    }
+
+    if (focusID != lastFocusID) {
+        if (lastFocusID >= 0) {
+            uploadToTexture(con, env->tex[lastFocusID], 1);
+        }
+        if (focusID >= 0) {
+            uploadToTexture(con, env->tex[focusID], 0);
+        }
+    }
+    storeEnvI32(con, 2, 0, focusID);
+
+
+    for (imgId=1; imgId <= imgCount; imgId++) {
+        float pos = focusPos + imgId + .4f;
+        int offset = (int)floor(pos*2);
+        pos -= 0.75;
+    
+        offset += env->triangleOffsetsCount / 2;
+    
+        if ((offset < 0) || (offset >= env->triangleOffsetsCount)) {
+            continue;
+        }
+    
+        int start = offset -2;
+        int end = offset + 2;
+    
+        if (start < 0) {
+            start = 0;
+        }
+        if (end > env->triangleOffsetsCount) {
+            end = env->triangleOffsetsCount;
+        }
+    
+        programFragmentBindTexture(con, env->fpImages, 0, env->tex[imgId - 1]);
+        matrixLoadTranslate(con, &m, -pos - env->triangleOffsetsTex[env->triangleOffsetsCount / 2], 0, 0); 
+        storeEnvMatrix(con, 3, RS_PROGRAM_VERTEX_TEXTURE_OFFSET, &m);
+        renderTriangleMeshRange(con, env->mesh, env->triangleOffsets[start], env->triangleOffsets[end] - env->triangleOffsets[start]);
+    } 
+*/
+    return 0;
+}
+
diff --git a/libs/rs/java/Film/src/com/android/film/Film.java b/libs/rs/java/Film/src/com/android/film/Film.java
new file mode 100644
index 0000000..6e99816
--- /dev/null
+++ b/libs/rs/java/Film/src/com/android/film/Film.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.film;
+
+import android.renderscript.RSSurfaceView;
+import android.renderscript.RenderScript;
+
+import android.app.Activity;
+import android.content.res.Configuration;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.provider.Settings.System;
+import android.util.Config;
+import android.util.Log;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.Window;
+import android.widget.Button;
+import android.widget.ListView;
+
+import java.lang.Runtime;
+
+public class Film extends Activity {
+    //EventListener mListener = new EventListener();
+
+    private static final String LOG_TAG = "libRS_jni";
+    private static final boolean DEBUG  = false;
+    private static final boolean LOG_ENABLED = DEBUG ? Config.LOGD : Config.LOGV;
+
+    private FilmView mView;
+
+    // get the current looper (from your Activity UI thread for instance
+
+
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        // Create our Preview view and set it as the content of our
+        // Activity
+        mView = new FilmView(this);
+        setContentView(mView);
+    }
+
+    @Override
+    protected void onResume() {
+        // Ideally a game should implement onResume() and onPause()
+        // to take appropriate action when the activity looses focus
+        super.onResume();
+        mView.onResume();
+    }
+
+    @Override
+    protected void onPause() {
+        // Ideally a game should implement onResume() and onPause()
+        // to take appropriate action when the activity looses focus
+        super.onPause();
+        mView.onPause();
+
+        Runtime.getRuntime().exit(0);
+    }
+
+
+    static void log(String message) {
+        if (LOG_ENABLED) {
+            Log.v(LOG_TAG, message);
+        }
+    }
+
+
+}
+
diff --git a/libs/rs/java/Film/src/com/android/film/FilmRS.java b/libs/rs/java/Film/src/com/android/film/FilmRS.java
new file mode 100644
index 0000000..fca0818
--- /dev/null
+++ b/libs/rs/java/Film/src/com/android/film/FilmRS.java
@@ -0,0 +1,222 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.film;
+
+import java.io.Writer;
+
+import android.renderscript.RenderScript;
+import android.renderscript.ProgramVertexAlloc;
+import android.renderscript.Matrix;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.os.Handler;
+import android.os.Message;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.Surface;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+
+public class FilmRS {
+
+    public FilmRS() {
+    }
+
+    public void init(RenderScript rs, Resources res, int width, int height) {
+        mRS = rs;
+        mRes = res;
+        initRS();
+    }
+
+    public void setFilmStripPosition(int x, int y)
+    {
+        if (x < 50) {
+            x = 50;
+        }
+        if (x > 270) {
+            x = 270;
+        }
+    
+        float anim = ((float)x-50) / 270.f;
+        mBufferPos[0] = 2f * anim + 0.5f;   // translation
+        mBufferPos[1] = (anim * 40);  // rotation
+        mBufferPos[2] = ((float)y) / 16.f - 8;  // focusPos
+        mAllocPos.data(mBufferPos);
+    }
+
+
+    private Resources mRes;
+    private RenderScript mRS;
+    private RenderScript.Script mScriptStrip;
+    private RenderScript.Script mScriptImage;
+    private RenderScript.Element mElementVertex;
+    private RenderScript.Element mElementIndex;
+    private RenderScript.Sampler mSampler;
+    private RenderScript.ProgramFragmentStore mPFSBackground;
+    private RenderScript.ProgramFragmentStore mPFSImages;
+    private RenderScript.ProgramFragment mPFBackground;
+    private RenderScript.ProgramFragment mPFImages;
+    private RenderScript.ProgramVertex mPVBackground;
+    private RenderScript.ProgramVertex mPVImages;
+    private ProgramVertexAlloc mPVA;
+
+    private RenderScript.Allocation mAllocEnv;
+    private RenderScript.Allocation mAllocPos;
+    private RenderScript.Allocation mAllocState;
+    private RenderScript.Allocation mAllocPV;
+    private RenderScript.TriangleMesh mMesh;
+    private RenderScript.Light mLight;
+
+    private float[] mBufferPos;
+    private float[] mBufferPV;
+
+    private void initSamplers() {
+        mRS.samplerBegin();
+        mRS.samplerSet(RenderScript.SamplerParam.FILTER_MIN,
+                       RenderScript.SamplerValue.LINEAR_MIP_LINEAR);
+        mRS.samplerSet(RenderScript.SamplerParam.WRAP_MODE_S,
+                       RenderScript.SamplerValue.CLAMP);
+        mRS.samplerSet(RenderScript.SamplerParam.WRAP_MODE_T,
+                       RenderScript.SamplerValue.CLAMP);
+        mSampler = mRS.samplerCreate();
+    }
+
+    private void initPFS() {
+        mRS.programFragmentStoreBegin(null, null);
+        mRS.programFragmentStoreDepthFunc(RenderScript.DepthFunc.LESS);
+        mRS.programFragmentStoreDitherEnable(true);
+        mPFSBackground = mRS.programFragmentStoreCreate();
+        mPFSBackground.setName("PFSBackground");
+
+        mRS.programFragmentStoreBegin(null, null);
+        mRS.programFragmentStoreDepthFunc(RenderScript.DepthFunc.EQUAL);
+        mRS.programFragmentStoreDitherEnable(false);
+        mRS.programFragmentStoreDepthMask(false);
+        mRS.programFragmentStoreBlendFunc(RenderScript.BlendSrcFunc.ONE, 
+                                          RenderScript.BlendDstFunc.ONE);
+        mPFSImages = mRS.programFragmentStoreCreate();
+        mPFSImages.setName("PFSImages");
+    }
+
+    private void initPF() {
+        mRS.programFragmentBegin(null, null);
+        mPFBackground = mRS.programFragmentCreate();
+        mPFBackground.setName("PFBackground");
+
+        mRS.programFragmentBegin(null, null);
+        mRS.programFragmentSetTexEnable(0, true);
+        //mRS.programFragmentSetEnvMode(0, RS_TEX_ENV_MODE_REPLACE);
+        //rsProgramFragmentSetType(0, gEnv.tex[0]->getType());
+        mPFImages = mRS.programFragmentCreate();
+        mPFImages.setName("PFImages");
+    }
+
+    private void initPV() {
+        mRS.lightBegin();
+        mLight = mRS.lightCreate();
+        mLight.setPosition(0, -0.5f, -1.0f);
+
+        mRS.programVertexBegin(null, null);
+        mRS.programVertexSetTextureMatrixEnable(true);
+        mRS.programVertexAddLight(mLight);
+        mPVBackground = mRS.programVertexCreate();
+        mPVBackground.setName("PVBackground");
+
+        mRS.programVertexBegin(null, null);
+        mPVImages = mRS.programVertexCreate();
+        mPVImages.setName("PVImages");
+    }
+
+
+    int mParams[] = new int[10];
+
+    private void initRS() {
+        mElementVertex = mRS.elementGetPredefined(
+            RenderScript.ElementPredefined.NORM_ST_XYZ_F32);
+        mElementIndex = mRS.elementGetPredefined(
+            RenderScript.ElementPredefined.INDEX_16);
+
+        mRS.triangleMeshBegin(mElementVertex, mElementIndex);
+        FilmStripMesh fsm = new FilmStripMesh();
+        fsm.init(mRS);
+        mMesh = mRS.triangleMeshCreate();
+        mMesh.setName("mesh");
+
+        initPFS();
+        initSamplers();
+        initPF();
+        initPV();
+        mPFImages.bindSampler(mSampler, 0);
+
+        Log.e("rs", "Done loading named");
+
+        mRS.scriptCBegin();
+        mRS.scriptCSetClearColor(0.0f, 0.0f, 0.0f, 1.0f);
+        mRS.scriptCSetScript(mRes, R.raw.filmstrip);
+        mRS.scriptCSetRoot(true);
+        mScriptStrip = mRS.scriptCCreate();
+
+        mBufferPos = new float[3];
+        mAllocPos = mRS.allocationCreatePredefSized(
+            RenderScript.ElementPredefined.USER_FLOAT, 
+            mBufferPos.length);
+
+        mPVA = new ProgramVertexAlloc(mRS);
+        mPVBackground.bindAllocation(0, mPVA.mAlloc);
+        mPVImages.bindAllocation(0, mPVA.mAlloc);
+        mPVA.setupProjectionNormalized(320, 480);
+
+
+        mScriptStrip.bindAllocation(mAllocPos, 1);
+       //mScriptStrip.bindAllocation(gStateAlloc, 2);
+        mScriptStrip.bindAllocation(mPVA.mAlloc, 3);
+
+
+/*
+        {
+            Resources res = getResources();
+            Drawable d = res.getDrawable(R.drawable.gadgets_clock_mp3);
+            BitmapDrawable bd = (BitmapDrawable)d;
+            Bitmap b = bd.getBitmap();
+            mTexture = mRS.allocationCreateFromBitmap(b,
+                                                      RenderScript.ElementPredefined.RGB_565,
+                                                      true);
+            mTexture.uploadToTexture(0);
+        }
+
+        mRS.programFragmentStoreBegin(null, null);
+        mRS.programFragmentStoreBlendFunc(RenderScript.BlendSrcFunc.SRC_ALPHA, RenderScript.BlendDstFunc.ONE);
+        mRS.programFragmentStoreDepthFunc(RenderScript.DepthFunc.ALWAYS);
+        mPFS = mRS.programFragmentStoreCreate();
+        mPFS.setName("MyBlend");
+        mRS.contextBindProgramFragmentStore(mPFS);
+        */
+
+        setFilmStripPosition(0, 0);
+
+        mRS.contextBindRootScript(mScriptStrip);
+    }
+}
+
+
+
diff --git a/libs/rs/java/Film/src/com/android/film/FilmStripMesh.java b/libs/rs/java/Film/src/com/android/film/FilmStripMesh.java
new file mode 100644
index 0000000..02bffd8
--- /dev/null
+++ b/libs/rs/java/Film/src/com/android/film/FilmStripMesh.java
@@ -0,0 +1,255 @@
+/*
+ * 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.
+ */
+
+
+package com.android.film;
+
+import java.io.Writer;
+import java.lang.Math;
+import android.util.Log;
+
+import android.renderscript.RenderScript;
+
+
+class FilmStripMesh {
+
+    class Vertex {
+        float nx;
+        float ny;
+        float nz;
+        float s;
+        float t;
+        float x;
+        float y;
+        float z;
+
+        Vertex() {
+            nx = 0;
+            ny = 0;
+            nz = 0;
+            s = 0;
+            t = 0;
+            x = 0;
+            y = 0;
+            z = 0;
+        }
+
+        void xyz(float _x, float _y, float _z) {
+            x = _x;
+            y = _y;
+            z = _z;
+        }
+
+        void nxyz(float _x, float _y, float _z) {
+            nx = _x;
+            ny = _y;
+            nz = _z;
+        }
+
+        void st(float _s, float _t) {
+            s = _s;
+            t = _t;
+        }
+
+        void computeNorm(Vertex v1, Vertex v2) {
+            float dx = v1.x - v2.x;
+            float dy = v1.y - v2.y;
+            float dz = v1.z - v2.z;
+            float len = (float)java.lang.Math.sqrt(dx*dx + dy*dy + dz*dz);
+            dx /= len;
+            dy /= len;
+            dz /= len;
+        
+            nx = dx * dz;
+            ny = dy * dz;
+            nz = (float)java.lang.Math.sqrt(dx*dx + dy*dy);
+        
+            len = (float)java.lang.Math.sqrt(nx*nx + ny*ny + nz*nz);
+            nx /= len;
+            ny /= len;
+            nz /= len;
+        }
+
+        void addToRS(RenderScript rs) {
+            rs.triangleMeshAddVertex_XYZ_ST_NORM(x, y, z, s, t, nx, ny, nz);
+        }
+    }
+
+    int[] mTriangleOffsets;
+    float[] mTriangleOffsetsTex;
+    int mTriangleOffsetsCount;
+
+    void init(RenderScript rs)
+    {
+        float vtx[] = new float[] {
+            60.431003f, 124.482050f,
+            60.862074f, 120.872604f,
+            61.705303f, 117.336662f,
+            62.949505f, 113.921127f,
+            64.578177f, 110.671304f,
+            66.569716f, 107.630302f,
+            68.897703f, 104.838457f,
+            71.531259f, 102.332803f,
+            74.435452f, 100.146577f,
+            77.571757f, 98.308777f,
+            80.898574f, 96.843781f,
+            84.371773f, 95.771023f,
+            87.945283f, 95.104731f,
+            98.958994f, 95.267098f,
+            109.489523f, 98.497596f,
+            118.699582f, 104.539366f,
+            125.856872f, 112.912022f,
+            130.392311f, 122.949849f,
+            131.945283f, 133.854731f,
+            130.392311f, 144.759613f,
+            125.856872f, 154.797439f,
+            118.699582f, 163.170096f,
+            109.489523f, 169.211866f,
+            98.958994f, 172.442364f,
+            87.945283f, 172.604731f,
+            72.507313f, 172.672927f,
+            57.678920f, 168.377071f,
+            44.668135f, 160.067134f,
+            34.534908f, 148.420104f,
+            28.104767f, 134.384831f,
+            25.901557f, 119.104731f,
+            28.104767f, 103.824631f,
+            34.534908f, 89.789358f,
+            44.668135f, 78.142327f,
+            57.678920f, 69.832390f,
+            72.507313f, 65.536534f,
+            87.945283f, 65.604731f,
+            106.918117f, 65.688542f,
+            125.141795f, 60.409056f,
+            141.131686f, 50.196376f,
+            153.585137f, 35.882502f,
+            161.487600f, 18.633545f,
+            164.195283f, -0.145269f,
+            161.487600f, -18.924084f,
+            153.585137f, -36.173040f,
+            141.131686f, -50.486914f,
+            125.141795f, -60.699594f,
+            106.918117f, -65.979081f,
+            87.945283f, -65.895269f,
+            80f, -65.895269f,
+            60f, -65.895269f,
+            40f, -65.895269f,
+            20f, -65.895269f,
+            0f, -65.895269f,
+            -20f, -65.895269f,
+            -40f, -65.895269f,
+            -60f, -65.895269f,
+            -80f, -65.895269f,
+            -87.945283f, -65.895269f,
+            -106.918117f, -65.979081f,
+            -125.141795f, -60.699594f,
+            -141.131686f, -50.486914f,
+            -153.585137f, -36.173040f,
+            -161.487600f, -18.924084f,
+            -164.195283f, -0.145269f,
+            -161.487600f, 18.633545f,
+             -153.585137f, 35.882502f,
+             -141.131686f, 50.196376f,
+             -125.141795f, 60.409056f,
+             -106.918117f, 65.688542f,
+             -87.945283f, 65.604731f,
+             -72.507313f, 65.536534f,
+             -57.678920f, 69.832390f,
+             -44.668135f, 78.142327f,
+             -34.534908f, 89.789358f,
+             -28.104767f, 103.824631f,
+             -25.901557f, 119.104731f,
+             -28.104767f, 134.384831f,
+             -34.534908f, 148.420104f,
+             -44.668135f, 160.067134f,
+             -57.678920f, 168.377071f,
+             -72.507313f, 172.672927f,
+             -87.945283f, 172.604731f,
+             -98.958994f, 172.442364f,
+             -109.489523f, 169.211866f,
+             -118.699582f, 163.170096f,
+             -125.856872f, 154.797439f,
+             -130.392311f, 144.759613f,
+             -131.945283f, 133.854731f,
+             -130.392311f, 122.949849f,
+             -125.856872f, 112.912022f,
+             -118.699582f, 104.539366f,
+             -109.489523f, 98.497596f,
+             -98.958994f, 95.267098f,
+             -87.945283f, 95.104731f,
+             -84.371773f, 95.771023f,
+             -80.898574f, 96.843781f,
+             -77.571757f, 98.308777f,
+             -74.435452f, 100.146577f,
+             -71.531259f, 102.332803f,
+             -68.897703f, 104.838457f,
+             -66.569716f, 107.630302f,
+             -64.578177f, 110.671304f,
+             -62.949505f, 113.921127f,
+             -61.705303f, 117.336662f,
+             -60.862074f, 120.872604f,
+             -60.431003f, 124.482050f
+        };
+    
+    
+        mTriangleOffsets = new int[64];
+        mTriangleOffsetsTex = new float[64];
+    
+        mTriangleOffsets[0] = 0;
+        mTriangleOffsetsCount = 1;
+
+        Vertex t = new Vertex();
+        t.nxyz(1, 0, 0);
+        int count = vtx.length / 2;
+
+        float runningS = 0;
+        for (int ct=0; ct < (count-1); ct++) {
+            t.x = -vtx[ct*2] / 100.f;
+            t.z = vtx[ct*2+1] / 100.f;
+            t.s = runningS;
+            t.nx =  (vtx[ct*2+3] - vtx[ct*2 +1]);
+            t.ny =  (vtx[ct*2+2] - vtx[ct*2   ]);
+            float len = (float)java.lang.Math.sqrt(t.nx * t.nx + t.ny * t.ny);
+            runningS += len / 100;
+            t.nx /= len;
+            t.ny /= len;
+            t.y = -0.5f;
+            t.t = 0;
+            //Log.e("xx", "vtx " + t.x + "  " + t.y + "  " + t.z);
+            t.addToRS(rs);
+            t.y = .5f;
+            t.t = 1;
+            t.addToRS(rs);
+
+            //LOGE(" %f", runningS);
+            if((runningS*2) > mTriangleOffsetsCount) {
+                //LOGE("**** img %i  %i", gTriangleOffsetsCount, ct*2);
+                mTriangleOffsets[mTriangleOffsetsCount] = ct*2;
+                mTriangleOffsetsTex[mTriangleOffsetsCount] = t.s;
+                mTriangleOffsetsCount ++;
+            }
+        }
+
+        count = (count * 2 - 2);
+        for (int ct=0; ct < (count-2); ct+= 2) {
+            rs.triangleMeshAddTriangle(ct, ct+1, ct+2);
+            rs.triangleMeshAddTriangle(ct+1, ct+3, ct+2);
+        }
+    }
+
+
+}
+
diff --git a/libs/rs/java/Film/src/com/android/film/FilmView.java b/libs/rs/java/Film/src/com/android/film/FilmView.java
new file mode 100644
index 0000000..a743b1b
--- /dev/null
+++ b/libs/rs/java/Film/src/com/android/film/FilmView.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.film;
+
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.concurrent.Semaphore;
+
+import android.renderscript.RSSurfaceView;
+import android.renderscript.RenderScript;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.os.Handler;
+import android.os.Message;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.Surface;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+
+public class FilmView extends RSSurfaceView {
+
+    public FilmView(Context context) {
+        super(context);
+
+        //setFocusable(true);
+    }
+
+    private RenderScript mRS;
+    private FilmRS mRender;
+
+    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
+        super.surfaceChanged(holder, format, w, h);
+
+        mRS = createRenderScript();
+        mRender = new FilmRS();
+        mRender.init(mRS, getResources(), w, h);
+    }
+
+    @Override
+    public boolean onKeyDown(int keyCode, KeyEvent event)
+    {
+        // break point at here
+        // this method doesn't work when 'extends View' include 'extends ScrollView'.
+        return super.onKeyDown(keyCode, event);
+    }
+
+
+    @Override
+    public boolean onTouchEvent(MotionEvent ev)
+    {
+        boolean ret = true;
+        int act = ev.getAction();
+        if (act == ev.ACTION_UP) {
+            ret = false;
+        }
+        mRender.setFilmStripPosition((int)ev.getX(), (int)ev.getY());
+        return ret;
+    }
+}
+
+
diff --git a/libs/rs/java/Fountain/Android.mk b/libs/rs/java/Fountain/Android.mk
new file mode 100644
index 0000000..b6a9f10
--- /dev/null
+++ b/libs/rs/java/Fountain/Android.mk
@@ -0,0 +1,25 @@
+#
+# Copyright (C) 2008 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+#LOCAL_STATIC_JAVA_LIBRARIES := android.renderscript
+
+LOCAL_PACKAGE_NAME := Fountain
+
+include $(BUILD_PACKAGE)
diff --git a/libs/rs/java/Fountain/AndroidManifest.xml b/libs/rs/java/Fountain/AndroidManifest.xml
new file mode 100644
index 0000000..dd0e428
--- /dev/null
+++ b/libs/rs/java/Fountain/AndroidManifest.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.fountain">
+    <application android:label="Fountain">
+        <activity android:name="Fountain"
+                  android:theme="@android:style/Theme.Translucent">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/libs/rs/java/Fountain/res/drawable/gadgets_clock_mp3.png b/libs/rs/java/Fountain/res/drawable/gadgets_clock_mp3.png
new file mode 100755
index 0000000..e91bfb4
--- /dev/null
+++ b/libs/rs/java/Fountain/res/drawable/gadgets_clock_mp3.png
Binary files differ
diff --git a/libs/rs/java/Fountain/res/raw/fountain.c b/libs/rs/java/Fountain/res/raw/fountain.c
new file mode 100644
index 0000000..99551fcd
--- /dev/null
+++ b/libs/rs/java/Fountain/res/raw/fountain.c
@@ -0,0 +1,106 @@
+// Fountain test script
+
+#pragma version(1)
+#pragma stateVertex(default)
+#pragma stateFragment(PgmFragParts)
+#pragma stateFragmentStore(PFSBlend)
+
+
+int main(int launchID) {
+    int count, touch, x, y, rate, maxLife, lifeShift;
+    int life;
+    int ct, ct2;
+    int newPart;
+    int drawCount;
+    int dx, dy, idx;
+    int posx,posy;
+    int c;
+    int srcIdx;
+    int dstIdx;
+
+    count = loadI32(0, 1);
+    touch = loadI32(0, 2);
+    x = loadI32(0, 3);
+    y = loadI32(0, 4);
+
+    rate = 4;
+    maxLife = (count / rate) - 1;
+    lifeShift = 0;
+    {
+        life = maxLife;
+        while (life > 255) {
+            life = life >> 1;
+            lifeShift ++;
+        }
+    }
+
+    if (touch) {
+        newPart = loadI32(2, 0);
+        for (ct2=0; ct2<rate; ct2++) {
+            dx = (int)((randf(1.f) - 0.5f) * 0x10000);
+            dy = (int)((randf(1.f) - 0.5f) * 0x10000);
+
+            idx = newPart * 5 + 1;
+            storeI32(2, idx, dx);
+            storeI32(2, idx + 1, dy);
+            storeI32(2, idx + 2, maxLife);
+            storeI32(2, idx + 3, x << 16);
+            storeI32(2, idx + 4, y << 16);
+
+            newPart++;
+            if (newPart >= count) {
+                newPart = 0;
+            }
+        }
+        storeI32(2, 0, newPart);
+    }
+
+    drawCount = 0;
+    for (ct=0; ct < count; ct++) {
+        srcIdx = ct * 5 + 1;
+
+        dx = loadI32(2, srcIdx);
+        dy = loadI32(2, srcIdx + 1);
+        life = loadI32(2, srcIdx + 2);
+        posx = loadI32(2, srcIdx + 3);
+        posy = loadI32(2, srcIdx + 4);
+
+        if (life) {
+            if (posy < (480 << 16)) {
+                dstIdx = drawCount * 9;
+                c = 0xffafcf | ((life >> lifeShift) << 24);
+
+                storeI32(1, dstIdx, c);
+                storeI32(1, dstIdx + 1, posx);
+                storeI32(1, dstIdx + 2, posy);
+
+                storeI32(1, dstIdx + 3, c);
+                storeI32(1, dstIdx + 4, posx + 0x10000);
+                storeI32(1, dstIdx + 5, posy + dy * 4);
+
+                storeI32(1, dstIdx + 6, c);
+                storeI32(1, dstIdx + 7, posx - 0x10000);
+                storeI32(1, dstIdx + 8, posy + dy * 4);
+                drawCount ++;
+            } else {
+                if (dy > 0) {
+                    dy = (-dy) >> 1;
+                }
+            }
+
+            posx = posx + dx;
+            posy = posy + dy;
+            dy = dy + 0x400;
+            life --;
+
+            //storeI32(2, srcIdx, dx);
+            storeI32(2, srcIdx + 1, dy);
+            storeI32(2, srcIdx + 2, life);
+            storeI32(2, srcIdx + 3, posx);
+            storeI32(2, srcIdx + 4, posy);
+        }
+    }
+
+    drawTriangleArray(NAMED_PartBuffer, drawCount);
+    return 1;
+}
diff --git a/libs/rs/java/Fountain/src/com/android/fountain/Fountain.java b/libs/rs/java/Fountain/src/com/android/fountain/Fountain.java
new file mode 100644
index 0000000..58c78fa
--- /dev/null
+++ b/libs/rs/java/Fountain/src/com/android/fountain/Fountain.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.fountain;
+
+import android.renderscript.RSSurfaceView;
+import android.renderscript.RenderScript;
+
+import android.app.Activity;
+import android.content.res.Configuration;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.provider.Settings.System;
+import android.util.Config;
+import android.util.Log;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.Window;
+import android.widget.Button;
+import android.widget.ListView;
+
+import java.lang.Runtime;
+
+public class Fountain extends Activity {
+    //EventListener mListener = new EventListener();
+
+    private static final String LOG_TAG = "libRS_jni";
+    private static final boolean DEBUG  = false;
+    private static final boolean LOG_ENABLED = DEBUG ? Config.LOGD : Config.LOGV;
+
+    private FountainView mView;
+
+    // get the current looper (from your Activity UI thread for instance
+
+
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        // Create our Preview view and set it as the content of our
+        // Activity
+        mView = new FountainView(this);
+        setContentView(mView);
+    }
+
+    @Override
+    protected void onResume() {
+        // Ideally a game should implement onResume() and onPause()
+        // to take appropriate action when the activity looses focus
+        super.onResume();
+        mView.onResume();
+    }
+
+    @Override
+    protected void onPause() {
+        // Ideally a game should implement onResume() and onPause()
+        // to take appropriate action when the activity looses focus
+        super.onPause();
+        mView.onPause();
+
+        Runtime.getRuntime().exit(0);
+    }
+
+
+    static void log(String message) {
+        if (LOG_ENABLED) {
+            Log.v(LOG_TAG, message);
+        }
+    }
+
+
+}
+
diff --git a/libs/rs/java/Fountain/src/com/android/fountain/FountainRS.java b/libs/rs/java/Fountain/src/com/android/fountain/FountainRS.java
new file mode 100644
index 0000000..c8e9a1e
--- /dev/null
+++ b/libs/rs/java/Fountain/src/com/android/fountain/FountainRS.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.fountain;
+
+import java.io.Writer;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.renderscript.RenderScript;
+import android.renderscript.ProgramVertexAlloc;
+import android.util.Log;
+
+public class FountainRS {
+
+    public FountainRS() {
+    }
+
+    public void init(RenderScript rs, Resources res, int width, int height) {
+        mRS = rs;
+        mRes = res;
+        initRS();
+    }
+
+    public void newTouchPosition(int x, int y) {
+        mParams[0] = 1;
+        mParams[1] = x;
+        mParams[2] = y;
+        mIntAlloc.subData1D(2, 3, mParams);
+    }
+
+
+    /////////////////////////////////////////
+
+    private Resources mRes;
+
+    private RenderScript mRS;
+    private RenderScript.Allocation mIntAlloc;
+    private RenderScript.Allocation mPartAlloc;
+    private RenderScript.Allocation mVertAlloc;
+    private RenderScript.Script mScript;
+    private RenderScript.ProgramFragmentStore mPFS;
+    private RenderScript.ProgramFragment mPF;
+
+    private Bitmap mBackground;
+
+    int mParams[] = new int[10];
+
+    private void initRS() {
+        int partCount = 1024;
+
+        mIntAlloc = mRS.allocationCreatePredefSized(RenderScript.ElementPredefined.USER_I32, 10);
+        mPartAlloc = mRS.allocationCreatePredefSized(RenderScript.ElementPredefined.USER_I32, partCount * 3 * 3);
+        mPartAlloc.setName("PartBuffer");
+        mVertAlloc = mRS.allocationCreatePredefSized(RenderScript.ElementPredefined.USER_I32, partCount * 5 + 1);
+
+        mRS.programFragmentStoreBegin(null, null);
+        mRS.programFragmentStoreBlendFunc(RenderScript.BlendSrcFunc.SRC_ALPHA, RenderScript.BlendDstFunc.ONE);
+        mRS.programFragmentStoreDepthFunc(RenderScript.DepthFunc.ALWAYS);
+        mRS.programFragmentStoreDepthMask(false);
+        mRS.programFragmentStoreDitherEnable(false);
+        mPFS = mRS.programFragmentStoreCreate();
+        mPFS.setName("PFSBlend");
+
+        mRS.programFragmentBegin(null, null);
+        mPF = mRS.programFragmentCreate();
+        mPF.setName("PgmFragParts");
+
+        mParams[0] = 0;
+        mParams[1] = partCount;
+        mParams[2] = 0;
+        mParams[3] = 0;
+        mParams[4] = 0;
+        mIntAlloc.data(mParams);
+
+        int t2[] = new int[partCount * 4*3];
+        for (int ct=0; ct < t2.length; ct++) {
+            t2[ct] = 0;
+        }
+        mPartAlloc.data(t2);
+
+        mRS.scriptCBegin();
+        mRS.scriptCSetClearColor(0.0f, 0.0f, 0.0f, 1.0f);
+        mRS.scriptCSetScript(mRes, R.raw.fountain);
+        mRS.scriptCSetRoot(true);
+        mScript = mRS.scriptCCreate();
+
+        mScript.bindAllocation(mIntAlloc, 0);
+        mScript.bindAllocation(mPartAlloc, 1);
+        mScript.bindAllocation(mVertAlloc, 2);
+        mRS.contextBindRootScript(mScript);
+    }
+
+}
+
+
diff --git a/libs/rs/java/Fountain/src/com/android/fountain/FountainView.java b/libs/rs/java/Fountain/src/com/android/fountain/FountainView.java
new file mode 100644
index 0000000..be8b24e
--- /dev/null
+++ b/libs/rs/java/Fountain/src/com/android/fountain/FountainView.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.fountain;
+
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.concurrent.Semaphore;
+
+import android.renderscript.RSSurfaceView;
+import android.renderscript.RenderScript;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.os.Handler;
+import android.os.Message;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.Surface;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+
+public class FountainView extends RSSurfaceView {
+
+    public FountainView(Context context) {
+        super(context);
+
+        //setFocusable(true);
+    }
+
+    private RenderScript mRS;
+    private FountainRS mRender;
+
+    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
+        super.surfaceChanged(holder, format, w, h);
+
+        mRS = createRenderScript();
+        mRender = new FountainRS();
+        mRender.init(mRS, getResources(), w, h);
+    }
+
+
+    @Override
+    public boolean onTouchEvent(MotionEvent ev)
+    {
+        boolean ret = true;
+        int act = ev.getAction();
+        if (act == ev.ACTION_UP) {
+            ret = false;
+        }
+        mRender.newTouchPosition((int)ev.getX(), (int)ev.getY());
+        return ret;
+    }
+}
+
+
diff --git a/libs/rs/java/Rollo/Android.mk b/libs/rs/java/Rollo/Android.mk
new file mode 100644
index 0000000..5a4957c
--- /dev/null
+++ b/libs/rs/java/Rollo/Android.mk
@@ -0,0 +1,25 @@
+#
+# Copyright (C) 2008 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+#LOCAL_STATIC_JAVA_LIBRARIES := android.renderscript
+
+LOCAL_PACKAGE_NAME := Rollo
+
+include $(BUILD_PACKAGE)
diff --git a/libs/rs/java/Rollo/AndroidManifest.xml b/libs/rs/java/Rollo/AndroidManifest.xml
new file mode 100644
index 0000000..127a140
--- /dev/null
+++ b/libs/rs/java/Rollo/AndroidManifest.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.rollo">
+    <application android:label="Rollo">
+        <activity android:name="Rollo"
+                  android:theme="@android:style/Theme.Translucent">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/libs/rs/java/Rollo/res/raw/browser.png b/libs/rs/java/Rollo/res/raw/browser.png
new file mode 100644
index 0000000..513f0be
--- /dev/null
+++ b/libs/rs/java/Rollo/res/raw/browser.png
Binary files differ
diff --git a/libs/rs/java/Rollo/res/raw/market.png b/libs/rs/java/Rollo/res/raw/market.png
new file mode 100644
index 0000000..83b6910
--- /dev/null
+++ b/libs/rs/java/Rollo/res/raw/market.png
Binary files differ
diff --git a/libs/rs/java/Rollo/res/raw/photos.png b/libs/rs/java/Rollo/res/raw/photos.png
new file mode 100644
index 0000000..1ed8f1e
--- /dev/null
+++ b/libs/rs/java/Rollo/res/raw/photos.png
Binary files differ
diff --git a/libs/rs/java/Rollo/res/raw/rollo.c b/libs/rs/java/Rollo/res/raw/rollo.c
new file mode 100644
index 0000000..d338d0d
--- /dev/null
+++ b/libs/rs/java/Rollo/res/raw/rollo.c
@@ -0,0 +1,105 @@
+#pragma version(1)
+#pragma stateVertex(PV)
+#pragma stateFragment(PF)
+#pragma stateFragmentStore(PFS)
+
+// Scratch buffer layout
+#define SCRATCH_FADE 0
+#define SCRATCH_ZOOM 1
+#define SCRATCH_ROT 2
+
+//#define STATE_POS_X             0
+#define STATE_DONE              1
+//#define STATE_PRESSURE          2
+#define STATE_ZOOM              3
+//#define STATE_WARP              4
+#define STATE_ORIENTATION       5
+#define STATE_SELECTION         6
+#define STATE_FIRST_VISIBLE     7
+#define STATE_COUNT             8
+#define STATE_TOUCH             9
+
+float filter(float val, float target, float str)
+{
+    float delta = (target - val);
+    return val + delta * str;
+}
+
+int main(void* con, int ft, int launchID)
+{
+    int rowCount;
+    int row;
+    int col;
+    int imageID;
+    int done = loadI32(0, STATE_DONE);
+    int selectedID = loadI32(0, STATE_SELECTION);
+
+    float f = loadF(2, 0);
+
+    pfClearColor(0.0f, 0.0f, 0.0f, f);
+    if (done) {
+        if (f > 0.02f) {
+            //f = f - 0.02f;
+            //storeF(2, 0, f);
+        }
+    } else {
+        if (f < 0.8f) {
+            f = f + 0.02f;
+            storeF(2, 0, f);
+        }
+    }
+
+    float touchCut = 1.f;
+    if (loadI32(0, STATE_TOUCH)) {
+        touchCut = 5.f;
+    }
+
+
+    float targetZoom = ((float)loadI32(0, STATE_ZOOM)) / 1000.f;
+    float zoom = filter(loadF(2, SCRATCH_ZOOM), targetZoom, 0.15 * touchCut);
+    storeF(2, SCRATCH_ZOOM, zoom);
+
+    float targetRot = loadI32(0, STATE_FIRST_VISIBLE) / 180.0f * 3.14f;
+    float rot = filter(loadF(2, SCRATCH_ROT), targetRot, 0.1f * touchCut);
+    storeF(2, SCRATCH_ROT, rot);
+
+    float diam = 8.f;// + curve * 2.f;
+    float scale = 1.0f / zoom;
+
+    rot = rot * scale;
+    float rotStep = 20.0f / 180.0f * 3.14f * scale;
+    rowCount = 4;
+    int index = 0;
+    int iconCount = loadI32(0, STATE_COUNT);
+    while (iconCount) {
+        float tmpSin = sinf(rot);
+        float tmpCos = cosf(rot);
+
+        float tx1 = tmpSin * diam - (tmpCos * scale);
+        float tx2 = tx1 + (tmpCos * scale * 2.f);
+        float tz1 = tmpCos * diam + (tmpSin * scale);
+        float tz2 = tz1 - (tmpSin * scale * 2.f);
+
+        int y;
+        for (y = rowCount -1; (y >= 0) && iconCount; y--) {
+            float ty1 = ((y * 3.0f) - 4.5f) * scale;
+            float ty2 = ty1 + scale * 2.f;
+            bindTexture(NAMED_PF, 0, loadI32(1, y));
+            color(1.0f, 1.0f, 1.0f, 1.0f);
+            if (done && (index != selectedID)) {
+                color(0.4f, 0.4f, 0.4f, 1.0f);
+            }
+            drawQuad(tx1, ty1, tz1,
+                     tx2, ty1, tz2,
+                     tx2, ty2, tz2,
+                     tx1, ty2, tz1);
+            iconCount--;
+            index++;
+        }
+        rot = rot + rotStep;
+    }
+
+    return 0;
+}
+
+
diff --git a/libs/rs/java/Rollo/res/raw/rollo2.c b/libs/rs/java/Rollo/res/raw/rollo2.c
new file mode 100644
index 0000000..b04ea73
--- /dev/null
+++ b/libs/rs/java/Rollo/res/raw/rollo2.c
@@ -0,0 +1,67 @@
+#pragma version(1)
+#pragma stateVertex(PV)
+#pragma stateFragment(PF)
+#pragma stateFragmentStore(PFS)
+
+void drawLoop(int x, int y, int z, int rot)
+{
+    int ct;
+    int tx;
+    int ty;
+    int tmpSin;
+    int tmpCos;
+    int sz;
+
+    for (ct = 0; ct < 10; ct ++) {
+        tmpSin = sinx((ct * 36 + rot) * 0x10000);
+        tmpCos = cosx((ct * 36 + rot) * 0x10000);
+
+        ty = y + tmpCos * 4;
+        tx = x + tmpSin * 4;
+        pfBindTexture(NAMED_PF, 0, loadI32(1, ct & 3));
+
+        sz = 0xc000;
+        drawQuad(tx - sz, ty - sz, z,
+                 tx + sz, ty - sz, z,
+                 tx + sz, ty + sz, z,
+                 tx - sz, ty + sz, z);
+    }
+}
+
+int main(void* con, int ft, int launchID)
+{
+    int rowCount;
+    int x;
+    int y;
+    int row;
+    int col;
+    int imageID;
+    int tx1;
+    int ty1;
+    int tz1;
+    int tx2;
+    int ty2;
+    int tz2;
+    int tmpSin;
+    int tmpCos;
+    int iconCount;
+    int pressure;
+
+    int ringCount;
+
+
+
+    rotStep = 16 * 0x10000;
+    pressure = loadI32(0, 2);
+    rowCount = 4;
+
+    iconCount = loadI32(0, 1);
+    rot = (-20 + loadI32(0, 0)) * 0x10000;
+
+    for (ringCount = 0; ringCount < 5; ringCount++) {
+        drawLoop(0, 0, 0x90000 + (ringCount * 0x80000));
+    }
+
+    return 0;
+}
+
diff --git a/libs/rs/java/Rollo/res/raw/settings.png b/libs/rs/java/Rollo/res/raw/settings.png
new file mode 100644
index 0000000..dd2cd95
--- /dev/null
+++ b/libs/rs/java/Rollo/res/raw/settings.png
Binary files differ
diff --git a/libs/rs/java/Rollo/src/com/android/rollo/Rollo.java b/libs/rs/java/Rollo/src/com/android/rollo/Rollo.java
new file mode 100644
index 0000000..400d801
--- /dev/null
+++ b/libs/rs/java/Rollo/src/com/android/rollo/Rollo.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.rollo;
+
+import android.renderscript.RSSurfaceView;
+import android.renderscript.RenderScript;
+
+import android.app.Activity;
+import android.content.res.Configuration;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.provider.Settings.System;
+import android.util.Config;
+import android.util.Log;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.Window;
+import android.widget.Button;
+import android.widget.ListView;
+
+import java.lang.Runtime;
+
+public class Rollo extends Activity {
+    //EventListener mListener = new EventListener();
+
+    private static final String LOG_TAG = "libRS_jni";
+    private static final boolean DEBUG  = false;
+    private static final boolean LOG_ENABLED = DEBUG ? Config.LOGD : Config.LOGV;
+
+    private RolloView mView;
+
+    // get the current looper (from your Activity UI thread for instance
+
+
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        // Create our Preview view and set it as the content of our
+        // Activity
+        mView = new RolloView(this);
+        setContentView(mView);
+    }
+
+    @Override
+    protected void onResume() {
+        // Ideally a game should implement onResume() and onPause()
+        // to take appropriate action when the activity looses focus
+        super.onResume();
+        mView.onResume();
+    }
+
+    @Override
+    protected void onPause() {
+        // Ideally a game should implement onResume() and onPause()
+        // to take appropriate action when the activity looses focus
+        super.onPause();
+        mView.onPause();
+
+        Runtime.getRuntime().exit(0);
+    }
+
+
+    static void log(String message) {
+        if (LOG_ENABLED) {
+            Log.v(LOG_TAG, message);
+        }
+    }
+
+
+}
+
diff --git a/libs/rs/java/Rollo/src/com/android/rollo/RolloMesh.java b/libs/rs/java/Rollo/src/com/android/rollo/RolloMesh.java
new file mode 100644
index 0000000..d7252fb
--- /dev/null
+++ b/libs/rs/java/Rollo/src/com/android/rollo/RolloMesh.java
@@ -0,0 +1,90 @@
+ /*
+ * 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.
+ */
+
+
+package com.android.rollo;
+
+import java.io.Writer;
+import java.lang.Math;
+
+import android.renderscript.RenderScript;
+
+
+class RolloMesh {
+    static public final float mCardHeight = 1.2f;
+    static public final float mCardWidth = 1.8f;
+    static public final float mTabHeight = 0.2f;
+    static public final float mTabs = 3;
+    static public final float mTabGap = 0.1f;
+
+    static RenderScript.TriangleMesh createCard(RenderScript rs) {
+        RenderScript.Element vtx = rs.elementGetPredefined(
+            RenderScript.ElementPredefined.ST_XYZ_F32);
+        RenderScript.Element idx = rs.elementGetPredefined(
+            RenderScript.ElementPredefined.INDEX_16);
+
+        float w = mCardWidth / 2;
+        float h = mCardHeight;
+        float z = 0;
+
+        rs.triangleMeshBegin(vtx, idx);
+        rs.triangleMeshAddVertex_XYZ_ST(-w, 0, z,  0, 0);
+        rs.triangleMeshAddVertex_XYZ_ST(-w, h, z,  0, 1);
+        rs.triangleMeshAddVertex_XYZ_ST( w, h, z,  1, 1);
+        rs.triangleMeshAddVertex_XYZ_ST( w, 0, z,  1, 0);
+        rs.triangleMeshAddTriangle(0,1,2);
+        rs.triangleMeshAddTriangle(0,2,3);
+        return rs.triangleMeshCreate();
+    }
+
+    static RenderScript.TriangleMesh createTab(RenderScript rs) {
+        RenderScript.Element vtx = rs.elementGetPredefined(
+            RenderScript.ElementPredefined.ST_XYZ_F32);
+        RenderScript.Element idx = rs.elementGetPredefined(
+            RenderScript.ElementPredefined.INDEX_16);
+
+
+        float tabSlope = 0.1f;
+        float num = 0;
+
+        float w = (mCardWidth - ((mTabs - 1) * mTabGap)) / mTabs;
+        float w1 = -(mCardWidth / 2) + ((w + mTabGap) * num);
+        float w2 = w1 + (w * tabSlope);
+        float w3 = w1 + w - (w * tabSlope);
+        float w4 = w1 + w;
+        float h1 = mCardHeight;
+        float h2 = h1 + mTabHeight;
+        float z = 0;
+
+        float stScale = w / mTabHeight / 2;
+        float stScale2 = stScale * (tabSlope / w);
+
+
+        rs.triangleMeshBegin(vtx, idx);
+        rs.triangleMeshAddVertex_XYZ_ST(w1, h1, z,  -stScale, 0);
+        rs.triangleMeshAddVertex_XYZ_ST(w2, h2, z,  -stScale2, 1);
+        rs.triangleMeshAddVertex_XYZ_ST(w3, h2, z,   stScale2, 1);
+        rs.triangleMeshAddVertex_XYZ_ST(w4, h1, z,   stScale, 0);
+        rs.triangleMeshAddTriangle(0,1,2);
+        rs.triangleMeshAddTriangle(0,2,3);
+        return rs.triangleMeshCreate();
+    }
+
+
+
+}
+
+
diff --git a/libs/rs/java/Rollo/src/com/android/rollo/RolloRS.java b/libs/rs/java/Rollo/src/com/android/rollo/RolloRS.java
new file mode 100644
index 0000000..8f48335
--- /dev/null
+++ b/libs/rs/java/Rollo/src/com/android/rollo/RolloRS.java
@@ -0,0 +1,251 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.rollo;
+
+import java.io.Writer;
+
+import android.renderscript.RenderScript;
+import android.renderscript.ProgramVertexAlloc;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.os.Handler;
+import android.os.Message;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.Surface;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+
+public class RolloRS {
+    //public static final int STATE_SELECTED_ID = 0;
+    public static final int STATE_DONE = 1;
+    //public static final int STATE_PRESSURE = 2;
+    public static final int STATE_ZOOM = 3;
+    //public static final int STATE_WARP = 4;
+    public static final int STATE_ORIENTATION = 5;
+    public static final int STATE_SELECTION = 6;
+    public static final int STATE_FIRST_VISIBLE = 7;
+    public static final int STATE_COUNT = 8;
+    public static final int STATE_TOUCH = 9;
+
+
+    public RolloRS() {
+    }
+
+    public void init(RenderScript rs, Resources res, int width, int height) {
+        mRS = rs;
+        mRes = res;
+        initNamed();
+        initRS();
+    }
+
+    public void setPosition(float column) {
+        mAllocStateBuf[STATE_FIRST_VISIBLE] = (int)(column * (-20));
+        mAllocState.data(mAllocStateBuf);
+    }
+
+    public void setTouch(boolean touch) {
+        mAllocStateBuf[STATE_TOUCH] = touch ? 1 : 0;
+        mAllocState.data(mAllocStateBuf);
+    }
+
+    public void setZoom(float z) {
+        //Log.e("rs", "zoom " + Float.toString(z));
+
+        mAllocStateBuf[STATE_ZOOM] = (int)(z * 1000.f);
+        mAllocState.data(mAllocStateBuf);
+    }
+
+    public void setSelected(int index) {
+        Log.e("rs",  "setSelected " + Integer.toString(index));
+
+        mAllocStateBuf[STATE_SELECTION] = index;
+        mAllocStateBuf[STATE_DONE] = 1;
+        mAllocState.data(mAllocStateBuf);
+    }
+
+
+    private Resources mRes;
+    private RenderScript mRS;
+    private RenderScript.Script mScript;
+    private RenderScript.Sampler mSampler;
+    private RenderScript.ProgramFragmentStore mPFSBackground;
+    private RenderScript.ProgramFragment mPFBackground;
+    private RenderScript.ProgramFragment mPFImages;
+    private RenderScript.ProgramVertex mPV;
+    private ProgramVertexAlloc mPVAlloc;
+    private RenderScript.Allocation[] mIcons;
+    private RenderScript.Allocation mIconPlate;
+
+    private int[] mAllocStateBuf;
+    private RenderScript.Allocation mAllocState;
+
+    private int[] mAllocIconIDBuf;
+    private RenderScript.Allocation mAllocIconID;
+
+    private int[] mAllocScratchBuf;
+    private RenderScript.Allocation mAllocScratch;
+
+    private void initNamed() {
+        mRS.samplerBegin();
+        mRS.samplerSet(RenderScript.SamplerParam.FILTER_MIN,
+                       RenderScript.SamplerValue.LINEAR);//_MIP_LINEAR);
+        mRS.samplerSet(RenderScript.SamplerParam.FILTER_MAG,
+                       RenderScript.SamplerValue.LINEAR);
+        mRS.samplerSet(RenderScript.SamplerParam.WRAP_MODE_S,
+                       RenderScript.SamplerValue.CLAMP);
+        mRS.samplerSet(RenderScript.SamplerParam.WRAP_MODE_T,
+                       RenderScript.SamplerValue.CLAMP);
+        mSampler = mRS.samplerCreate();
+
+
+        mRS.programFragmentBegin(null, null);
+        mRS.programFragmentSetTexEnable(0, true);
+        mRS.programFragmentSetTexEnvMode(0, RenderScript.EnvMode.MODULATE);
+        mPFImages = mRS.programFragmentCreate();
+        mPFImages.setName("PF");
+        mPFImages.bindSampler(mSampler, 0);
+
+        mRS.programFragmentStoreBegin(null, null);
+        mRS.programFragmentStoreDepthFunc(RenderScript.DepthFunc.LESS);
+        mRS.programFragmentStoreDitherEnable(false);
+        mRS.programFragmentStoreDepthMask(false);
+        mRS.programFragmentStoreBlendFunc(RenderScript.BlendSrcFunc.ONE, 
+                                          RenderScript.BlendDstFunc.ONE);
+        mPFSBackground = mRS.programFragmentStoreCreate();
+        mPFSBackground.setName("PFS");
+
+        mPVAlloc = new ProgramVertexAlloc(mRS);
+        mRS.programVertexBegin(null, null);
+        mRS.programVertexSetTextureMatrixEnable(true);
+        mPV = mRS.programVertexCreate();
+        mPV.setName("PV");
+        mPV.bindAllocation(0, mPVAlloc.mAlloc);
+
+
+
+        mPVAlloc.setupProjectionNormalized(320, 480);
+        //mPVAlloc.setupOrthoNormalized(320, 480);
+        mRS.contextBindProgramVertex(mPV);
+
+        mAllocScratchBuf = new int[32];
+        for(int ct=0; ct < mAllocScratchBuf.length; ct++) {
+            mAllocScratchBuf[ct] = 0;
+        }
+        mAllocScratch = mRS.allocationCreatePredefSized(
+            RenderScript.ElementPredefined.USER_I32, mAllocScratchBuf.length);
+        mAllocScratch.data(mAllocScratchBuf);
+
+        Log.e("rs", "Done loading named");
+
+
+
+        {
+            mIcons = new RenderScript.Allocation[4];
+            mAllocIconIDBuf = new int[mIcons.length];
+            mAllocIconID = mRS.allocationCreatePredefSized(
+                RenderScript.ElementPredefined.USER_I32, mAllocIconIDBuf.length);
+
+            
+            Bitmap b;
+            BitmapFactory.Options opts = new BitmapFactory.Options();
+            opts.inScaled = false;
+
+            b = BitmapFactory.decodeResource(mRes, R.raw.browser, opts);
+            mIcons[0] = mRS.allocationCreateFromBitmap(b, RenderScript.ElementPredefined.RGB_565, true);
+
+            b = BitmapFactory.decodeResource(mRes, R.raw.market, opts);
+            mIcons[1] = mRS.allocationCreateFromBitmap(b, RenderScript.ElementPredefined.RGB_565, true);
+
+            b = BitmapFactory.decodeResource(mRes, R.raw.photos, opts);
+            mIcons[2] = mRS.allocationCreateFromBitmap(b, RenderScript.ElementPredefined.RGB_565, true);
+
+            b = BitmapFactory.decodeResource(mRes, R.raw.settings, opts);
+            mIcons[3] = mRS.allocationCreateFromBitmap(b, RenderScript.ElementPredefined.RGB_565, true);
+
+            for(int ct=0; ct < mIcons.length; ct++) {
+                mIcons[ct].uploadToTexture(0);
+                mAllocIconIDBuf[ct] = mIcons[ct].getID();
+            }
+            mAllocIconID.data(mAllocIconIDBuf);
+
+            RenderScript.Element e = mRS.elementGetPredefined(RenderScript.ElementPredefined.RGB_565);
+            mRS.typeBegin(e);
+            mRS.typeAdd(RenderScript.Dimension.X, 64);
+            mRS.typeAdd(RenderScript.Dimension.Y, 64);
+            RenderScript.Type t = mRS.typeCreate();
+            mIconPlate = mRS.allocationCreateTyped(t);
+            //t.destroy();
+            //e.destroy();
+
+            int tmp[] = new int[64 * 32];
+            for(int ct = 0; ct < (64*32); ct++) {
+                tmp[ct] = 7 | (13 << 5) | (7 << 11);
+                tmp[ct] = tmp[ct] | (tmp[ct] << 16);
+            }
+            for(int ct = 0; ct < 32; ct++) {
+                tmp[ct] = 0;
+                tmp[ct + (63*32)] = 0;
+            }
+            for(int ct = 0; ct < 64; ct++) {
+                tmp[ct * 32] = 0;
+                tmp[ct * 32 + 31] = 0;
+            }
+            mIconPlate.data(tmp);
+            Log.e("xx", "plate");
+            mIconPlate.uploadToTexture(0);
+            mIconPlate.setName("Plate");
+            mPFImages.bindTexture(mIconPlate, 0);
+        }
+
+    }
+
+
+
+    private void initRS() {
+        mRS.scriptCBegin();
+        mRS.scriptCSetClearColor(0.0f, 0.0f, 0.0f, 0.0f);
+        mRS.scriptCSetScript(mRes, R.raw.rollo);
+        //mRS.scriptCSetScript(mRes, R.raw.rollo2);
+        mRS.scriptCSetRoot(true);
+        //mRS.scriptCSetClearDepth(0);
+        mScript = mRS.scriptCCreate();
+
+        mAllocStateBuf = new int[] {0, 0, 0, 8, 0, 0, 0, 0, 38, 0, 0};
+        mAllocState = mRS.allocationCreatePredefSized(
+            RenderScript.ElementPredefined.USER_I32, mAllocStateBuf.length);
+        mScript.bindAllocation(mAllocState, 0);
+        mScript.bindAllocation(mAllocIconID, 1);
+        mScript.bindAllocation(mAllocScratch, 2);
+        setPosition(0);
+        setZoom(1);
+
+        //RenderScript.File f = mRS.fileOpen("/sdcard/test.a3d");
+
+        mRS.contextBindRootScript(mScript);
+    }
+}
+
+
+
diff --git a/libs/rs/java/Rollo/src/com/android/rollo/RolloView.java b/libs/rs/java/Rollo/src/com/android/rollo/RolloView.java
new file mode 100644
index 0000000..b5e02af
--- /dev/null
+++ b/libs/rs/java/Rollo/src/com/android/rollo/RolloView.java
@@ -0,0 +1,208 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.rollo;
+
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.concurrent.Semaphore;
+import java.lang.Float;
+
+import android.renderscript.RSSurfaceView;
+import android.renderscript.RenderScript;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.os.Handler;
+import android.os.Message;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.Surface;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+import android.graphics.PixelFormat;
+
+
+public class RolloView extends RSSurfaceView {
+    public RolloView(Context context) {
+        super(context);
+        setFocusable(true);
+        getHolder().setFormat(PixelFormat.TRANSLUCENT);
+    }
+
+    private RenderScript mRS;
+    private RolloRS mRender;
+
+    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
+        super.surfaceChanged(holder, format, w, h);
+
+        mRS = createRenderScript();
+        mRender = new RolloRS();
+        mRender.init(mRS, getResources(), w, h);
+    }
+
+    @Override
+    public boolean onKeyDown(int keyCode, KeyEvent event)
+    {
+        // break point at here
+        // this method doesn't work when 'extends View' include 'extends ScrollView'.
+        return super.onKeyDown(keyCode, event);
+    }
+
+    boolean mControlMode = false;
+    boolean mZoomMode = false;
+    boolean mFlingMode = false;
+    float mFlingX = 0;
+    float mFlingY = 0;
+    float mColumn = -1;
+    float mOldColumn;
+    float mZoom = 1;
+
+    int mIconCount = 38;
+    int mRows = 4;
+    int mColumns = (mIconCount + mRows - 1) / mRows;
+
+    float mMaxZoom = ((float)mColumns) / 3.f;
+
+
+    void setColumn(boolean clamp)
+    {
+        //Log.e("rs", " col = " + Float.toString(mColumn));
+        float c = mColumn;
+        if(c > (mColumns -2)) {
+            c = (mColumns -2);
+        }
+        if(c < 1) {
+            c = 1;
+        }
+        mRender.setPosition(c);
+        if(clamp) {
+            mColumn = c;
+        }
+    }
+
+    void computeSelection(float x, float y)
+    {
+        float col = mColumn + (x - 0.5f) * 3;
+        int iCol = (int)(col + 0.25f);
+
+        float row = (y / 0.8f) * mRows;
+        int iRow = (int)(row - 0.25f);
+
+        mRender.setSelected(iCol * mRows + iRow);
+    }
+
+    @Override
+    public boolean onTouchEvent(MotionEvent ev)
+    {
+        boolean ret = true;
+        int act = ev.getAction();
+        if (act == ev.ACTION_UP) {
+            ret = false;
+        }
+
+        float nx = ev.getX() / getWidth();
+        float ny = ev.getY() / getHeight();
+
+        mRender.setTouch(ret);
+
+        if((ny > 0.85f) || mControlMode) {
+            mFlingMode = false;
+
+            // Projector control
+            if((nx > 0.2f) && (nx < 0.8f) || mControlMode) {
+                if(act != ev.ACTION_UP) {
+                    float zoom = mMaxZoom;
+                    if(mControlMode) {
+                        if(!mZoomMode) {
+                            zoom = 1.f;
+                        }
+                        float dx = nx - mFlingX;
+
+                        if((ny < 0.9) && mZoomMode) {
+                            zoom = mMaxZoom - ((0.9f - ny) * 10.f);
+                            if(zoom < 1) {
+                                zoom = 1;
+                                mZoomMode = false;
+                            }
+                            mOldColumn = mColumn;
+                        }
+                        mColumn += dx * 4;// * zoom;
+                        if(zoom > 1.01f) {
+                            mColumn += (mZoom - zoom) * (nx - 0.5f) * 4 * zoom;
+                        }
+                    } else {
+                        mOldColumn = mColumn;
+                        mColumn = ((float)mColumns) / 2;
+                        mControlMode = true;
+                        mZoomMode = true;
+                    }
+                    mZoom = zoom;
+                    mFlingX = nx;
+                    mRender.setZoom(zoom);
+                } else {
+                    if(mControlMode && (mZoom < 1.01f)) {
+                        computeSelection(nx, ny);
+                    }
+                    mControlMode = false;
+                    mColumn = mOldColumn;
+                    mRender.setZoom(1.f);
+                }
+            } else {
+                // Do something with corners here....
+            }
+            setColumn(true);
+
+        } else {
+            // icon control
+            if(act != ev.ACTION_UP) {
+                if(mFlingMode) {
+                    mColumn += (mFlingX - nx) * 4;
+                    setColumn(true);
+                }
+                mFlingMode = true;
+                mFlingX = nx;
+                mFlingY = ny;
+            } else {
+                mFlingMode = false;
+            }
+        }
+
+
+        return ret;
+    }
+
+    @Override
+    public boolean onTrackballEvent(MotionEvent ev)
+    {
+        float x = ev.getX();
+        float y = ev.getY();
+        //Float tx = new Float(x);
+        //Float ty = new Float(y);
+        //Log.e("rs", "tbe " + tx.toString() + ", " + ty.toString());
+
+
+        return true;
+    }
+
+}
+
+
diff --git a/libs/rs/rs.spec b/libs/rs/rs.spec
new file mode 100644
index 0000000..2f99808
--- /dev/null
+++ b/libs/rs/rs.spec
@@ -0,0 +1,449 @@
+
+
+ContextBindRootScript {
+	param RsScript sampler
+	}
+
+ContextBindProgramFragmentStore {
+	param RsProgramFragmentStore pgm
+	}
+
+ContextBindProgramFragment {
+	param RsProgramFragment pgm
+	}
+
+ContextBindProgramVertex {
+	param RsProgramVertex pgm
+	}
+
+AssignName {
+	param void *obj
+	param const char *name
+	param size_t len
+	}
+
+ElementBegin {
+}
+
+ElementAddPredefined {
+	param RsElementPredefined predef
+	}
+
+ElementAdd {
+	param RsDataKind dataKind
+	param RsDataType dataType
+	param bool isNormalized
+	param size_t bits
+	}
+
+ElementCreate {
+	ret RsElement
+	}
+
+ElementGetPredefined {
+	param RsElementPredefined predef
+	ret RsElement
+	}
+
+ElementDestroy {
+	param RsElement ve
+	}
+
+TypeBegin {
+	param RsElement type
+	}
+
+TypeAdd {
+	param RsDimension dim
+	param size_t value
+	}
+
+TypeCreate {
+	ret RsType
+	}
+
+TypeDestroy {
+	param RsType p
+	}
+
+AllocationCreateTyped {
+	param RsType type
+	ret RsAllocation
+	}
+
+AllocationCreatePredefSized {
+	param RsElementPredefined predef
+	param size_t count
+	ret RsAllocation
+	}
+
+AllocationCreateSized {
+	param RsElement e
+	param size_t count
+	ret RsAllocation
+	}
+
+AllocationCreateFromFile {
+	param const char *file
+	param bool genMips
+	ret RsAllocation
+	}
+
+AllocationCreateFromBitmap {
+	param uint32_t width
+	param uint32_t height
+	param RsElementPredefined dstFmt
+	param RsElementPredefined srcFmt
+	param bool genMips
+	param const void * data
+	ret RsAllocation
+	}
+
+
+AllocationUploadToTexture {
+	param RsAllocation alloc
+	param uint32_t baseMipLevel
+	}
+
+AllocationUploadToBufferObject {
+	param RsAllocation alloc
+	}
+
+AllocationDestroy {
+	param RsAllocation alloc
+	}
+
+
+AllocationData {
+	param RsAllocation va
+	param const void * data
+	} 
+
+Allocation1DSubData {
+	param RsAllocation va
+	param uint32_t xoff
+	param uint32_t count
+	param const void *data
+	} 
+
+Allocation2DSubData {
+	param RsAllocation va
+	param uint32_t xoff
+	param uint32_t yoff
+	param uint32_t w
+	param uint32_t h
+	param const void *data
+	}
+
+
+Adapter1DCreate {
+	ret RsAdapter1D
+	}
+
+Adapter1DBindAllocation {
+	param RsAdapter1D adapt
+	param RsAllocation alloc
+	}
+
+Adapter1DDestroy {
+	param RsAdapter1D adapter
+	}
+
+Adapter1DSetConstraint {
+	param RsAdapter1D adapter
+	param RsDimension dim
+	param uint32_t value
+	}
+
+Adapter1DData {
+	param RsAdapter1D adapter
+	param const void * data
+	} 
+
+Adapter1DSubData {
+	param RsAdapter1D adapter
+	param uint32_t xoff
+	param uint32_t count
+	param const void *data
+	} 
+
+Adapter2DCreate {
+	ret RsAdapter2D
+	}
+
+Adapter2DBindAllocation {
+	param RsAdapter2D adapt
+	param RsAllocation alloc
+	}
+
+Adapter2DDestroy {
+	param RsAdapter2D adapter
+	}
+
+Adapter2DSetConstraint {
+	param RsAdapter2D adapter
+	param RsDimension dim
+	param uint32_t value
+	}
+
+Adapter2DData {
+	param RsAdapter2D adapter
+	param const void *data
+	} 
+
+Adapter2DSubData {
+	param RsAdapter2D adapter
+	param uint32_t xoff
+	param uint32_t yoff
+	param uint32_t w
+	param uint32_t h
+	param const void *data
+	}
+
+SamplerBegin {
+	}
+
+SamplerSet {
+	param RsSamplerParam p
+	param RsSamplerValue value
+	}
+
+SamplerCreate {
+	ret RsSampler
+	}
+
+SamplerDestroy {
+	param RsSampler s
+	}
+
+TriangleMeshBegin {
+	param RsElement vertex
+	param RsElement index
+	}
+
+TriangleMeshAddVertex {
+	param const void *vtx
+	}
+
+TriangleMeshAddTriangle {
+	param uint32_t idx1
+	param uint32_t idx2
+	param uint32_t idx3
+	}
+
+TriangleMeshCreate {
+	ret RsTriangleMesh
+	}
+
+TriangleMeshDestroy {
+	param RsTriangleMesh mesh
+	}
+
+TriangleMeshRender {
+	param RsTriangleMesh vtm
+	}
+
+TriangleMeshRenderRange {
+	param RsTriangleMesh vtm
+	param uint32_t start
+	param uint32_t count
+	}
+
+ScriptDestroy {
+	param RsScript script
+	}
+
+ScriptBindAllocation {
+	param RsScript vtm
+	param RsAllocation va
+	param uint32_t slot
+	}
+
+
+ScriptCBegin {
+	}
+
+ScriptCSetClearColor {
+	param float r
+	param float g
+	param float b
+	param float a
+	}
+
+ScriptCSetClearDepth {
+	param float depth
+	}
+
+ScriptCSetClearStencil {
+	param uint32_t stencil
+	}
+
+ScriptCAddType {
+	param RsType type
+	}
+
+ScriptCSetRoot {
+	param bool isRoot
+	}
+
+ScriptCSetScript {
+	param void * codePtr
+	}
+
+ScriptCSetText {
+	param const char * text
+	param uint32_t length
+	}
+
+ScriptCCreate {
+	ret RsScript
+	}
+
+
+ProgramFragmentStoreBegin {
+	param RsElement in
+	param RsElement out
+	}
+
+ProgramFragmentStoreColorMask {
+	param bool r
+	param bool g
+	param bool b
+	param bool a
+	}
+
+ProgramFragmentStoreBlendFunc {
+	param RsBlendSrcFunc srcFunc
+	param RsBlendDstFunc destFunc
+	}
+
+ProgramFragmentStoreDepthMask {
+	param bool enable
+}
+
+ProgramFragmentStoreDither {
+	param bool enable
+}
+
+ProgramFragmentStoreDepthFunc {
+	param RsDepthFunc func
+}
+
+ProgramFragmentStoreCreate {
+	ret RsProgramFragmentStore
+	}
+
+ProgramFragmentStoreDestroy {
+	param RsProgramFragmentStore pfs
+	}
+
+
+ProgramFragmentBegin {
+	param RsElement in
+	param RsElement out
+	}
+
+ProgramFragmentBindTexture {
+	param RsProgramFragment pf
+	param uint32_t slot
+	param RsAllocation a
+	}
+
+ProgramFragmentBindSampler {
+	param RsProgramFragment pf
+	param uint32_t slot
+	param RsSampler s
+	}
+
+ProgramFragmentSetType {
+	param uint32_t slot
+	param RsType t
+	}
+
+ProgramFragmentSetEnvMode {
+	param uint32_t slot
+	param RsTexEnvMode env
+	}
+
+ProgramFragmentSetTexEnable {
+	param uint32_t slot
+	param bool enable
+	}
+
+ProgramFragmentCreate {
+	ret RsProgramFragment
+	}
+
+ProgramFragmentDestroy {
+	param RsProgramFragment pf
+	}
+
+
+ProgramVertexBegin {
+	param RsElement in
+	param RsElement out
+	}
+
+ProgramVertexCreate {
+	ret RsProgramVertex
+	}
+
+ProgramVertexBindAllocation {
+	param RsProgramVertex vpgm
+	param uint32_t slot
+	param RsAllocation constants
+	}
+
+ProgramVertexSetType {
+	param uint32_t slot
+	param RsType constants
+	}
+
+ProgramVertexSetTextureMatrixEnable {
+	param bool enable
+	}
+
+ProgramVertexAddLight {
+	param RsLight light
+	}
+
+LightBegin {
+	}
+
+LightSetLocal {
+	param bool isLocal
+	}
+
+LightSetMonochromatic {
+	param bool isMono
+	}
+
+LightCreate {
+	ret RsLight light
+	}
+
+LightDestroy {
+	param RsLight light
+	}
+
+LightSetPosition {
+	param RsLight light
+	param float x
+	param float y
+	param float z
+	}
+
+LightSetColor {
+	param RsLight light
+	param float r
+	param float g
+	param float b
+	}
+
+FileOpen {
+	ret RsFile
+	param const char *name
+	param size_t len
+	}
+
+
diff --git a/libs/rs/rsAdapter.cpp b/libs/rs/rsAdapter.cpp
new file mode 100644
index 0000000..7ac2aed
--- /dev/null
+++ b/libs/rs/rsAdapter.cpp
@@ -0,0 +1,245 @@
+
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+
+Adapter1D::Adapter1D()
+{
+    reset();
+}
+
+Adapter1D::Adapter1D(Allocation *a)
+{
+    reset();
+    setAllocation(a);
+}
+
+void Adapter1D::reset()
+{
+    mY = 0;
+    mZ = 0;
+    mLOD = 0;
+    mFace = 0;
+}
+
+void * Adapter1D::getElement(uint32_t x)
+{
+    rsAssert(mAllocation.get());
+    rsAssert(mAllocation->getPtr());
+    rsAssert(mAllocation->getType());
+    uint8_t * ptr = static_cast<uint8_t *>(mAllocation->getPtr());
+    ptr += mAllocation->getType()->getLODOffset(mLOD, x, mY);
+    return ptr;
+}
+
+void Adapter1D::subData(uint32_t xoff, uint32_t count, const void *data)
+{
+    if (mAllocation.get() && mAllocation.get()->getType()) {
+        void *ptr = getElement(xoff);
+        count *= mAllocation.get()->getType()->getElementSizeBytes();
+        memcpy(ptr, data, count);
+    }
+}
+
+void Adapter1D::data(const void *data)
+{
+    memcpy(getElement(0), 
+           data, 
+           mAllocation.get()->getType()->getSizeBytes());
+}
+
+namespace android {
+namespace renderscript {
+
+RsAdapter1D rsi_Adapter1DCreate(Context *rsc)
+{
+    return new Adapter1D();
+}
+
+void rsi_Adapter1DDestroy(Context *rsc, RsAdapter1D va)
+{
+    Adapter1D * a = static_cast<Adapter1D *>(va);
+    a->decRef();
+}
+
+void rsi_Adapter1DBindAllocation(Context *rsc, RsAdapter1D va, RsAllocation valloc)
+{
+    Adapter1D * a = static_cast<Adapter1D *>(va);
+    Allocation * alloc = static_cast<Allocation *>(valloc);
+    a->setAllocation(alloc);
+}
+
+void rsi_Adapter1DSetConstraint(Context *rsc, RsAdapter1D va, RsDimension dim, uint32_t value)
+{
+    Adapter1D * a = static_cast<Adapter1D *>(va);
+    switch(dim) {
+    case RS_DIMENSION_X:
+        rsAssert(!"Cannot contrain X in an 1D adapter");
+        return;
+    case RS_DIMENSION_Y:
+        a->setY(value);
+        break;
+    case RS_DIMENSION_Z:
+        a->setZ(value);
+        break;
+    case RS_DIMENSION_LOD:
+        a->setLOD(value);
+        break;
+    case RS_DIMENSION_FACE:
+        a->setFace(value);
+        break;
+    default:
+        rsAssert(!"Unimplemented constraint");
+        return;
+    }
+}
+
+void rsi_Adapter1DSubData(Context *rsc, RsAdapter1D va, uint32_t xoff, uint32_t count, const void *data)
+{
+    Adapter1D * a = static_cast<Adapter1D *>(va);
+    a->subData(xoff, count, data);
+}
+
+void rsi_Adapter1DData(Context *rsc, RsAdapter1D va, const void *data)
+{
+    Adapter1D * a = static_cast<Adapter1D *>(va);
+    a->data(data);
+}
+
+}
+}
+
+//////////////////////////
+
+Adapter2D::Adapter2D()
+{
+    reset();
+}
+
+Adapter2D::Adapter2D(Allocation *a)
+{
+    reset();
+    setAllocation(a);
+}
+
+void Adapter2D::reset()
+{
+    mZ = 0;
+    mLOD = 0;
+    mFace = 0;
+}
+
+void * Adapter2D::getElement(uint32_t x, uint32_t y) const
+{
+    rsAssert(mAllocation.get());
+    rsAssert(mAllocation->getPtr());
+    rsAssert(mAllocation->getType());
+    uint8_t * ptr = static_cast<uint8_t *>(mAllocation->getPtr());
+    ptr += mAllocation->getType()->getLODOffset(mLOD, x, y);
+    return ptr;
+}
+
+void Adapter2D::subData(uint32_t xoff, uint32_t yoff, uint32_t w, uint32_t h, const void *data)
+{
+    rsAssert(mAllocation.get());
+    rsAssert(mAllocation->getPtr());
+    rsAssert(mAllocation->getType());
+
+    uint32_t eSize = mAllocation.get()->getType()->getElementSizeBytes();
+    uint32_t lineSize = eSize * w;
+    uint32_t destW = getDimX();
+
+    const uint8_t *src = static_cast<const uint8_t *>(data);
+    for (uint32_t line=yoff; line < (yoff+h); line++) {
+        memcpy(getElement(xoff, line), src, lineSize);
+        src += lineSize;
+    }
+}
+
+void Adapter2D::data(const void *data)
+{
+    memcpy(getElement(0,0), 
+           data, 
+           mAllocation.get()->getType()->getSizeBytes());
+}
+
+
+
+namespace android {
+namespace renderscript {
+
+RsAdapter2D rsi_Adapter2DCreate(Context *rsc)
+{
+    return new Adapter2D();
+}
+
+void rsi_Adapter2DDestroy(Context *rsc, RsAdapter2D va)
+{
+    Adapter2D * a = static_cast<Adapter2D *>(va);
+    a->decRef();
+}
+
+void rsi_Adapter2DBindAllocation(Context *rsc, RsAdapter2D va, RsAllocation valloc)
+{
+    Adapter2D * a = static_cast<Adapter2D *>(va);
+    Allocation * alloc = static_cast<Allocation *>(valloc);
+    a->setAllocation(alloc);
+}
+
+void rsi_Adapter2DSetConstraint(Context *rsc, RsAdapter2D va, RsDimension dim, uint32_t value)
+{
+    Adapter2D * a = static_cast<Adapter2D *>(va);
+    switch(dim) {
+    case RS_DIMENSION_X:
+        rsAssert(!"Cannot contrain X in an 2D adapter");
+        return;
+    case RS_DIMENSION_Y:
+        rsAssert(!"Cannot contrain Y in an 2D adapter");
+        break;
+    case RS_DIMENSION_Z:
+        a->setZ(value);
+        break;
+    case RS_DIMENSION_LOD:
+        a->setLOD(value);
+        break;
+    case RS_DIMENSION_FACE:
+        a->setFace(value);
+        break;
+    default:
+        rsAssert(!"Unimplemented constraint");
+        return;
+    }
+}
+
+void rsi_Adapter2DData(Context *rsc, RsAdapter2D va, const void *data)
+{
+    Adapter2D * a = static_cast<Adapter2D *>(va);
+    a->data(data);
+}
+
+void rsi_Adapter2DSubData(Context *rsc, RsAdapter2D va, uint32_t xoff, uint32_t yoff, uint32_t w, uint32_t h, const void *data)
+{
+    Adapter2D * a = static_cast<Adapter2D *>(va);
+    a->subData(xoff, yoff, w, h, data);
+}
+
+}
+}
diff --git a/libs/rs/rsAdapter.h b/libs/rs/rsAdapter.h
new file mode 100644
index 0000000..865535e
--- /dev/null
+++ b/libs/rs/rsAdapter.h
@@ -0,0 +1,96 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_ADAPTER_H
+#define ANDROID_RS_ADAPTER_H
+
+#include "rsAllocation.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+    
+class Adapter1D : public ObjectBase
+{
+
+public:
+    // By policy this allocation will hold a pointer to the type
+    // but will not destroy it on destruction.
+    Adapter1D();
+    Adapter1D(Allocation *);
+    void reset();
+    void * getElement(uint32_t x);
+
+    void setAllocation(Allocation *a) {mAllocation.set(a);}
+
+    uint32_t getDimX() const {return mAllocation->getType()->getLODDimX(mLOD);}
+
+    const Type * getBaseType() const {return mAllocation->getType();}
+
+    inline void setY(uint32_t y) {mY = y;}
+    inline void setZ(uint32_t z) {mZ = z;}
+    inline void setLOD(uint32_t lod) {mLOD = lod;}
+    inline void setFace(uint32_t face) {mFace = face;}
+    //void setArray(uint32_t num, uint32_t value);
+
+    void subData(uint32_t xoff, uint32_t count, const void *data);
+    void data(const void *data);
+
+protected:
+    ObjectBaseRef<Allocation> mAllocation;
+    uint32_t mY;
+    uint32_t mZ;
+    uint32_t mLOD;
+    uint32_t mFace;
+};
+
+class Adapter2D : public ObjectBase
+{
+
+public:
+    // By policy this allocation will hold a pointer to the type
+    // but will not destroy it on destruction.
+    Adapter2D();
+    Adapter2D(Allocation *);
+    void reset();
+    void * getElement(uint32_t x, uint32_t y) const;
+
+    uint32_t getDimX() const {return mAllocation->getType()->getLODDimX(mLOD);}
+    uint32_t getDimY() const {return mAllocation->getType()->getLODDimY(mLOD);}
+    const Type * getBaseType() const {return mAllocation->getType();}
+
+    void setAllocation(Allocation *a) {mAllocation.set(a);}
+    inline void setZ(uint32_t z) {mZ = z;}
+    inline void setLOD(uint32_t lod) {mLOD = lod;}
+    inline void setFace(uint32_t face) {mFace = face;}
+    //void setArray(uint32_t num, uint32_t value);
+
+    void data(const void *data); 
+    void subData(uint32_t xoff, uint32_t yoff, uint32_t w, uint32_t h, const void *data); 
+
+protected:
+    ObjectBaseRef<Allocation> mAllocation;
+    uint32_t mZ;
+    uint32_t mLOD;
+    uint32_t mFace;
+};
+
+
+}
+}
+#endif
+
diff --git a/libs/rs/rsAllocation.cpp b/libs/rs/rsAllocation.cpp
new file mode 100644
index 0000000..c143307
--- /dev/null
+++ b/libs/rs/rsAllocation.cpp
@@ -0,0 +1,477 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+using namespace android;
+using namespace android::renderscript;
+
+Allocation::Allocation(const Type *type)
+{
+    mPtr = NULL;
+
+    mCpuWrite = false;
+    mCpuRead = false;
+    mGpuWrite = false;
+    mGpuRead = false;
+
+    mReadWriteRatio = 0;
+    mUpdateSize = 0;
+
+    mIsTexture = false;
+    mTextureID = 0;
+
+    mIsVertexBuffer = false;
+    mBufferID = 0;
+
+    mType.set(type);
+    mPtr = malloc(mType->getSizeBytes());
+    if (!mPtr) {
+        LOGE("Allocation::Allocation, alloc failure");
+    }
+
+}
+
+Allocation::~Allocation()
+{
+}
+
+void Allocation::setCpuWritable(bool)
+{
+}
+
+void Allocation::setGpuWritable(bool)
+{
+}
+
+void Allocation::setCpuReadable(bool)
+{
+}
+
+void Allocation::setGpuReadable(bool)
+{
+}
+
+bool Allocation::fixAllocation()
+{
+    return false;
+}
+
+void Allocation::uploadToTexture(uint32_t lodOffset)
+{
+    //rsAssert(!mTextureId);
+    rsAssert(lodOffset < mType->getLODCount());
+
+    GLenum type = mType->getElement()->getGLType();
+    GLenum format = mType->getElement()->getGLFormat();
+
+    if (!type || !format) {
+        return;
+    }
+
+    if (!mTextureID) {
+        glGenTextures(1, &mTextureID);
+    }
+    glBindTexture(GL_TEXTURE_2D, mTextureID);
+
+    Adapter2D adapt(this);
+    for(uint32_t lod = 0; (lod + lodOffset) < mType->getLODCount(); lod++) {
+        adapt.setLOD(lod+lodOffset);
+
+        uint16_t * ptr = static_cast<uint16_t *>(adapt.getElement(0,0));
+        glTexImage2D(GL_TEXTURE_2D, lod, format,
+                     adapt.getDimX(), adapt.getDimY(),
+                     0, format, type, ptr);
+    }
+}
+
+void Allocation::uploadToBufferObject()
+{
+    rsAssert(!mType->getDimY());
+    rsAssert(!mType->getDimZ());
+
+    if (!mBufferID) {
+        glGenBuffers(1, &mBufferID);
+    }
+    glBindBuffer(GL_ARRAY_BUFFER, mBufferID);
+    glBufferData(GL_ARRAY_BUFFER, mType->getSizeBytes(), getPtr(), GL_DYNAMIC_DRAW);
+    glBindBuffer(GL_ARRAY_BUFFER, 0);
+}
+
+void Allocation::data(const void *data)
+{
+    memcpy(mPtr, data, mType->getSizeBytes());
+}
+
+void Allocation::subData(uint32_t xoff, uint32_t count, const void *data)
+{
+    uint32_t eSize = mType->getElementSizeBytes();
+    uint8_t * ptr = static_cast<uint8_t *>(mPtr);
+    ptr += eSize * xoff;
+    memcpy(ptr, data, count * eSize);
+}
+
+void Allocation::subData(uint32_t xoff, uint32_t yoff,
+             uint32_t w, uint32_t h, const void *data)
+{
+    uint32_t eSize = mType->getElementSizeBytes();
+    uint32_t lineSize = eSize * w;
+    uint32_t destW = mType->getDimX();
+
+    const uint8_t *src = static_cast<const uint8_t *>(data);
+    uint8_t *dst = static_cast<uint8_t *>(mPtr);
+    dst += eSize * (xoff + yoff * destW);
+    for (uint32_t line=yoff; line < (yoff+h); line++) {
+        uint8_t * ptr = static_cast<uint8_t *>(mPtr);
+        memcpy(dst, src, lineSize);
+        src += lineSize;
+        dst += destW * eSize;
+    }
+}
+
+void Allocation::subData(uint32_t xoff, uint32_t yoff, uint32_t zoff,
+             uint32_t w, uint32_t h, uint32_t d, const void *data)
+{
+}
+
+
+
+/////////////////
+//
+
+
+namespace android {
+namespace renderscript {
+
+RsAllocation rsi_AllocationCreateTyped(Context *rsc, RsType vtype)
+{
+    const Type * type = static_cast<const Type *>(vtype);
+
+    Allocation * alloc = new Allocation(type);
+    alloc->incRef();
+    return alloc;
+}
+
+RsAllocation rsi_AllocationCreatePredefSized(Context *rsc, RsElementPredefined t, size_t count)
+{
+    RsElement e = rsi_ElementGetPredefined(rsc, t);
+    return rsi_AllocationCreateSized(rsc, e, count);
+}
+
+RsAllocation rsi_AllocationCreateSized(Context *rsc, RsElement e, size_t count)
+{
+    Type * type = new Type();
+    type->setDimX(count);
+    type->setElement(static_cast<Element *>(e));
+    type->compute();
+    return rsi_AllocationCreateTyped(rsc, type);
+}
+
+void rsi_AllocationUploadToTexture(Context *rsc, RsAllocation va, uint32_t baseMipLevel)
+{
+    Allocation *alloc = static_cast<Allocation *>(va);
+    alloc->uploadToTexture(baseMipLevel);
+}
+
+void rsi_AllocationUploadToBufferObject(Context *rsc, RsAllocation va)
+{
+    Allocation *alloc = static_cast<Allocation *>(va);
+    alloc->uploadToBufferObject();
+}
+
+void rsi_AllocationDestroy(Context *rsc, RsAllocation)
+{
+}
+
+static void mip565(const Adapter2D &out, const Adapter2D &in)
+{
+    uint32_t w = out.getDimX();
+    uint32_t h = out.getDimY();
+
+    for (uint32_t y=0; y < w; y++) {
+        uint16_t *oPtr = static_cast<uint16_t *>(out.getElement(0, y));
+        const uint16_t *i1 = static_cast<uint16_t *>(in.getElement(0, y*2));
+        const uint16_t *i2 = static_cast<uint16_t *>(in.getElement(0, y*2+1));
+
+        for (uint32_t x=0; x < h; x++) {
+            *oPtr = rsBoxFilter565(i1[0], i1[1], i2[0], i2[1]);
+            oPtr ++;
+            i1 += 2;
+            i2 += 2;
+        }
+    }
+}
+
+static void mip8888(const Adapter2D &out, const Adapter2D &in)
+{
+    uint32_t w = out.getDimX();
+    uint32_t h = out.getDimY();
+
+    for (uint32_t y=0; y < w; y++) {
+        uint32_t *oPtr = static_cast<uint32_t *>(out.getElement(0, y));
+        const uint32_t *i1 = static_cast<uint32_t *>(in.getElement(0, y*2));
+        const uint32_t *i2 = static_cast<uint32_t *>(in.getElement(0, y*2+1));
+
+        for (uint32_t x=0; x < h; x++) {
+            *oPtr = rsBoxFilter8888(i1[0], i1[1], i2[0], i2[1]);
+            oPtr ++;
+            i1 += 2;
+            i2 += 2;
+        }
+    }
+
+}
+
+
+typedef void (*ElementConverter_t)(void *dst, const void *src, uint32_t count);
+
+static void elementConverter_cpy_16(void *dst, const void *src, uint32_t count)
+{
+    memcpy(dst, src, count * 2);
+}
+static void elementConverter_cpy_8(void *dst, const void *src, uint32_t count)
+{
+    memcpy(dst, src, count);
+}
+static void elementConverter_cpy_32(void *dst, const void *src, uint32_t count)
+{
+    memcpy(dst, src, count * 4);
+}
+
+
+static void elementConverter_888_to_565(void *dst, const void *src, uint32_t count)
+{
+    uint16_t *d = static_cast<uint16_t *>(dst);
+    const uint8_t *s = static_cast<const uint8_t *>(src);
+
+    while(count--) {
+        *d = rs888to565(s[0], s[1], s[2]);
+        d++;
+        s+= 3;
+    }
+}
+
+static void elementConverter_8888_to_565(void *dst, const void *src, uint32_t count)
+{
+    uint16_t *d = static_cast<uint16_t *>(dst);
+    const uint8_t *s = static_cast<const uint8_t *>(src);
+
+    while(count--) {
+        *d = rs888to565(s[0], s[1], s[2]);
+        d++;
+        s+= 4;
+    }
+}
+
+static ElementConverter_t pickConverter(RsElementPredefined dstFmt, RsElementPredefined srcFmt)
+{
+    if ((dstFmt == RS_ELEMENT_RGB_565) &&
+        (srcFmt == RS_ELEMENT_RGB_565)) {
+        return elementConverter_cpy_16;
+    }
+
+    if ((dstFmt == RS_ELEMENT_RGB_565) &&
+        (srcFmt == RS_ELEMENT_RGB_888)) {
+        return elementConverter_888_to_565;
+    }
+
+    if ((dstFmt == RS_ELEMENT_RGB_565) &&
+        (srcFmt == RS_ELEMENT_RGBA_8888)) {
+        return elementConverter_8888_to_565;
+    }
+
+    if ((dstFmt == RS_ELEMENT_RGBA_8888) &&
+        (srcFmt == RS_ELEMENT_RGBA_8888)) {
+        return elementConverter_cpy_32;
+    }
+
+    LOGE("pickConverter, unsuported combo");
+    return 0;
+}
+
+
+RsAllocation rsi_AllocationCreateFromBitmap(Context *rsc, uint32_t w, uint32_t h, RsElementPredefined dstFmt, RsElementPredefined srcFmt,  bool genMips, const void *data)
+{
+    rsi_TypeBegin(rsc, rsi_ElementGetPredefined(rsc, RS_ELEMENT_RGB_565));
+    rsi_TypeAdd(rsc, RS_DIMENSION_X, w);
+    rsi_TypeAdd(rsc, RS_DIMENSION_Y, h);
+    if (genMips) {
+        rsi_TypeAdd(rsc, RS_DIMENSION_LOD, 1);
+    }
+    RsType type = rsi_TypeCreate(rsc);
+
+    RsAllocation vTexAlloc = rsi_AllocationCreateTyped(rsc, type);
+    Allocation *texAlloc = static_cast<Allocation *>(vTexAlloc);
+    if (texAlloc == NULL) {
+        LOGE("Memory allocation failure");
+        return NULL;
+    }
+    texAlloc->incRef();
+
+    ElementConverter_t cvt = pickConverter(dstFmt, srcFmt);
+    cvt(texAlloc->getPtr(), data, w * h);
+
+    if (genMips) {
+        Adapter2D adapt(texAlloc);
+        Adapter2D adapt2(texAlloc);
+        for(uint32_t lod=0; lod < (texAlloc->getType()->getLODCount() -1); lod++) {
+            adapt.setLOD(lod);
+            adapt2.setLOD(lod + 1);
+            mip565(adapt2, adapt);
+        }
+    }
+
+    return texAlloc;
+}
+
+RsAllocation rsi_AllocationCreateFromFile(Context *rsc, const char *file, bool genMips)
+{
+    bool use32bpp = false;
+
+    typedef struct _Win3xBitmapHeader
+    {
+       uint16_t type;
+       uint32_t totalSize;
+       uint32_t reserved;
+       uint32_t offset;
+       int32_t hdrSize;            /* Size of this header in bytes */
+       int32_t width;           /* Image width in pixels */
+       int32_t height;          /* Image height in pixels */
+       int16_t planes;          /* Number of color planes */
+       int16_t bpp;             /* Number of bits per pixel */
+       /* Fields added for Windows 3.x follow this line */
+       int32_t compression;     /* Compression methods used */
+       int32_t sizeOfBitmap;    /* Size of bitmap in bytes */
+       int32_t horzResolution;  /* Horizontal resolution in pixels per meter */
+       int32_t vertResolution;  /* Vertical resolution in pixels per meter */
+       int32_t colorsUsed;      /* Number of colors in the image */
+       int32_t colorsImportant; /* Minimum number of important colors */
+    } __attribute__((__packed__)) WIN3XBITMAPHEADER;
+
+    _Win3xBitmapHeader hdr;
+
+    FILE *f = fopen(file, "rb");
+    if (f == NULL) {
+        LOGE("rsAllocationCreateFromBitmap failed to open file %s", file);
+        return NULL;
+    }
+    memset(&hdr, 0, sizeof(hdr));
+    fread(&hdr, sizeof(hdr), 1, f);
+
+    if (hdr.bpp != 24) {
+        LOGE("Unsuported BMP type");
+        fclose(f);
+        return NULL;
+    }
+
+    int32_t texWidth = rsHigherPow2(hdr.width);
+    int32_t texHeight = rsHigherPow2(hdr.height);
+
+    if (use32bpp) {
+        rsi_TypeBegin(rsc, rsi_ElementGetPredefined(rsc, RS_ELEMENT_RGBA_8888));
+    } else {
+        rsi_TypeBegin(rsc, rsi_ElementGetPredefined(rsc, RS_ELEMENT_RGB_565));
+    }
+    rsi_TypeAdd(rsc, RS_DIMENSION_X, texWidth);
+    rsi_TypeAdd(rsc, RS_DIMENSION_Y, texHeight);
+    if (genMips) {
+        rsi_TypeAdd(rsc, RS_DIMENSION_LOD, 1);
+    }
+    RsType type = rsi_TypeCreate(rsc);
+
+    RsAllocation vTexAlloc = rsi_AllocationCreateTyped(rsc, type);
+    Allocation *texAlloc = static_cast<Allocation *>(vTexAlloc);
+    texAlloc->incRef();
+    if (texAlloc == NULL) {
+        LOGE("Memory allocation failure");
+        fclose(f);
+        return NULL;
+    }
+
+    // offset to letterbox if height is not pow2
+    Adapter2D adapt(texAlloc);
+    uint8_t * fileInBuf = new uint8_t[texWidth * 3];
+    uint32_t yOffset = (hdr.width - hdr.height) / 2;
+
+    if (use32bpp) {
+        uint8_t *tmp = static_cast<uint8_t *>(adapt.getElement(0, yOffset));
+        for (int y=0; y < hdr.height; y++) {
+            fseek(f, hdr.offset + (y*hdr.width*3), SEEK_SET);
+            fread(fileInBuf, 1, hdr.width * 3, f);
+            for(int x=0; x < hdr.width; x++) {
+                tmp[0] = fileInBuf[x*3 + 2];
+                tmp[1] = fileInBuf[x*3 + 1];
+                tmp[2] = fileInBuf[x*3];
+                tmp[3] = 0xff;
+                tmp += 4;
+            }
+        }
+    } else {
+        uint16_t *tmp = static_cast<uint16_t *>(adapt.getElement(0, yOffset));
+        for (int y=0; y < hdr.height; y++) {
+            fseek(f, hdr.offset + (y*hdr.width*3), SEEK_SET);
+            fread(fileInBuf, 1, hdr.width * 3, f);
+            for(int x=0; x < hdr.width; x++) {
+                *tmp = rs888to565(fileInBuf[x*3 + 2], fileInBuf[x*3 + 1], fileInBuf[x*3]);
+                tmp++;
+            }
+        }
+    }
+
+    fclose(f);
+    delete [] fileInBuf;
+
+    if (genMips) {
+        Adapter2D adapt2(texAlloc);
+        for(uint32_t lod=0; lod < (texAlloc->getType()->getLODCount() -1); lod++) {
+            adapt.setLOD(lod);
+            adapt2.setLOD(lod + 1);
+            if (use32bpp) {
+                mip8888(adapt2, adapt);
+            } else {
+                mip565(adapt2, adapt);
+            }
+        }
+    }
+
+    return texAlloc;
+}
+
+
+void rsi_AllocationData(Context *rsc, RsAllocation va, const void *data)
+{
+    Allocation *a = static_cast<Allocation *>(va);
+    a->data(data);
+}
+
+void rsi_Allocation1DSubData(Context *rsc, RsAllocation va, uint32_t xoff, uint32_t count, const void *data)
+{
+    Allocation *a = static_cast<Allocation *>(va);
+    a->subData(xoff, count, data);
+}
+
+void rsi_Allocation2DSubData(Context *rsc, RsAllocation va, uint32_t xoff, uint32_t yoff, uint32_t w, uint32_t h, const void *data)
+{
+    Allocation *a = static_cast<Allocation *>(va);
+    a->subData(xoff, yoff, w, h, data);
+}
+
+
+}
+}
diff --git a/libs/rs/rsAllocation.h b/libs/rs/rsAllocation.h
new file mode 100644
index 0000000..d0b91fd
--- /dev/null
+++ b/libs/rs/rsAllocation.h
@@ -0,0 +1,96 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_STRUCTURED_ALLOCATION_H
+#define ANDROID_STRUCTURED_ALLOCATION_H
+
+#include "rsType.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+    
+
+class Allocation : public ObjectBase
+{
+    // The graphics equilivent of malloc.  The allocation contains a structure of elements.
+
+
+public:
+    // By policy this allocation will hold a pointer to the type
+    // but will not destroy it on destruction.
+    Allocation(const Type *);
+    virtual ~Allocation();
+
+    void setCpuWritable(bool);
+    void setGpuWritable(bool);
+    void setCpuReadable(bool);
+    void setGpuReadable(bool);
+
+    bool fixAllocation();
+
+    void * getPtr() const {return mPtr;}
+    const Type * getType() const {return mType.get();}
+
+    void uploadToTexture(uint32_t lodOffset = 0);
+    uint32_t getTextureID() const {return mTextureID;}
+
+    void uploadToBufferObject();
+    uint32_t getBufferObjectID() const {return mBufferID;}
+
+
+    void data(const void *data);
+    void subData(uint32_t xoff, uint32_t count, const void *data);
+    void subData(uint32_t xoff, uint32_t yoff, 
+                 uint32_t w, uint32_t h, const void *data);
+    void subData(uint32_t xoff, uint32_t yoff, uint32_t zoff,
+                 uint32_t w, uint32_t h, uint32_t d, const void *data);
+
+protected:
+    ObjectBaseRef<const Type> mType;
+    void * mPtr;
+
+    // Usage restrictions
+    bool mCpuWrite;
+    bool mCpuRead;
+    bool mGpuWrite;
+    bool mGpuRead;
+
+    // more usage hint data from the application
+    // which can be used by a driver to pick the best memory type.
+    // Likely ignored for now
+    float mReadWriteRatio;
+    float mUpdateSize;
+
+
+    // Is this a legal structure to be used as a texture source.
+    // Initially this will require 1D or 2D and color data
+    bool mIsTexture;
+    uint32_t mTextureID;
+
+    // Is this a legal structure to be used as a vertex source.
+    // Initially this will require 1D and x(yzw).  Additional per element data
+    // is allowed.
+    bool mIsVertexBuffer;
+    uint32_t mBufferID;
+
+};
+
+}
+}
+#endif
+
diff --git a/libs/rs/rsComponent.cpp b/libs/rs/rsComponent.cpp
new file mode 100644
index 0000000..a931811
--- /dev/null
+++ b/libs/rs/rsComponent.cpp
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+#include "rsComponent.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+
+Component::Component()
+{
+    mType = FLOAT;
+    mKind = NONE;
+    mIsNormalized = false;
+    mBits = 0;
+}
+
+Component::Component(
+    DataKind dk, DataType dt, 
+    bool isNormalized, uint32_t bits)
+{
+    mType = dt;
+    mKind = dk;
+    mIsNormalized = isNormalized;
+    mBits = bits;
+}
+
+Component::~Component()
+{
+}
diff --git a/libs/rs/rsComponent.h b/libs/rs/rsComponent.h
new file mode 100644
index 0000000..e1b0585
--- /dev/null
+++ b/libs/rs/rsComponent.h
@@ -0,0 +1,71 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_STRUCTURED_COMPONENT_H
+#define ANDROID_RS_STRUCTURED_COMPONENT_H
+
+#include "rsUtils.h"
+#include "rsObjectBase.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+class Component : public ObjectBase
+{
+public:
+    enum DataType {
+        FLOAT,
+        UNSIGNED,
+        SIGNED
+    };
+
+    enum DataKind {
+        NONE,
+        RED, GREEN, BLUE, ALPHA, LUMINANCE, INTENSITY,
+        X, Y, Z, W,
+        S, T, Q, R,
+        NX, NY, NZ,
+        INDEX,
+        USER
+    };
+
+
+    Component(DataKind dk, DataType dt, bool isNormalized, uint32_t bits);
+    virtual ~Component();
+
+    DataType getType() const {return mType;}
+    bool getIsNormalized() const {return mIsNormalized;}
+    DataKind getKind() const {return mKind;}
+    uint32_t getBits() const {return mBits;}
+
+protected:
+
+    DataType mType;
+    bool mIsNormalized;
+    DataKind mKind;
+    uint32_t mBits;
+
+private:
+    Component();
+};
+
+
+}
+}
+
+#endif //ANDROID_RS_STRUCTURED_COMPONENT_H
+
diff --git a/libs/rs/rsContext.cpp b/libs/rs/rsContext.cpp
new file mode 100644
index 0000000..78b8bf8
--- /dev/null
+++ b/libs/rs/rsContext.cpp
@@ -0,0 +1,378 @@
+/*
+ * 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.
+ */
+
+#include "rsDevice.h"
+#include "rsContext.h"
+#include "rsThreadIO.h"
+#include "utils/String8.h"
+#include <ui/FramebufferNativeWindow.h>
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+using namespace android;
+using namespace android::renderscript;
+
+Context * Context::gCon = NULL;
+pthread_key_t Context::gThreadTLSKey = 0;
+
+void Context::initEGL()
+{
+    mNumConfigs = -1;
+
+    EGLint s_configAttribs[] = {
+         EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
+#if 1
+         EGL_RED_SIZE,       8,
+         EGL_GREEN_SIZE,     8,
+         EGL_BLUE_SIZE,      8,
+         EGL_ALPHA_SIZE,     8,
+#else
+         EGL_RED_SIZE,       5,
+         EGL_GREEN_SIZE,     6,
+         EGL_BLUE_SIZE,      5,
+#endif
+         EGL_DEPTH_SIZE,     16,
+         EGL_NONE
+     };
+
+     mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
+     eglInitialize(mDisplay, &mMajorVersion, &mMinorVersion);
+     eglChooseConfig(mDisplay, s_configAttribs, &mConfig, 1, &mNumConfigs);
+
+     if (mWndSurface) {
+         mSurface = eglCreateWindowSurface(mDisplay, mConfig, mWndSurface,
+                 NULL);
+     } else {
+         mSurface = eglCreateWindowSurface(mDisplay, mConfig,
+                 android_createDisplaySurface(),
+                 NULL);
+     }
+
+     mContext = eglCreateContext(mDisplay, mConfig, NULL, NULL);
+     eglMakeCurrent(mDisplay, mSurface, mSurface, mContext);
+     eglQuerySurface(mDisplay, mSurface, EGL_WIDTH, &mWidth);
+     eglQuerySurface(mDisplay, mSurface, EGL_HEIGHT, &mHeight);
+}
+
+bool Context::runScript(Script *s, uint32_t launchID)
+{
+    ObjectBaseRef<ProgramFragment> frag(mFragment);
+    ObjectBaseRef<ProgramVertex> vtx(mVertex);
+    ObjectBaseRef<ProgramFragmentStore> store(mFragmentStore);
+
+    bool ret = s->run(this, launchID);
+
+    mFragment.set(frag);
+    mVertex.set(vtx);
+    mFragmentStore.set(store);
+    return true;
+
+}
+
+
+bool Context::runRootScript()
+{
+    rsAssert(mRootScript->mEnviroment.mIsRoot);
+
+    glColor4f(1,1,1,1);
+    glEnable(GL_LIGHT0);
+    glViewport(0, 0, mWidth, mHeight);
+
+    glDepthMask(GL_TRUE);
+    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+
+    glClearColor(mRootScript->mEnviroment.mClearColor[0],
+                 mRootScript->mEnviroment.mClearColor[1],
+                 mRootScript->mEnviroment.mClearColor[2],
+                 mRootScript->mEnviroment.mClearColor[3]);
+    glClearDepthf(mRootScript->mEnviroment.mClearDepth);
+    glClear(GL_COLOR_BUFFER_BIT);
+    glClear(GL_DEPTH_BUFFER_BIT);
+
+    return runScript(mRootScript.get(), 0);
+}
+
+void Context::setupCheck()
+{
+    if (mFragmentStore.get()) {
+        mFragmentStore->setupGL();
+    }
+    if (mFragment.get()) {
+        mFragment->setupGL();
+    }
+    if (mVertex.get()) {
+        mVertex->setupGL();
+    }
+
+}
+
+
+void * Context::threadProc(void *vrsc)
+{
+     Context *rsc = static_cast<Context *>(vrsc);
+
+     gIO = new ThreadIO();
+     rsc->initEGL();
+
+     ScriptTLSStruct *tlsStruct = new ScriptTLSStruct;
+     if (!tlsStruct) {
+         LOGE("Error allocating tls storage");
+         return NULL;
+     }
+     tlsStruct->mContext = rsc;
+     tlsStruct->mScript = NULL;
+     int status = pthread_setspecific(rsc->gThreadTLSKey, tlsStruct);
+     if (status) {
+         LOGE("pthread_setspecific %i", status);
+     }
+
+     rsc->mStateVertex.init(rsc, rsc->mWidth, rsc->mHeight);
+     rsc->setVertex(NULL);
+     rsc->mStateFragment.init(rsc, rsc->mWidth, rsc->mHeight);
+     rsc->setFragment(NULL);
+     rsc->mStateFragmentStore.init(rsc, rsc->mWidth, rsc->mHeight);
+     rsc->setFragmentStore(NULL);
+
+     rsc->mRunning = true;
+     bool mDraw = true;
+     while (!rsc->mExit) {
+         mDraw |= gIO->playCoreCommands(rsc, !mDraw);
+         mDraw &= (rsc->mRootScript.get() != NULL);
+
+         if (mDraw) {
+             mDraw = rsc->runRootScript();
+             eglSwapBuffers(rsc->mDisplay, rsc->mSurface);
+         }
+     }
+
+     glClearColor(0,0,0,0);
+     glClear(GL_COLOR_BUFFER_BIT);
+     eglSwapBuffers(rsc->mDisplay, rsc->mSurface);
+     eglTerminate(rsc->mDisplay);
+     return NULL;
+}
+
+Context::Context(Device *dev, Surface *sur)
+{
+    dev->addContext(this);
+    mDev = dev;
+    mRunning = false;
+    mExit = false;
+
+    // see comment in header
+    gCon = this;
+
+    int status;
+    pthread_attr_t threadAttr;
+
+    status = pthread_key_create(&gThreadTLSKey, NULL);
+    if (status) {
+        LOGE("Failed to init thread tls key.");
+        return;
+    }
+
+    status = pthread_attr_init(&threadAttr);
+    if (status) {
+        LOGE("Failed to init thread attribute.");
+        return;
+    }
+
+    sched_param sparam;
+    sparam.sched_priority = ANDROID_PRIORITY_DISPLAY;
+    pthread_attr_setschedparam(&threadAttr, &sparam);
+
+    mWndSurface = sur;
+
+    LOGV("RS Launching thread");
+    status = pthread_create(&mThreadId, &threadAttr, threadProc, this);
+    if (status) {
+        LOGE("Failed to start rs context thread.");
+    }
+
+    while(!mRunning) {
+        sleep(1);
+    }
+
+    pthread_attr_destroy(&threadAttr);
+}
+
+Context::~Context()
+{
+    mExit = true;
+    void *res;
+
+    int status = pthread_join(mThreadId, &res);
+
+    if (mDev) {
+        mDev->removeContext(this);
+        pthread_key_delete(gThreadTLSKey);
+    }
+}
+
+void Context::swapBuffers()
+{
+    eglSwapBuffers(mDisplay, mSurface);
+}
+
+void rsContextSwap(RsContext vrsc)
+{
+    Context *rsc = static_cast<Context *>(vrsc);
+    rsc->swapBuffers();
+}
+
+void Context::setRootScript(Script *s)
+{
+    mRootScript.set(s);
+}
+
+void Context::setFragmentStore(ProgramFragmentStore *pfs)
+{
+    if (pfs == NULL) {
+        mFragmentStore.set(mStateFragmentStore.mDefault);
+    } else {
+        mFragmentStore.set(pfs);
+    }
+    mFragmentStore->setupGL();
+}
+
+void Context::setFragment(ProgramFragment *pf)
+{
+    if (pf == NULL) {
+        mFragment.set(mStateFragment.mDefault);
+    } else {
+        mFragment.set(pf);
+    }
+    mFragment->setupGL();
+}
+
+void Context::setVertex(ProgramVertex *pv)
+{
+    if (pv == NULL) {
+        mVertex.set(mStateVertex.mDefault);
+    } else {
+        mVertex.set(pv);
+    }
+    mVertex->setupGL();
+}
+
+void Context::assignName(ObjectBase *obj, const char *name, uint32_t len)
+{
+    rsAssert(!obj->getName());
+    obj->setName(name, len);
+    mNames.add(obj);
+}
+
+void Context::removeName(ObjectBase *obj)
+{
+    for(size_t ct=0; ct < mNames.size(); ct++) {
+        if (obj == mNames[ct]) {
+            mNames.removeAt(ct);
+            return;
+        }
+    }
+}
+
+ObjectBase * Context::lookupName(const char *name) const
+{
+    for(size_t ct=0; ct < mNames.size(); ct++) {
+        if (!strcmp(name, mNames[ct]->getName())) {
+            return mNames[ct];
+        }
+    }
+    return NULL;
+}
+
+void Context::appendNameDefines(String8 *str) const
+{
+    char buf[256];
+    for (size_t ct=0; ct < mNames.size(); ct++) {
+        str->append("#define NAMED_");
+        str->append(mNames[ct]->getName());
+        str->append(" ");
+        sprintf(buf, "%i\n", (int)mNames[ct]);
+        str->append(buf);
+    }
+}
+
+
+///////////////////////////////////////////////////////////////////////////////////////////
+//
+
+namespace android {
+namespace renderscript {
+
+
+void rsi_ContextBindRootScript(Context *rsc, RsScript vs)
+{
+    Script *s = static_cast<Script *>(vs);
+    rsc->setRootScript(s);
+}
+
+void rsi_ContextBindSampler(Context *rsc, uint32_t slot, RsSampler vs)
+{
+    Sampler *s = static_cast<Sampler *>(vs);
+
+    if (slot > RS_MAX_SAMPLER_SLOT) {
+        LOGE("Invalid sampler slot");
+        return;
+    }
+
+    s->bindToContext(&rsc->mStateSampler, slot);
+}
+
+void rsi_ContextBindProgramFragmentStore(Context *rsc, RsProgramFragmentStore vpfs)
+{
+    ProgramFragmentStore *pfs = static_cast<ProgramFragmentStore *>(vpfs);
+    rsc->setFragmentStore(pfs);
+}
+
+void rsi_ContextBindProgramFragment(Context *rsc, RsProgramFragment vpf)
+{
+    ProgramFragment *pf = static_cast<ProgramFragment *>(vpf);
+    rsc->setFragment(pf);
+}
+
+void rsi_ContextBindProgramVertex(Context *rsc, RsProgramVertex vpv)
+{
+    ProgramVertex *pv = static_cast<ProgramVertex *>(vpv);
+    rsc->setVertex(pv);
+}
+
+void rsi_AssignName(Context *rsc, void * obj, const char *name, uint32_t len)
+{
+    ObjectBase *ob = static_cast<ObjectBase *>(obj);
+    rsc->assignName(ob, name, len);
+}
+
+
+}
+}
+
+
+RsContext rsContextCreate(RsDevice vdev, void *sur, uint32_t version)
+{
+    Device * dev = static_cast<Device *>(vdev);
+    Context *rsc = new Context(dev, (Surface *)sur);
+    return rsc;
+}
+
+void rsContextDestroy(RsContext vrsc)
+{
+    Context * rsc = static_cast<Context *>(vrsc);
+    delete rsc;
+}
+
diff --git a/libs/rs/rsContext.h b/libs/rs/rsContext.h
new file mode 100644
index 0000000..497dbcf
--- /dev/null
+++ b/libs/rs/rsContext.h
@@ -0,0 +1,148 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_CONTEXT_H
+#define ANDROID_RS_CONTEXT_H
+
+#include "rsUtils.h"
+
+#include <utils/Vector.h>
+#include <ui/Surface.h>
+
+#include "rsType.h"
+#include "rsMatrix.h"
+#include "rsAllocation.h"
+#include "rsTriangleMesh.h"
+#include "rsMesh.h"
+#include "rsDevice.h"
+#include "rsScriptC.h"
+#include "rsAllocation.h"
+#include "rsAdapter.h"
+#include "rsSampler.h"
+#include "rsLight.h"
+#include "rsProgramFragment.h"
+#include "rsProgramFragmentStore.h"
+#include "rsProgramVertex.h"
+
+#include "rsgApiStructs.h"
+#include "rsLocklessFifo.h"
+
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+class Context 
+{
+public:
+    Context(Device *, Surface *);
+    ~Context();
+
+    static pthread_key_t gThreadTLSKey;
+    struct ScriptTLSStruct {
+        Context * mContext;
+        Script * mScript;
+    };
+
+
+    //StructuredAllocationContext mStateAllocation;
+    ElementState mStateElement;
+    TypeState mStateType;
+    SamplerState mStateSampler;
+    ProgramFragmentState mStateFragment;
+    ProgramFragmentStoreState mStateFragmentStore;
+    ProgramVertexState mStateVertex;
+    LightState mStateLight;
+
+    TriangleMeshContext mStateTriangleMesh;
+
+    ScriptCState mScriptC;
+
+    static Context * getContext() {return gCon;}
+
+    void swapBuffers();
+    void setRootScript(Script *);
+    void setVertex(ProgramVertex *);
+    void setFragment(ProgramFragment *);
+    void setFragmentStore(ProgramFragmentStore *);
+
+    void updateSurface(void *sur);
+
+    const ProgramFragment * getFragment() {return mFragment.get();}
+    const ProgramFragmentStore * getFragmentStore() {return mFragmentStore.get();}
+
+    void setupCheck();
+
+    void assignName(ObjectBase *obj, const char *name, uint32_t len);
+    void removeName(ObjectBase *obj);
+    ObjectBase * lookupName(const char *name) const;
+    void appendNameDefines(String8 *str) const;
+
+
+    ProgramFragment * getDefaultProgramFragment() const {
+        return mStateFragment.mDefault.get();
+    }
+    ProgramVertex * getDefaultProgramVertex() const {
+        return mStateVertex.mDefault.get();
+    }
+    ProgramFragmentStore * getDefaultProgramFragmentStore() const {
+        return mStateFragmentStore.mDefault.get();
+    }
+
+protected:
+    Device *mDev;
+
+    EGLint mNumConfigs;
+    EGLint mMajorVersion;
+    EGLint mMinorVersion;
+    EGLConfig mConfig;
+    EGLContext mContext;
+    EGLSurface mSurface;
+    EGLint mWidth;
+    EGLint mHeight;
+    EGLDisplay mDisplay;
+
+    bool mRunning;
+    bool mExit;
+
+    pthread_t mThreadId;
+
+    ObjectBaseRef<Script> mRootScript;
+    ObjectBaseRef<ProgramFragment> mFragment;
+    ObjectBaseRef<ProgramVertex> mVertex;
+    ObjectBaseRef<ProgramFragmentStore> mFragmentStore;
+
+private:
+    Context();
+
+    void initEGL();
+
+    bool runScript(Script *s, uint32_t launchID);
+    bool runRootScript();
+
+    static void * threadProc(void *);
+
+    // todo: put in TLS
+    static Context *gCon;
+    Surface *mWndSurface;
+
+    Vector<ObjectBase *> mNames;
+};
+
+
+}
+}
+#endif
diff --git a/libs/rs/rsDevice.cpp b/libs/rs/rsDevice.cpp
new file mode 100644
index 0000000..1b3c41b
--- /dev/null
+++ b/libs/rs/rsDevice.cpp
@@ -0,0 +1,62 @@
+/*
+ * 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.
+ */
+
+#include "rsDevice.h"
+#include "rsContext.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+Device::Device()
+{
+
+}
+
+Device::~Device()
+{
+
+}
+
+void Device::addContext(Context *rsc)
+{
+    mContexts.add(rsc);
+}
+
+void Device::removeContext(Context *rsc)
+{
+    for (size_t idx=0; idx < mContexts.size(); idx++) {
+        if (mContexts[idx] == rsc) {
+            mContexts.removeAt(idx);
+            break;
+        }
+    }
+}
+
+
+
+RsDevice rsDeviceCreate()
+{
+    Device * d = new Device();
+    return d;
+}
+
+void rsDeviceDestroy(RsDevice dev)
+{
+    Device * d = static_cast<Device *>(dev);
+    delete d;
+
+}
+
diff --git a/libs/utils/IInterface.cpp b/libs/rs/rsDevice.h
similarity index 63%
copy from libs/utils/IInterface.cpp
copy to libs/rs/rsDevice.h
index 6ea8178..156315f 100644
--- a/libs/utils/IInterface.cpp
+++ b/libs/rs/rsDevice.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005 The Android Open Source Project
+ * 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.
@@ -14,22 +14,35 @@
  * limitations under the License.
  */
 
-#include <utils/IInterface.h>
+#ifndef ANDROID_RS_DEVICE_H
+#define ANDROID_RS_DEVICE_H
 
+#include "rsUtils.h"
+
+// ---------------------------------------------------------------------------
 namespace android {
+namespace renderscript {
 
-// ---------------------------------------------------------------------------
+class Context;
 
-sp<IBinder> IInterface::asBinder()
-{
-    return this ? onAsBinder() : NULL;
+class Device {
+public:
+    Device();
+    ~Device();
+
+    void addContext(Context *);
+    void removeContext(Context *);
+
+protected:
+    Vector<Context *> mContexts;
+
+
+};
+
+
+
+
+
 }
-
-sp<const IBinder> IInterface::asBinder() const
-{
-    return this ? const_cast<IInterface*>(this)->onAsBinder() : NULL;
 }
-
-// ---------------------------------------------------------------------------
-
-}; // namespace android
+#endif
diff --git a/libs/rs/rsElement.cpp b/libs/rs/rsElement.cpp
new file mode 100644
index 0000000..069a128
--- /dev/null
+++ b/libs/rs/rsElement.cpp
@@ -0,0 +1,432 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+
+#include <GLES/gl.h>
+
+using namespace android;
+using namespace android::renderscript;
+
+void ElementState::initPredefined()
+{
+    Component * u_8  = new Component(Component::USER,   Component::UNSIGNED,  true,  8);
+    Component * i_8  = new Component(Component::USER,   Component::SIGNED,    true,  8);
+    Component * u_16 = new Component(Component::USER,   Component::UNSIGNED,  true,  16);
+    Component * i_16 = new Component(Component::USER,   Component::SIGNED,    true,  16);
+    Component * u_32 = new Component(Component::USER,   Component::UNSIGNED,  true,  32);
+    Component * i_32 = new Component(Component::USER,   Component::SIGNED,    true,  32);
+    Component * f_32 = new Component(Component::USER,   Component::FLOAT,     true,  32);
+
+
+    Component * r_4  = new Component(Component::RED,    Component::UNSIGNED,  true,  4);
+    Component * r_5  = new Component(Component::RED,    Component::UNSIGNED,  true,  5);
+    Component * r_8  = new Component(Component::RED,    Component::UNSIGNED,  true,  8);
+
+    Component * g_4  = new Component(Component::GREEN,  Component::UNSIGNED,  true,  4);
+    Component * g_5  = new Component(Component::GREEN,  Component::UNSIGNED,  true,  5);
+    Component * g_6  = new Component(Component::GREEN,  Component::UNSIGNED,  true,  6);
+    Component * g_8  = new Component(Component::GREEN,  Component::UNSIGNED,  true,  8);
+
+    Component * b_4  = new Component(Component::BLUE,   Component::UNSIGNED,  true,  4);
+    Component * b_5  = new Component(Component::BLUE,   Component::UNSIGNED,  true,  5);
+    Component * b_8  = new Component(Component::BLUE,   Component::UNSIGNED,  true,  8);
+
+    Component * a_1  = new Component(Component::ALPHA,  Component::UNSIGNED,  true,  1);
+    Component * a_4  = new Component(Component::ALPHA,  Component::UNSIGNED,  true,  4);
+    Component * a_8  = new Component(Component::ALPHA,  Component::UNSIGNED,  true,  8);
+
+    Component * idx_16 = new Component(Component::INDEX,  Component::UNSIGNED,  false, 16);
+    Component * idx_32 = new Component(Component::INDEX,  Component::UNSIGNED,  false, 32);
+
+    Component * x    = new Component(Component::X,      Component::FLOAT,     false, 32);
+    Component * y    = new Component(Component::Y,      Component::FLOAT,     false, 32);
+    Component * z    = new Component(Component::Z,      Component::FLOAT,     false, 32);
+
+    Component * nx   = new Component(Component::NX,     Component::FLOAT,     false, 32);
+    Component * ny   = new Component(Component::NY,     Component::FLOAT,     false, 32);
+    Component * nz   = new Component(Component::NZ,     Component::FLOAT,     false, 32);
+
+    Component * s    = new Component(Component::S,      Component::FLOAT,     false, 32);
+    Component * t    = new Component(Component::T,      Component::FLOAT,     false, 32);
+
+    Element * e;
+
+    e = new Element(1);
+    e->setComponent(0, u_8);
+    mPredefinedList.add(Predefined(RS_ELEMENT_USER_U8, e));
+
+    e = new Element(1);
+    e->setComponent(0, i_8);
+    mPredefinedList.add(Predefined(RS_ELEMENT_USER_I8, e));
+
+    e = new Element(1);
+    e->setComponent(0, u_16);
+    mPredefinedList.add(Predefined(RS_ELEMENT_USER_U16, e));
+
+    e = new Element(1);
+    e->setComponent(0, i_16);
+    mPredefinedList.add(Predefined(RS_ELEMENT_USER_I16, e));
+
+    e = new Element(1);
+    e->setComponent(0, u_32);
+    mPredefinedList.add(Predefined(RS_ELEMENT_USER_U32, e));
+
+    e = new Element(1);
+    e->setComponent(0, i_32);
+    mPredefinedList.add(Predefined(RS_ELEMENT_USER_I32, e));
+
+    e = new Element(1);
+    e->setComponent(0, f_32);
+    mPredefinedList.add(Predefined(RS_ELEMENT_USER_FLOAT, e));
+
+    e = new Element(1);
+    e->setComponent(0, a_8);
+    mPredefinedList.add(Predefined(RS_ELEMENT_A_8, e));
+
+    e = new Element(3);
+    e->setComponent(0, r_5);
+    e->setComponent(1, g_6);
+    e->setComponent(2, b_5);
+    mPredefinedList.add(Predefined(RS_ELEMENT_RGB_565, e));
+
+    e = new Element(4);
+    e->setComponent(0, r_5);
+    e->setComponent(1, g_5);
+    e->setComponent(2, b_5);
+    e->setComponent(3, a_1);
+    mPredefinedList.add(Predefined(RS_ELEMENT_RGBA_5551, e));
+
+    e = new Element(4);
+    e->setComponent(0, r_4);
+    e->setComponent(1, g_4);
+    e->setComponent(2, b_4);
+    e->setComponent(3, a_4);
+    mPredefinedList.add(Predefined(RS_ELEMENT_RGBA_4444, e));
+
+    e = new Element(3);
+    e->setComponent(0, r_8);
+    e->setComponent(1, g_8);
+    e->setComponent(2, b_8);
+    mPredefinedList.add(Predefined(RS_ELEMENT_RGB_888, e));
+
+    e = new Element(4);
+    e->setComponent(0, r_8);
+    e->setComponent(1, g_8);
+    e->setComponent(2, b_8);
+    e->setComponent(3, a_8);
+    mPredefinedList.add(Predefined(RS_ELEMENT_RGBA_8888, e));
+
+    e = new Element(1);
+    e->setComponent(0, idx_16);
+    mPredefinedList.add(Predefined(RS_ELEMENT_INDEX_16, e));
+
+    e = new Element(1);
+    e->setComponent(0, idx_32);
+    mPredefinedList.add(Predefined(RS_ELEMENT_INDEX_32, e));
+
+    e = new Element(2);
+    e->setComponent(0, x);
+    e->setComponent(1, y);
+    mPredefinedList.add(Predefined(RS_ELEMENT_XY_F32, e));
+
+    e = new Element(3);
+    e->setComponent(0, x);
+    e->setComponent(1, y);
+    e->setComponent(2, z);
+    mPredefinedList.add(Predefined(RS_ELEMENT_XYZ_F32, e));
+
+    e = new Element(4);
+    e->setComponent(0, s);
+    e->setComponent(1, t);
+    e->setComponent(2, x);
+    e->setComponent(3, y);
+    mPredefinedList.add(Predefined(RS_ELEMENT_ST_XY_F32, e));
+
+    e = new Element(5);
+    e->setComponent(0, s);
+    e->setComponent(1, t);
+    e->setComponent(2, x);
+    e->setComponent(3, y);
+    e->setComponent(4, z);
+    mPredefinedList.add(Predefined(RS_ELEMENT_ST_XYZ_F32, e));
+
+    e = new Element(6);
+    e->setComponent(0, nx);
+    e->setComponent(1, ny);
+    e->setComponent(2, nz);
+    e->setComponent(3, x);
+    e->setComponent(4, y);
+    e->setComponent(5, z);
+    mPredefinedList.add(Predefined(RS_ELEMENT_NORM_XYZ_F32, e));
+
+    e = new Element(8);
+    e->setComponent(0, nx);
+    e->setComponent(1, ny);
+    e->setComponent(2, nz);
+    e->setComponent(3, s);
+    e->setComponent(4, t);
+    e->setComponent(5, x);
+    e->setComponent(6, y);
+    e->setComponent(7, z);
+    mPredefinedList.add(Predefined(RS_ELEMENT_NORM_ST_XYZ_F32, e));
+}
+
+
+Element::Element()
+{
+    mComponents = NULL;
+    mComponentCount = 0;
+}
+
+Element::Element(uint32_t count)
+{
+    mComponents = new ObjectBaseRef<Component> [count];
+    mComponentCount = count;
+}
+
+Element::~Element()
+{
+    clear();
+}
+
+void Element::clear()
+{
+    delete [] mComponents;
+    mComponents = NULL;
+    mComponentCount = 0;
+}
+
+void Element::setComponent(uint32_t idx, Component *c)
+{
+    rsAssert(!mComponents[idx].get());
+    rsAssert(idx < mComponentCount);
+    mComponents[idx].set(c);
+    c->incRef();
+}
+
+
+size_t Element::getSizeBits() const
+{
+    size_t total = 0;
+    for (size_t ct=0; ct < mComponentCount; ct++) {
+        total += mComponents[ct]->getBits();
+    }
+    return total;
+}
+
+size_t Element::getComponentOffsetBits(uint32_t componentNumber) const
+{
+    size_t offset = 0;
+    for (uint32_t ct = 0; ct < componentNumber; ct++) {
+        offset += mComponents[ct]->getBits();
+    }
+    return offset;
+}
+
+uint32_t Element::getGLType() const
+{
+    int bits[4];
+
+    if (mComponentCount > 4) {
+        return 0;
+    }
+
+    for (uint32_t ct=0; ct < mComponentCount; ct++) {
+        bits[ct] = mComponents[ct]->getBits();
+        if (mComponents[ct]->getType() != Component::UNSIGNED) {
+            return 0;
+        }
+        if (!mComponents[ct]->getIsNormalized()) {
+            return 0;
+        }
+    }
+
+    switch(mComponentCount) {
+    case 1:
+        if (bits[0] == 8) {
+            return GL_UNSIGNED_BYTE;
+        }
+        return 0;
+    case 2:
+        if ((bits[0] == 8) &&
+            (bits[1] == 8)) {
+            return GL_UNSIGNED_BYTE;
+        }
+        return 0;
+    case 3:
+        if ((bits[0] == 8) &&
+            (bits[1] == 8) &&
+            (bits[2] == 8)) {
+            return GL_UNSIGNED_BYTE;
+        }
+        if ((bits[0] == 5) &&
+            (bits[1] == 6) &&
+            (bits[2] == 5)) {
+            return GL_UNSIGNED_SHORT_5_6_5;
+        }
+        return 0;
+    case 4:
+        if ((bits[0] == 8) &&
+            (bits[1] == 8) &&
+            (bits[2] == 8) &&
+            (bits[3] == 8)) {
+            return GL_UNSIGNED_BYTE;
+        }
+        if ((bits[0] == 4) &&
+            (bits[1] == 4) &&
+            (bits[2] == 4) &&
+            (bits[3] == 4)) {
+            return GL_UNSIGNED_SHORT_4_4_4_4;
+        }
+        if ((bits[0] == 5) &&
+            (bits[1] == 5) &&
+            (bits[2] == 5) &&
+            (bits[3] == 1)) {
+            return GL_UNSIGNED_SHORT_5_5_5_1;
+        }
+    }
+    return 0;
+}
+
+uint32_t Element::getGLFormat() const
+{
+    switch(mComponentCount) {
+    case 1:
+        if (mComponents[0]->getKind() == Component::ALPHA) {
+            return GL_ALPHA;
+        }
+        if (mComponents[0]->getKind() == Component::LUMINANCE) {
+            return GL_LUMINANCE;
+        }
+        break;
+    case 2:
+        if ((mComponents[0]->getKind() == Component::LUMINANCE) &&
+            (mComponents[1]->getKind() == Component::ALPHA)) {
+            return GL_LUMINANCE_ALPHA;
+        }
+        break;
+    case 3:
+        if ((mComponents[0]->getKind() == Component::RED) &&
+            (mComponents[1]->getKind() == Component::GREEN) &&
+            (mComponents[2]->getKind() == Component::BLUE)) {
+            return GL_RGB;
+        }
+        break;
+    case 4:
+        if ((mComponents[0]->getKind() == Component::RED) &&
+            (mComponents[1]->getKind() == Component::GREEN) &&
+            (mComponents[2]->getKind() == Component::BLUE) &&
+            (mComponents[3]->getKind() == Component::ALPHA)) {
+            return GL_RGBA;
+        }
+        break;
+    }
+    return 0;
+}
+
+
+ElementState::ElementState()
+{
+}
+
+ElementState::~ElementState()
+{
+}
+
+/////////////////////////////////////////
+// 
+
+namespace android {
+namespace renderscript {
+
+void rsi_ElementBegin(Context *rsc)
+{
+    rsc->mStateElement.mComponentBuildList.clear();
+}
+
+void rsi_ElementAddPredefined(Context *rsc, RsElementPredefined predef)
+{
+    ElementState * sec = &rsc->mStateElement;
+
+    RsElement ve = rsi_ElementGetPredefined(rsc, predef);
+    const Element *e = static_cast<const Element *>(ve);
+
+    for(size_t ct = 0; ct < sec->mPredefinedList[predef].mElement->getComponentCount(); ct++) {
+        sec->mComponentBuildList.add(sec->mPredefinedList[predef].mElement->getComponent(ct));
+    }
+}
+
+RsElement rsi_ElementGetPredefined(Context *rsc, RsElementPredefined predef)
+{
+    ElementState * sec = &rsc->mStateElement;
+
+    if (!sec->mPredefinedList.size()) {
+        sec->initPredefined();
+    }
+
+    if ((predef < 0) || 
+        (static_cast<uint32_t>(predef) >= sec->mPredefinedList.size())) {
+        LOGE("rsElementGetPredefined: Request for bad predefined type");
+        // error
+        return NULL;
+    }
+
+    rsAssert(sec->mPredefinedList[predef].mEnum == predef);
+    Element * e = sec->mPredefinedList[predef].mElement;
+    e->incRef();
+    return e;
+}
+
+void rsi_ElementAdd(Context *rsc, RsDataKind dk, RsDataType dt, bool isNormalized, size_t bits)
+{
+    ElementState * sec = &rsc->mStateElement;
+
+}
+
+RsElement rsi_ElementCreate(Context *rsc)
+{
+    ElementState * sec = &rsc->mStateElement;
+
+    Element *se = new Element(sec->mComponentBuildList.size());
+    sec->mAllElements.add(se);
+
+    for (size_t ct = 0; ct < se->getComponentCount(); ct++) {
+        se->setComponent(ct, sec->mComponentBuildList[ct]);
+    }
+
+    rsc->mStateElement.mComponentBuildList.clear();
+    se->incRef();
+    return se;
+}
+
+void rsi_ElementDestroy(Context *rsc, RsElement vse)
+{
+    ElementState * sec = &rsc->mStateElement;
+    Element * se = static_cast<Element *>(vse);
+
+    for (size_t ct = 0; ct < sec->mAllElements.size(); ct++) {
+        if (sec->mAllElements[ct] == se) {
+            sec->mAllElements.removeAt(ct);
+            break;
+        }
+    }
+    se->decRef();
+}
+
+
+}
+}
diff --git a/libs/rs/rsElement.h b/libs/rs/rsElement.h
new file mode 100644
index 0000000..ea6fa8f
--- /dev/null
+++ b/libs/rs/rsElement.h
@@ -0,0 +1,96 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_STRUCTURED_ELEMENT_H
+#define ANDROID_STRUCTURED_ELEMENT_H
+
+#include "rsComponent.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+
+// An element is a group of Components that occupies one cell in a structure.
+class Element : public ObjectBase
+{
+public:
+    Element(uint32_t count);
+    ~Element();
+
+
+    void setComponent(uint32_t idx, Component *c);
+
+    uint32_t getGLType() const;
+    uint32_t getGLFormat() const;
+
+
+    size_t getSizeBits() const;
+    size_t getSizeBytes() const { 
+        return (getSizeBits() + 7) >> 3; 
+    }
+
+    size_t getComponentOffsetBits(uint32_t componentNumber) const;
+    size_t getComponentOffsetBytes(uint32_t componentNumber) const { 
+        return (getComponentOffsetBits(componentNumber) + 7) >> 3;
+    }
+
+    uint32_t getComponentCount() const {return mComponentCount;}
+    Component * getComponent(uint32_t idx) const {return mComponents[idx].get();}
+
+protected:
+    // deallocate any components that are part of this element.
+    void clear();
+
+    size_t mComponentCount;
+    ObjectBaseRef<Component> * mComponents;
+    //uint32_t *mOffsetTable;
+
+    Element();
+};
+
+
+class ElementState {
+public:
+    ElementState();
+    ~ElementState();
+
+    Vector<Element *> mAllElements;
+    Vector<Component *> mComponentBuildList;
+
+
+
+    struct Predefined {
+        Predefined() {
+            mElement = NULL;
+        }
+        Predefined(RsElementPredefined en, Element *e) {
+            mEnum = en; 
+            mElement = e;
+        }
+        RsElementPredefined mEnum;
+        Element * mElement;
+    };
+    Vector<Predefined> mPredefinedList;
+
+    void initPredefined();
+    
+};
+
+
+}
+}
+#endif //ANDROID_STRUCTURED_ELEMENT_H
diff --git a/libs/rs/rsFileA3D.cpp b/libs/rs/rsFileA3D.cpp
new file mode 100644
index 0000000..86d294b
--- /dev/null
+++ b/libs/rs/rsFileA3D.cpp
@@ -0,0 +1,384 @@
+
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+
+
+#include <utils/String8.h>
+#include "rsFileA3D.h"
+
+#include "rsMesh.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+
+
+FileA3D::FileA3D()
+{
+    mRsc = NULL;
+}
+
+FileA3D::~FileA3D()
+{
+}
+
+bool FileA3D::load(Context *rsc, FILE *f)
+{
+    char magicString[12];
+    size_t len;
+
+    LOGE("file open 1");
+    len = fread(magicString, 1, 12, f);
+    if ((len != 12) ||
+        memcmp(magicString, "Android3D_ff", 12)) {
+        return false;
+    }
+
+    LOGE("file open 2");
+    len = fread(&mMajorVersion, 1, sizeof(mMajorVersion), f);
+    if (len != sizeof(mMajorVersion)) {
+        return false;
+    }
+
+    LOGE("file open 3");
+    len = fread(&mMinorVersion, 1, sizeof(mMinorVersion), f);
+    if (len != sizeof(mMinorVersion)) {
+        return false;
+    }
+
+    LOGE("file open 4");
+    uint32_t flags;
+    len = fread(&flags, 1, sizeof(flags), f);
+    if (len != sizeof(flags)) {
+        return false;
+    }
+    mUse64BitOffsets = (flags & 1) != 0;
+
+    LOGE("file open 64bit = %i", mUse64BitOffsets);
+
+    if (mUse64BitOffsets) {
+        len = fread(&mDataSize, 1, sizeof(mDataSize), f);
+        if (len != sizeof(mDataSize)) {
+            return false;
+        }
+    } else {
+        uint32_t tmp;
+        len = fread(&tmp, 1, sizeof(tmp), f);
+        if (len != sizeof(tmp)) {
+            return false;
+        }
+        mDataSize = tmp;
+    }
+
+    LOGE("file open size = %lli", mDataSize);
+
+    // We should know enough to read the file in at this point.
+    fseek(f, SEEK_SET, 0);
+    mAlloc= malloc(mDataSize);
+    if (!mAlloc) {
+        return false;
+    }
+    mData = (uint8_t *)mAlloc;
+    len = fread(mAlloc, 1, mDataSize, f);
+    if (len != mDataSize) {
+        return false;
+    }
+
+    LOGE("file start processing");
+    return process(rsc);
+}
+
+bool FileA3D::processIndex(Context *rsc, A3DIndexEntry *ie)
+{
+    bool ret = false;
+    IO io(mData + ie->mOffset, mUse64BitOffsets);
+
+    LOGE("process index, type %i", ie->mType);
+
+    switch(ie->mType) {
+    case CHUNK_ELEMENT:
+        processChunk_Element(rsc, &io, ie);
+        break;
+    case CHUNK_ELEMENT_SOURCE:
+        processChunk_ElementSource(rsc, &io, ie);
+        break;
+    case CHUNK_VERTICIES:
+        processChunk_Verticies(rsc, &io, ie);
+        break;
+    case CHUNK_MESH:
+        processChunk_Mesh(rsc, &io, ie);
+        break;
+    case CHUNK_PRIMITIVE:
+        processChunk_Primitive(rsc, &io, ie);
+        break;
+    default:
+        LOGE("FileA3D Unknown chunk type");
+        break;
+    }
+    return (ie->mRsObj != NULL);
+}
+
+bool FileA3D::process(Context *rsc)
+{
+    LOGE("process");
+    IO io(mData + 12, mUse64BitOffsets);
+    bool ret = true;
+
+    // Build the index first
+    LOGE("process 1");
+    io.loadU32(); // major version, already loaded
+    io.loadU32(); // minor version, already loaded
+    LOGE("process 2");
+
+    io.loadU32();  // flags
+    io.loadOffset(); // filesize, already loaded.
+    LOGE("process 4");
+    uint64_t mIndexOffset = io.loadOffset();
+    uint64_t mStringOffset = io.loadOffset();
+
+    LOGE("process mIndexOffset= 0x%016llx", mIndexOffset);
+    LOGE("process mStringOffset= 0x%016llx", mStringOffset);
+
+    IO index(mData + mIndexOffset, mUse64BitOffsets);
+    IO stringTable(mData + mStringOffset, mUse64BitOffsets);
+
+    uint32_t stringEntryCount = stringTable.loadU32();
+    LOGE("stringEntryCount %i", stringEntryCount);
+    mStrings.setCapacity(stringEntryCount);
+    mStringIndexValues.setCapacity(stringEntryCount);
+    if (stringEntryCount) {
+        uint32_t stringType = stringTable.loadU32();
+        LOGE("stringType %i", stringType);
+        rsAssert(stringType==0);
+        for (uint32_t ct = 0; ct < stringEntryCount; ct++) {
+            uint64_t offset = stringTable.loadOffset();
+            LOGE("string offset 0x%016llx", offset);
+            IO tmp(mData + offset, mUse64BitOffsets);
+            String8 s;
+            tmp.loadString(&s);
+            LOGE("string %s", s.string());
+            mStrings.push(s);
+        }
+    }
+
+    LOGE("strings done");
+    uint32_t indexEntryCount = index.loadU32();
+    LOGE("index count %i", indexEntryCount);
+    mIndex.setCapacity(indexEntryCount);
+    for (uint32_t ct = 0; ct < indexEntryCount; ct++) {
+        A3DIndexEntry e;
+        uint32_t stringIndex = index.loadU32();
+        LOGE("index %i", ct);
+        LOGE("  string index %i", stringIndex);
+        e.mType = (A3DChunkType)index.loadU32();
+        LOGE("  type %i", e.mType);
+        e.mOffset = index.loadOffset();
+        LOGE("  offset 0x%016llx", e.mOffset);
+
+        if (stringIndex && (stringIndex < mStrings.size())) {
+            e.mID = mStrings[stringIndex];
+            mStringIndexValues.editItemAt(stringIndex) = ct;
+            LOGE("  id %s", e.mID.string());
+        }
+
+        mIndex.push(e);
+    }
+    LOGE("index done");
+
+    // At this point the index should be fully populated.
+    // We can now walk though it and load all the objects.
+    for (uint32_t ct = 0; ct < indexEntryCount; ct++) {
+        LOGE("processing index entry %i", ct);
+        processIndex(rsc, &mIndex.editItemAt(ct));
+    }
+
+    return ret;
+}
+
+
+FileA3D::IO::IO(const uint8_t *buf, bool use64)
+{
+    mData = buf;
+    mPos = 0;
+    mUse64 = use64;
+}
+
+uint64_t FileA3D::IO::loadOffset()
+{
+    uint64_t tmp;
+    if (mUse64) {
+        mPos = (mPos + 7) & (~7);
+        tmp = reinterpret_cast<const uint64_t *>(&mData[mPos])[0];
+        mPos += sizeof(uint64_t);
+        return tmp;
+    }
+    return loadU32();
+}
+
+void FileA3D::IO::loadString(String8 *s)
+{
+    LOGE("loadString");
+    uint32_t len = loadU32();
+    LOGE("loadString len %i", len);
+    s->setTo((const char *)&mData[mPos], len);
+    mPos += len;
+}
+
+
+void FileA3D::processChunk_Mesh(Context *rsc, IO *io, A3DIndexEntry *ie)
+{
+    Mesh * m = new Mesh;
+
+    m->mPrimitivesCount = io->loadU32();
+    m->mPrimitives = new Mesh::Primitive_t *[m->mPrimitivesCount];
+
+    for (uint32_t ct = 0; ct < m->mPrimitivesCount; ct++) {
+        uint32_t index = io->loadU32();
+
+        m->mPrimitives[ct] = (Mesh::Primitive_t *)mIndex[index].mRsObj;
+    }
+    ie->mRsObj = m;
+}
+
+void FileA3D::processChunk_Primitive(Context *rsc, IO *io, A3DIndexEntry *ie)
+{
+    Mesh::Primitive_t * p = new Mesh::Primitive_t;
+
+    p->mIndexCount = io->loadU32();
+    uint32_t vertIdx = io->loadU32();
+    p->mRestartCounts = io->loadU16();
+    uint32_t bits = io->loadU8();
+    p->mType = (RsPrimitive)io->loadU8();
+
+    LOGE("processChunk_Primitive count %i, bits %i", p->mIndexCount, bits);
+
+    p->mVerticies = (Mesh::Verticies_t *)mIndex[vertIdx].mRsObj;
+
+    p->mIndicies = new uint16_t[p->mIndexCount];
+    for (uint32_t ct = 0; ct < p->mIndexCount; ct++) {
+        switch(bits) {
+        case 8:
+            p->mIndicies[ct] = io->loadU8();
+            break;
+        case 16:
+            p->mIndicies[ct] = io->loadU16();
+            break;
+        case 32:
+            p->mIndicies[ct] = io->loadU32();
+            break;
+        }
+        LOGE("  idx %i", p->mIndicies[ct]);
+    }
+
+    if (p->mRestartCounts) {
+        p->mRestarts = new uint16_t[p->mRestartCounts];
+        for (uint32_t ct = 0; ct < p->mRestartCounts; ct++) {
+            switch(bits) {
+            case 8:
+                p->mRestarts[ct] = io->loadU8();
+                break;
+            case 16:
+                p->mRestarts[ct] = io->loadU16();
+                break;
+            case 32:
+                p->mRestarts[ct] = io->loadU32();
+                break;
+            }
+            LOGE("  idx %i", p->mRestarts[ct]);
+        }
+    } else {
+        p->mRestarts = NULL;
+    }
+
+    ie->mRsObj = p;
+}
+
+void FileA3D::processChunk_Verticies(Context *rsc, IO *io, A3DIndexEntry *ie)
+{
+    Mesh::Verticies_t *cv = new Mesh::Verticies_t;
+    cv->mAllocationCount = io->loadU32();
+    cv->mAllocations = new Allocation *[cv->mAllocationCount];
+    LOGE("processChunk_Verticies count %i", cv->mAllocationCount);
+    for (uint32_t ct = 0; ct < cv->mAllocationCount; ct++) {
+        uint32_t i = io->loadU32();
+        cv->mAllocations[ct] = (Allocation *)mIndex[i].mRsObj;
+        LOGE("  idx %i", i);
+    }
+    ie->mRsObj = cv;
+}
+
+void FileA3D::processChunk_Element(Context *rsc, IO *io, A3DIndexEntry *ie)
+{
+    rsi_ElementBegin(rsc);
+
+    uint32_t count = io->loadU32();
+    LOGE("processChunk_Element count %i", count);
+    while (count--) {
+        RsDataKind dk = (RsDataKind)io->loadU8();
+        RsDataType dt = (RsDataType)io->loadU8();
+        uint32_t bits = io->loadU8();
+        bool isNorm = io->loadU8() != 0;
+        LOGE("  %i %i %i %i", dk, dt, bits, isNorm);
+        rsi_ElementAdd(rsc, dk, dt, isNorm, bits);
+    }
+    LOGE("processChunk_Element create");
+    ie->mRsObj = rsi_ElementCreate(rsc);
+}
+
+void FileA3D::processChunk_ElementSource(Context *rsc, IO *io, A3DIndexEntry *ie)
+{
+    uint32_t index = io->loadU32();
+    uint32_t count = io->loadU32();
+
+    LOGE("processChunk_ElementSource count %i, index %i", count, index);
+
+    RsElement e = (RsElement)mIndex[index].mRsObj;
+
+    RsAllocation a = rsi_AllocationCreateSized(rsc, e, count);
+    Allocation * alloc = static_cast<Allocation *>(a);
+
+    float * data = (float *)alloc->getPtr();
+    while(count--) {
+        *data = io->loadF();
+        LOGE("  %f", *data);
+        data++;
+    }
+    ie->mRsObj = alloc;
+}
+
+namespace android {
+namespace renderscript {
+
+
+RsFile rsi_FileOpen(Context *rsc, char const *path, unsigned int len)
+{
+    FileA3D *fa3d = new FileA3D;
+
+    FILE *f = fopen("/sdcard/test.a3d", "rb");
+    if (f) {
+        fa3d->load(rsc, f);
+        fclose(f);
+        return fa3d;
+    }
+    delete fa3d;
+    return NULL;
+}
+
+
+}
+}
diff --git a/libs/rs/rsFileA3D.h b/libs/rs/rsFileA3D.h
new file mode 100644
index 0000000..9ee08ec
--- /dev/null
+++ b/libs/rs/rsFileA3D.h
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_FILE_A3D_H
+#define ANDROID_RS_FILE_A3D_H
+
+#include "RenderScript.h"
+#include "rsFileA3DDecls.h"
+#include "rsMesh.h"
+
+#include <utils/String8.h>
+#include <stdio.h>
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+class FileA3D
+{
+public:
+    FileA3D();
+    ~FileA3D();
+
+    uint32_t mMajorVersion;
+    uint32_t mMinorVersion;
+    uint64_t mIndexOffset;
+    uint64_t mStringTableOffset;
+    bool mUse64BitOffsets;
+
+    struct A3DIndexEntry {
+        String8 mID;
+        A3DChunkType mType;
+        uint64_t mOffset;
+        void * mRsObj;
+    };
+
+    bool load(Context *rsc, FILE *f);
+
+protected:
+    class IO
+    {
+    public:
+        IO(const uint8_t *, bool use64);
+    
+        float loadF() {
+            mPos = (mPos + 3) & (~3);
+            float tmp = reinterpret_cast<const float *>(&mData[mPos])[0];
+            mPos += sizeof(float);
+            return tmp;
+        }
+        int32_t loadI32() {
+            mPos = (mPos + 3) & (~3);
+            int32_t tmp = reinterpret_cast<const int32_t *>(&mData[mPos])[0];
+            mPos += sizeof(int32_t);
+            return tmp;
+        }
+        uint32_t loadU32() {
+            mPos = (mPos + 3) & (~3);
+            uint32_t tmp = reinterpret_cast<const uint32_t *>(&mData[mPos])[0];
+            mPos += sizeof(uint32_t);
+            return tmp;
+        }
+        uint16_t loadU16() {
+            mPos = (mPos + 1) & (~1);
+            uint16_t tmp = reinterpret_cast<const uint16_t *>(&mData[mPos])[0];
+            mPos += sizeof(uint16_t);
+            return tmp;
+        }
+        uint8_t loadU8() {
+            uint8_t tmp = reinterpret_cast<const uint8_t *>(&mData[mPos])[0];
+            mPos += sizeof(uint8_t);
+            return tmp;
+        }
+        uint64_t loadOffset();
+        void loadString(String8 *s);
+        uint64_t getPos() const {return mPos;}
+        const uint8_t * getPtr() const;
+    protected:
+        const uint8_t * mData;
+        uint64_t mPos;
+        bool mUse64;
+    };
+
+
+    bool process(Context *rsc);
+    bool processIndex(Context *rsc, A3DIndexEntry *);
+    void processChunk_Mesh(Context *rsc, IO *io, A3DIndexEntry *ie);
+    void processChunk_Primitive(Context *rsc, IO *io, A3DIndexEntry *ie);
+    void processChunk_Verticies(Context *rsc, IO *io, A3DIndexEntry *ie);
+    void processChunk_Element(Context *rsc, IO *io, A3DIndexEntry *ie);
+    void processChunk_ElementSource(Context *rsc, IO *io, A3DIndexEntry *ie);
+
+    const uint8_t * mData;
+    void * mAlloc;
+    uint64_t mDataSize;
+    Context * mRsc;
+
+    Vector<A3DIndexEntry> mIndex;
+    Vector<String8> mStrings;
+    Vector<uint32_t> mStringIndexValues;
+
+};
+
+
+}
+}
+#endif //ANDROID_RS_FILE_A3D_H
+
+
diff --git a/libs/rs/rsFileA3DDecls.h b/libs/rs/rsFileA3DDecls.h
new file mode 100644
index 0000000..2a08bd3
--- /dev/null
+++ b/libs/rs/rsFileA3DDecls.h
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_FILE_A3D_DECLS_H
+#define ANDROID_RS_FILE_A3D_DECLS_H
+
+
+#define A3D_MAGIC_KEY "Android3D_ff"
+
+namespace android {
+namespace renderscript {
+
+    enum A3DChunkType {
+        CHUNK_EMPTY,
+
+        CHUNK_ELEMENT,
+        CHUNK_ELEMENT_SOURCE,
+        CHUNK_VERTICIES,
+        CHUNK_MESH,
+        CHUNK_PRIMITIVE,
+
+        CHUNK_LAST
+    };
+
+
+}
+}
+#endif //ANDROID_RS_FILE_A3D_H
+
+
+
diff --git a/libs/rs/rsLight.cpp b/libs/rs/rsLight.cpp
new file mode 100644
index 0000000..24b58b6
--- /dev/null
+++ b/libs/rs/rsLight.cpp
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+
+#include <GLES/gl.h>
+
+using namespace android;
+using namespace android::renderscript;
+
+
+Light::Light(bool isLocal, bool isMono)
+{
+    mIsLocal = isLocal;
+    mIsMono = isMono;
+
+    mPosition[0] = 0;
+    mPosition[1] = 0;
+    mPosition[2] = 1;
+    mPosition[3] = 0;
+
+    mColor[0] = 1.f;
+    mColor[1] = 1.f;
+    mColor[2] = 1.f;
+    mColor[3] = 1.f;
+}
+
+Light::~Light()
+{
+}
+
+void Light::setPosition(float x, float y, float z)
+{
+    mPosition[0] = x;
+    mPosition[1] = y;
+    mPosition[2] = z;
+}
+
+void Light::setColor(float r, float g, float b)
+{
+    mColor[0] = r;
+    mColor[1] = g;
+    mColor[2] = b;
+}
+
+void Light::setupGL(uint32_t num) const
+{
+    glLightfv(GL_LIGHT0 + num, GL_DIFFUSE, mColor);
+    glLightfv(GL_LIGHT0 + num, GL_SPECULAR, mColor);
+    glLightfv(GL_LIGHT0 + num, GL_POSITION, mPosition);
+}
+
+////////////////////////////////////////////
+
+LightState::LightState()
+{
+    clear();
+}
+
+LightState::~LightState()
+{
+}
+
+void LightState::clear()
+{
+    mIsLocal = false;
+    mIsMono = false;
+}
+
+
+////////////////////////////////////////////////////
+// 
+
+namespace android {
+namespace renderscript {
+
+void rsi_LightBegin(Context *rsc)
+{
+    rsc->mStateLight.clear();
+}
+
+void rsi_LightSetLocal(Context *rsc, bool isLocal)
+{
+    rsc->mStateLight.mIsLocal = isLocal;
+}
+
+void rsi_LightSetMonochromatic(Context *rsc, bool isMono)
+{
+    rsc->mStateLight.mIsMono = isMono;
+}
+
+RsLight rsi_LightCreate(Context *rsc)
+{
+    Light *l = new Light(rsc->mStateLight.mIsLocal,
+                         rsc->mStateLight.mIsMono);
+    l->incRef();
+    return l;
+}
+
+void rsi_LightDestroy(Context *rsc, RsLight vl)
+{
+    Light *l = static_cast<Light *>(vl);
+    l->decRef();
+}
+
+void rsi_LightSetColor(Context *rsc, RsLight vl, float r, float g, float b)
+{
+    Light *l = static_cast<Light *>(vl);
+    l->setColor(r, g, b);
+}
+
+void rsi_LightSetPosition(Context *rsc, RsLight vl, float x, float y, float z)
+{
+    Light *l = static_cast<Light *>(vl);
+    l->setPosition(x, y, z);
+}
+
+
+
+}
+}
diff --git a/libs/rs/rsLight.h b/libs/rs/rsLight.h
new file mode 100644
index 0000000..b0c3386
--- /dev/null
+++ b/libs/rs/rsLight.h
@@ -0,0 +1,64 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_LIGHT_H
+#define ANDROID_LIGHT_H
+
+
+#include "rsObjectBase.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+
+// An element is a group of Components that occupies one cell in a structure.
+class Light : public ObjectBase
+{
+public:
+    Light(bool isLocal, bool isMono);
+    virtual ~Light();
+
+    // Values, mutable after creation.
+    void setPosition(float x, float y, float z);
+    void setColor(float r, float g, float b);
+
+    void setupGL(uint32_t num) const;
+
+protected:
+    float mColor[4];
+    float mPosition[4];
+    bool mIsLocal;
+    bool mIsMono;
+};
+
+
+class LightState {
+public:
+    LightState();
+    ~LightState();
+
+    void clear();
+
+    bool mIsMono;
+    bool mIsLocal;
+};
+
+
+}
+}
+#endif //ANDROID_LIGHT_H
+
diff --git a/libs/rs/rsLocklessFifo.cpp b/libs/rs/rsLocklessFifo.cpp
new file mode 100644
index 0000000..c3fee54
--- /dev/null
+++ b/libs/rs/rsLocklessFifo.cpp
@@ -0,0 +1,247 @@
+/*
+ * 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.
+ */
+
+#include "rsLocklessFifo.h"
+
+using namespace android;
+
+
+LocklessCommandFifo::LocklessCommandFifo()
+{
+}
+
+LocklessCommandFifo::~LocklessCommandFifo()
+{
+}
+
+bool LocklessCommandFifo::init(uint32_t sizeInBytes)
+{
+    // Add room for a buffer reset command
+    mBuffer = static_cast<uint8_t *>(malloc(sizeInBytes + 4));
+    if (!mBuffer) {
+        LOGE("LocklessFifo allocation failure");
+        return false;
+    }
+
+    if (!mSignalToControl.init() || !mSignalToWorker.init()) {
+        LOGE("Signal setup failed");
+        free(mBuffer);
+        return false;
+    }
+
+    mSize = sizeInBytes;
+    mPut = mBuffer;
+    mGet = mBuffer;
+    mEnd = mBuffer + (sizeInBytes) - 1;
+    dumpState("init");
+    return true;
+}
+
+uint32_t LocklessCommandFifo::getFreeSpace() const 
+{
+    int32_t freeSpace = 0;
+    //dumpState("getFreeSpace");
+
+    if (mPut >= mGet) {
+        freeSpace = mEnd - mPut;
+    } else {
+        freeSpace = mGet - mPut;
+    }
+
+    if (freeSpace < 0) {
+        freeSpace = 0;
+    }
+    return freeSpace;
+}
+
+bool LocklessCommandFifo::isEmpty() const
+{
+    return mPut == mGet;
+}
+
+
+void * LocklessCommandFifo::reserve(uint32_t sizeInBytes)
+{
+    // Add space for command header and loop token;
+    sizeInBytes += 8;
+
+    //dumpState("reserve");
+    if (getFreeSpace() < sizeInBytes) {
+        makeSpace(sizeInBytes);
+    }
+
+    return mPut + 4;
+}
+
+void LocklessCommandFifo::commit(uint32_t command, uint32_t sizeInBytes)
+{
+    //dumpState("commit 1");
+    reinterpret_cast<uint16_t *>(mPut)[0] = command;
+    reinterpret_cast<uint16_t *>(mPut)[1] = sizeInBytes;
+    mPut += ((sizeInBytes + 3) & ~3) + 4;
+    //dumpState("commit 2");
+    mSignalToWorker.set();
+}
+
+void LocklessCommandFifo::commitSync(uint32_t command, uint32_t sizeInBytes)
+{
+    commit(command, sizeInBytes);
+    flush();
+}
+
+void LocklessCommandFifo::flush()
+{
+    //dumpState("flush 1");
+    while(mPut != mGet) {
+        mSignalToControl.wait();
+    }
+    //dumpState("flush 2");
+}
+
+const void * LocklessCommandFifo::get(uint32_t *command, uint32_t *bytesData)
+{
+    while(1) {
+        //dumpState("get");
+        while(isEmpty()) {
+            mSignalToControl.set();
+            mSignalToWorker.wait();
+        }
+
+        *command = reinterpret_cast<const uint16_t *>(mGet)[0];
+        *bytesData = reinterpret_cast<const uint16_t *>(mGet)[1];
+        if (*command) {
+            // non-zero command is valid
+            return mGet+4;
+        }
+    
+        // zero command means reset to beginning.
+        mGet = mBuffer;
+    }
+}
+
+void LocklessCommandFifo::next()
+{
+    uint32_t bytes = reinterpret_cast<const uint16_t *>(mGet)[1];
+    mGet += ((bytes + 3) & ~3) + 4;
+    if (isEmpty()) {
+        mSignalToControl.set();
+    }
+    //dumpState("next");
+}
+
+void LocklessCommandFifo::makeSpace(uint32_t bytes)
+{
+    //dumpState("make space");
+    if ((mPut+bytes) > mEnd) {
+        // Need to loop regardless of where get is.
+        while((mGet > mPut) && (mBuffer+4 >= mGet)) {
+            sleep(1);
+        }
+
+        // Toss in a reset then the normal wait for space will do the rest.
+        reinterpret_cast<uint16_t *>(mPut)[0] = 0;
+        reinterpret_cast<uint16_t *>(mPut)[1] = 0;
+        mPut = mBuffer;
+    }
+
+    // it will fit here so we just need to wait for space.
+    while(getFreeSpace() < bytes) {
+        sleep(1);
+    }
+    
+}
+
+void LocklessCommandFifo::dumpState(const char *s) const
+{
+    LOGV("%s  put %p, get %p,  buf %p,  end %p", s, mPut, mGet, mBuffer, mEnd);
+}
+
+LocklessCommandFifo::Signal::Signal()
+{
+    mSet = true;
+}
+
+LocklessCommandFifo::Signal::~Signal()
+{
+    pthread_mutex_destroy(&mMutex);
+    pthread_cond_destroy(&mCondition);
+}
+
+bool LocklessCommandFifo::Signal::init()
+{
+    int status = pthread_mutex_init(&mMutex, NULL);
+    if (status) {
+        LOGE("LocklessFifo mutex init failure");
+        return false;
+    }
+
+    status = pthread_cond_init(&mCondition, NULL);
+    if (status) {
+        LOGE("LocklessFifo condition init failure");
+        pthread_mutex_destroy(&mMutex);
+        return false;
+    }
+
+    return true;
+}
+
+void LocklessCommandFifo::Signal::set()
+{
+    int status;
+
+    status = pthread_mutex_lock(&mMutex);
+    if (status) {
+        LOGE("LocklessCommandFifo: error %i locking for set condition.", status);
+        return;
+    }
+
+    mSet = true;
+
+    status = pthread_cond_signal(&mCondition);
+    if (status) {
+        LOGE("LocklessCommandFifo: error %i on set condition.", status);
+    }
+
+    status = pthread_mutex_unlock(&mMutex);
+    if (status) {
+        LOGE("LocklessCommandFifo: error %i unlocking for set condition.", status);
+    }
+}
+
+void LocklessCommandFifo::Signal::wait()
+{
+    int status;
+
+    status = pthread_mutex_lock(&mMutex);
+    if (status) {
+        LOGE("LocklessCommandFifo: error %i locking for condition.", status);
+        return;
+    }
+
+    if (!mSet) {
+        status = pthread_cond_wait(&mCondition, &mMutex);
+        if (status) {
+            LOGE("LocklessCommandFifo: error %i waiting on condition.", status);
+        }
+    }
+    mSet = false;
+
+    status = pthread_mutex_unlock(&mMutex);
+    if (status) {
+        LOGE("LocklessCommandFifo: error %i unlocking for condition.", status);
+    }
+}
+
diff --git a/libs/rs/rsLocklessFifo.h b/libs/rs/rsLocklessFifo.h
new file mode 100644
index 0000000..abeddf7
--- /dev/null
+++ b/libs/rs/rsLocklessFifo.h
@@ -0,0 +1,89 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_LOCKLESS_FIFO_H
+#define ANDROID_RS_LOCKLESS_FIFO_H
+
+
+#include "rsUtils.h"
+
+namespace android {
+
+
+// A simple FIFO to be used as a producer / consumer between two
+// threads.  One is writer and one is reader.  The common cases
+// will not require locking.  It is not threadsafe for multiple 
+// readers or writers by design.
+
+class LocklessCommandFifo 
+{
+public:
+    bool init(uint32_t size);
+
+    LocklessCommandFifo();
+    ~LocklessCommandFifo();
+
+
+protected:
+    class Signal {
+    public:
+        Signal();
+        ~Signal();
+
+        bool init();
+
+        void set();
+        void wait();
+
+    protected:
+        bool mSet;
+        pthread_mutex_t mMutex;
+        pthread_cond_t mCondition;
+    };
+
+    uint8_t * volatile mPut;
+    uint8_t * volatile mGet;
+    uint8_t * mBuffer;
+    uint8_t * mEnd;
+    uint8_t mSize;
+
+    Signal mSignalToWorker;
+    Signal mSignalToControl;
+
+
+
+public:
+    void * reserve(uint32_t bytes);
+    void commit(uint32_t command, uint32_t bytes);
+    void commitSync(uint32_t command, uint32_t bytes);
+
+    void flush();
+    const void * get(uint32_t *command, uint32_t *bytesData);
+    void next();
+
+    void makeSpace(uint32_t bytes);
+
+    bool isEmpty() const;
+    uint32_t getFreeSpace() const;
+
+
+private:
+    void dumpState(const char *) const;
+};
+
+
+}
+#endif
diff --git a/libs/rs/rsMatrix.cpp b/libs/rs/rsMatrix.cpp
new file mode 100644
index 0000000..5f68197
--- /dev/null
+++ b/libs/rs/rsMatrix.cpp
@@ -0,0 +1,159 @@
+/*
+ * 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.
+ */
+
+#include "rsMatrix.h"
+
+#include "stdlib.h"
+#include "string.h"
+#include "math.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+
+
+void Matrix::loadIdentity()
+{
+    set(0, 0, 1);
+    set(1, 0, 0);
+    set(2, 0, 0);
+    set(3, 0, 0);
+
+    set(0, 1, 0);
+    set(1, 1, 1);
+    set(2, 1, 0);
+    set(3, 1, 0);
+
+    set(0, 2, 0);
+    set(1, 2, 0);
+    set(2, 2, 1);
+    set(3, 2, 0);
+
+    set(0, 3, 0);
+    set(1, 3, 0);
+    set(2, 3, 0);
+    set(3, 3, 1);
+}
+
+void Matrix::load(const float *v)
+{
+    memcpy(m, v, sizeof(m));
+}
+
+void Matrix::load(const Matrix *v)
+{
+    memcpy(m, v->m, sizeof(m));
+}
+
+void Matrix::loadRotate(float rot, float x, float y, float z)
+{
+    float c, s;
+    m[3] = 0;
+    m[7] = 0;
+    m[11]= 0;
+    m[12]= 0;
+    m[13]= 0;
+    m[14]= 0;
+    m[15]= 1;
+    rot *= float(M_PI / 180.0f);
+    c = cosf(rot);
+    s = sinf(rot);
+
+    const float len = sqrtf(x*x + y*y + z*z);
+    if (!(len != 1)) {
+        const float recipLen = 1.f / len;
+        x *= recipLen;
+        y *= recipLen;
+        z *= recipLen;
+    }
+    const float nc = 1.0f - c;
+    const float xy = x * y;
+    const float yz = y * z;
+    const float zx = z * x;
+    const float xs = x * s;
+    const float ys = y * s;
+    const float zs = z * s;		
+    m[ 0] = x*x*nc +  c;
+    m[ 4] =  xy*nc - zs;
+    m[ 8] =  zx*nc + ys;
+    m[ 1] =  xy*nc + zs;
+    m[ 5] = y*y*nc +  c;
+    m[ 9] =  yz*nc - xs;
+    m[ 2] =  zx*nc - ys;
+    m[ 6] =  yz*nc + xs;
+    m[10] = z*z*nc +  c;
+}
+
+void Matrix::loadScale(float x, float y, float z)
+{
+    loadIdentity();
+    m[0] = x;
+    m[5] = y;
+    m[10] = z;
+}
+
+void Matrix::loadTranslate(float x, float y, float z)
+{
+    loadIdentity();
+    m[12] = x;
+    m[13] = y;
+    m[14] = z;
+}
+
+void Matrix::loadMultiply(const Matrix *lhs, const Matrix *rhs)
+{
+    for (int i=0 ; i<4 ; i++) {
+        float ri0 = 0;
+        float ri1 = 0;
+        float ri2 = 0;
+        float ri3 = 0;
+        for (int j=0 ; j<4 ; j++) {
+            const float rhs_ij = rhs->get(i,j);
+            ri0 += lhs->get(j,0) * rhs_ij;
+            ri1 += lhs->get(j,1) * rhs_ij;
+            ri2 += lhs->get(j,2) * rhs_ij;
+            ri3 += lhs->get(j,3) * rhs_ij;
+        }
+        set(i,0, ri0);
+        set(i,1, ri1);
+        set(i,2, ri2);
+        set(i,3, ri3);
+    }
+}
+
+void Matrix::loadOrtho(float l, float r, float b, float t, float n, float f) {
+    loadIdentity();
+    m[0] = 2 / (r - l);
+    m[5] = 2 / (t - b);
+    m[10]= -2 / (f - n);
+    m[12]= -(r + l) / (r - l);
+    m[13]= -(t + b) / (t - b);
+    m[14]= -(f + n) / (f - n);
+}
+
+void Matrix::loadFrustum(float l, float r, float b, float t, float n, float f) {
+    loadIdentity();
+    m[0] = 2 * n / (r - l);
+    m[5] = 2 * n / (t - b);
+    m[8] = (r + l) / (r - l);
+    m[9] = (t + b) / (t - b);
+    m[10]= -(f + n) / (f - n);
+    m[11]= -1;
+    m[14]= -2*f*n / (f - n);
+    m[15]= 0;
+}
+
+
diff --git a/libs/rs/rsMatrix.h b/libs/rs/rsMatrix.h
new file mode 100644
index 0000000..7dc4165
--- /dev/null
+++ b/libs/rs/rsMatrix.h
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_MATRIX_H
+#define ANDROID_RS_MATRIX_H
+
+
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+struct Matrix 
+{
+    float m[16];
+
+    inline float get(int i, int j) const {
+        return m[i*4 + j];
+    }
+
+    inline void set(int i, int j, float v) {
+        m[i*4 + j] = v;
+    }
+
+    void loadIdentity();
+    void load(const float *);
+    void load(const Matrix *);
+
+    void loadRotate(float rot, float x, float y, float z);
+    void loadScale(float x, float y, float z);
+    void loadTranslate(float x, float y, float z);
+    void loadMultiply(const Matrix *lhs, const Matrix *rhs);
+
+    void loadOrtho(float l, float r, float b, float t, float n, float f);
+    void loadFrustum(float l, float r, float b, float t, float n, float f);
+
+    void multiply(const Matrix *rhs) {
+        Matrix tmp;
+        tmp.loadMultiply(this, rhs);
+        load(&tmp);
+    }
+    void rotate(float rot, float x, float y, float z) {
+        Matrix tmp;
+        tmp.loadRotate(rot, x, y, z);
+        multiply(&tmp);
+    }
+    void scale(float x, float y, float z) {
+        Matrix tmp;
+        tmp.loadScale(x, y, z);
+        multiply(&tmp);
+    }
+    void translate(float x, float y, float z) {
+        Matrix tmp;
+        tmp.loadTranslate(x, y, z);
+        multiply(&tmp);
+    }
+
+
+
+};
+    
+
+
+}
+}
+
+
+
+
+#endif
+
+
+
+
diff --git a/libs/rs/rsMesh.cpp b/libs/rs/rsMesh.cpp
new file mode 100644
index 0000000..aeb52ed
--- /dev/null
+++ b/libs/rs/rsMesh.cpp
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+Mesh::Mesh()
+{
+    mVerticies = NULL;
+    mVerticiesCount = 0;
+    mPrimitives = NULL;
+    mPrimitivesCount = 0;
+}
+
+Mesh::~Mesh()
+{
+}
+
+
+
+MeshContext::MeshContext()
+{
+}
+
+MeshContext::~MeshContext()
+{
+}
+
diff --git a/libs/rs/rsMesh.h b/libs/rs/rsMesh.h
new file mode 100644
index 0000000..be207a3
--- /dev/null
+++ b/libs/rs/rsMesh.h
@@ -0,0 +1,90 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_MESH_H
+#define ANDROID_RS_MESH_H
+
+
+#include "RenderScript.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+
+// An element is a group of Components that occupies one cell in a structure.
+class Mesh : public ObjectBase
+{
+public:
+    Mesh();
+    ~Mesh();
+
+    struct Verticies_t
+    {
+        Allocation ** mAllocations;
+        uint32_t mAllocationCount;
+
+        size_t mVertexDataSize;
+
+        size_t mOffsetCoord;
+        size_t mOffsetTex;
+        size_t mOffsetNorm;
+    
+        size_t mSizeCoord;
+        size_t mSizeTex;
+        size_t mSizeNorm;
+
+        uint32_t mBufferObject;
+    };
+
+    struct Primitive_t
+    {
+        RsPrimitive mType;
+        Verticies_t *mVerticies;
+
+        uint32_t mIndexCount;
+        uint16_t *mIndicies;
+
+        uint32_t mRestartCounts;
+        uint16_t *mRestarts;
+    };
+
+    Verticies_t * mVerticies;
+    uint32_t mVerticiesCount;
+
+    Primitive_t ** mPrimitives;
+    uint32_t mPrimitivesCount;
+
+
+
+    void analyzeElement();
+protected:
+};
+
+class MeshContext
+{
+public:
+    MeshContext();
+    ~MeshContext();
+
+};
+
+
+}
+}
+#endif //ANDROID_RS_TRIANGLE_MESH_H
+
+
diff --git a/libs/rs/rsObjectBase.cpp b/libs/rs/rsObjectBase.cpp
new file mode 100644
index 0000000..3219c39
--- /dev/null
+++ b/libs/rs/rsObjectBase.cpp
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+#include "rsObjectBase.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+ObjectBase::ObjectBase()
+{
+    mRefCount = 0;
+    mName = NULL;
+}
+
+ObjectBase::~ObjectBase()
+{
+    rsAssert(!mRefCount);
+}
+
+void ObjectBase::incRef() const
+{
+    mRefCount ++;
+    //LOGV("ObjectBase %p inc ref %i", this, mRefCount);
+}
+
+void ObjectBase::decRef() const
+{
+    rsAssert(mRefCount > 0);
+    mRefCount --;
+    //LOGV("ObjectBase %p dec ref %i", this, mRefCount);
+    if (!mRefCount) {
+        delete this;
+    }
+}
+
+void ObjectBase::setName(const char *name)
+{
+    delete mName;
+    mName = NULL;
+    if (name) {
+        mName = new char[strlen(name) +1];
+        strcpy(mName, name);
+    }
+}
+
+void ObjectBase::setName(const char *name, uint32_t len)
+{
+    delete mName;
+    mName = NULL;
+    if (name) {
+        mName = new char[len + 1];
+        memcpy(mName, name, len);
+        mName[len] = 0;
+    }
+}
+
diff --git a/libs/rs/rsObjectBase.h b/libs/rs/rsObjectBase.h
new file mode 100644
index 0000000..b2c3338
--- /dev/null
+++ b/libs/rs/rsObjectBase.h
@@ -0,0 +1,114 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_OBJECT_BASE_H
+#define ANDROID_RS_OBJECT_BASE_H
+
+#include "rsUtils.h"
+
+
+namespace android {
+namespace renderscript {
+
+// An element is a group of Components that occupies one cell in a structure.
+class ObjectBase
+{
+public:
+    ObjectBase();
+    virtual ~ObjectBase();
+
+    void incRef() const;
+    void decRef() const;
+
+    const char * getName() const {
+        return mName;
+    }
+    void setName(const char *);
+    void setName(const char *, uint32_t len);
+
+private:
+    char * mName;
+    mutable int32_t mRefCount;
+
+
+};
+
+template<class T> 
+class ObjectBaseRef 
+{
+public:
+    ObjectBaseRef() {
+        mRef = NULL;
+    }
+
+    ObjectBaseRef(const ObjectBaseRef &ref) {
+        mRef = ref.get();
+        if (mRef) {
+            mRef->incRef();
+        }
+    }
+
+    ObjectBaseRef(T *ref) {
+        mRef = ref;
+        if (mRef) {
+            ref->incRef();
+        }
+    }
+
+    ~ObjectBaseRef() {
+        clear();
+    }
+
+    void set(T *ref) {
+        if (mRef != ref) {
+            clear();
+            mRef = ref;
+            if (mRef) {
+                ref->incRef();
+            }
+        }
+    }
+
+    void set(const ObjectBaseRef &ref) {
+        set(ref.mRef);
+    }
+
+    void clear() {
+        if (mRef) {
+            mRef->decRef();
+        }
+        mRef = NULL;
+    }
+
+    inline T * get() const {
+        return mRef;
+    }
+
+    inline T * operator-> () const { 
+        return mRef;  
+    }
+
+protected:
+    T * mRef;
+
+};
+
+
+}
+}
+
+#endif //ANDROID_RS_OBJECT_BASE_H
+
diff --git a/libs/rs/rsProgram.cpp b/libs/rs/rsProgram.cpp
new file mode 100644
index 0000000..5a83fb7
--- /dev/null
+++ b/libs/rs/rsProgram.cpp
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+#include "rsProgram.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+
+Program::Program(Element *in, Element *out)
+{
+    mElementIn.set(in);
+    mElementOut.set(out);
+
+
+}
+
+Program::~Program()
+{
+}
+
+
+void Program::setAllocation(Allocation *alloc)
+{
+    mConstants.set(alloc);
+    mDirty = true;
+}
+
+void Program::setupGL()
+{
+
+}
+
+
diff --git a/libs/rs/rsProgram.h b/libs/rs/rsProgram.h
new file mode 100644
index 0000000..913fdd2
--- /dev/null
+++ b/libs/rs/rsProgram.h
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_PROGRAM_H
+#define ANDROID_RS_PROGRAM_H
+
+#include "rsObjectBase.h"
+#include "rsElement.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+
+
+class Program : public ObjectBase
+{
+public:
+    Program(Element *in, Element *out);
+    virtual ~Program();
+
+
+    void setAllocation(Allocation *);
+
+    virtual void setupGL();
+
+protected:
+    // Components not listed in "in" will be passed though
+    // unless overwritten by components in out.
+    ObjectBaseRef<Element> mElementIn;
+    ObjectBaseRef<Element> mElementOut;
+
+    ObjectBaseRef<Allocation> mConstants;
+
+    bool mDirty;
+
+};
+
+
+
+}
+}
+#endif
+
+
+
diff --git a/libs/rs/rsProgramFragment.cpp b/libs/rs/rsProgramFragment.cpp
new file mode 100644
index 0000000..628f93e
--- /dev/null
+++ b/libs/rs/rsProgramFragment.cpp
@@ -0,0 +1,251 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+#include "rsProgramFragment.h"
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+using namespace android;
+using namespace android::renderscript;
+
+
+ProgramFragment::ProgramFragment(Element *in, Element *out) :
+    Program(in, out)
+{
+    for (uint32_t ct=0; ct < MAX_TEXTURE; ct++) {
+        mEnvModes[ct] = RS_TEX_ENV_MODE_REPLACE;
+        mTextureDimensions[ct] = 2;
+    }
+    mTextureEnableMask = 0;
+    mEnvModes[1] = RS_TEX_ENV_MODE_DECAL;
+}
+
+ProgramFragment::~ProgramFragment()
+{
+}
+
+void ProgramFragment::setupGL()
+{
+    for (uint32_t ct=0; ct < MAX_TEXTURE; ct++) {
+        glActiveTexture(GL_TEXTURE0 + ct);
+        if (!(mTextureEnableMask & (1 << ct)) || !mTextures[ct].get()) {
+            glDisable(GL_TEXTURE_2D);
+            continue;
+        }
+
+        glEnable(GL_TEXTURE_2D);
+        glBindTexture(GL_TEXTURE_2D, mTextures[ct]->getTextureID());
+
+        switch(mEnvModes[ct]) {
+        case RS_TEX_ENV_MODE_REPLACE:
+            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+            break;
+        case RS_TEX_ENV_MODE_MODULATE:
+            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+            break;
+        case RS_TEX_ENV_MODE_DECAL:
+            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
+            break;
+        }
+
+        if (mSamplers[ct].get()) {
+            mSamplers[ct]->setupGL();
+        } else {
+            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+        }
+
+        // Gross hack.
+        if (ct == 2) {
+            glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
+
+            glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_ADD);
+            glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
+            glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_TEXTURE);
+            glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
+            glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
+
+            glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_ADD);
+            glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
+            glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_ALPHA, GL_TEXTURE);
+            glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
+            glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA);
+        }
+    }
+
+
+    glActiveTexture(GL_TEXTURE0);
+}
+
+
+void ProgramFragment::bindTexture(uint32_t slot, Allocation *a)
+{
+    if (slot >= MAX_TEXTURE) {
+        LOGE("Attempt to bind a texture to a slot > MAX_TEXTURE");
+        return;
+    }
+
+    //LOGE("bindtex %i %p", slot, a);
+    mTextures[slot].set(a);
+}
+
+void ProgramFragment::bindSampler(uint32_t slot, Sampler *s)
+{
+    if (slot >= MAX_TEXTURE) {
+        LOGE("Attempt to bind a Sampler to a slot > MAX_TEXTURE");
+        return;
+    }
+
+    mSamplers[slot].set(s);
+}
+
+void ProgramFragment::setType(uint32_t slot, const Element *e, uint32_t dim)
+{
+    if (slot >= MAX_TEXTURE) {
+        LOGE("Attempt to setType to a slot > MAX_TEXTURE");
+        return;
+    }
+
+    if (dim >= 4) {
+        LOGE("Attempt to setType to a dimension > 3");
+        return;
+    }
+
+    mTextureFormats[slot].set(e);
+    mTextureDimensions[slot] = dim;
+}
+
+void ProgramFragment::setEnvMode(uint32_t slot, RsTexEnvMode env)
+{
+    if (slot >= MAX_TEXTURE) {
+        LOGE("Attempt to setEnvMode to a slot > MAX_TEXTURE");
+        return;
+    }
+
+    mEnvModes[slot] = env;
+}
+
+void ProgramFragment::setTexEnable(uint32_t slot, bool enable)
+{
+    if (slot >= MAX_TEXTURE) {
+        LOGE("Attempt to setEnvMode to a slot > MAX_TEXTURE");
+        return;
+    }
+
+    uint32_t bit = 1 << slot;
+    mTextureEnableMask &= ~bit;
+    if (enable) {
+        mTextureEnableMask |= bit;
+    }
+}
+
+
+
+ProgramFragmentState::ProgramFragmentState()
+{
+    mPF = NULL;
+}
+
+ProgramFragmentState::~ProgramFragmentState()
+{
+    delete mPF;
+
+}
+
+void ProgramFragmentState::init(Context *rsc, int32_t w, int32_t h)
+{
+    ProgramFragment *pf = new ProgramFragment(NULL, NULL);
+    mDefault.set(pf);
+}
+
+
+namespace android {
+namespace renderscript {
+
+void rsi_ProgramFragmentBegin(Context * rsc, RsElement in, RsElement out)
+{
+    delete rsc->mStateFragment.mPF;
+    rsc->mStateFragment.mPF = new ProgramFragment((Element *)in, (Element *)out);
+}
+
+void rsi_ProgramFragmentBindTexture(Context *rsc, RsProgramFragment vpf, uint32_t slot, RsAllocation a)
+{
+    ProgramFragment *pf = static_cast<ProgramFragment *>(vpf);
+    pf->bindTexture(slot, static_cast<Allocation *>(a));
+    if (pf == rsc->getFragment()) {
+        pf->setupGL();
+    }
+}
+
+void rsi_ProgramFragmentBindSampler(Context *rsc, RsProgramFragment vpf, uint32_t slot, RsSampler s)
+{
+    ProgramFragment *pf = static_cast<ProgramFragment *>(vpf);
+    pf->bindSampler(slot, static_cast<Sampler *>(s));
+
+    if (pf == rsc->getFragment()) {
+        pf->setupGL();
+    }
+}
+
+void rsi_ProgramFragmentSetType(Context *rsc, uint32_t slot, RsType vt)
+{
+    const Type *t = static_cast<const Type *>(vt);
+    uint32_t dim = 1;
+    if (t->getDimY()) {
+        dim ++;
+        if (t->getDimZ()) {
+            dim ++;
+        }
+    }
+
+    rsc->mStateFragment.mPF->setType(slot, t->getElement(), dim);
+}
+
+void rsi_ProgramFragmentSetEnvMode(Context *rsc, uint32_t slot, RsTexEnvMode env)
+{
+    rsc->mStateFragment.mPF->setEnvMode(slot, env);
+}
+
+void rsi_ProgramFragmentSetTexEnable(Context *rsc, uint32_t slot, bool enable)
+{
+    rsc->mStateFragment.mPF->setTexEnable(slot, enable);
+}
+
+RsProgramFragment rsi_ProgramFragmentCreate(Context *rsc)
+{
+    ProgramFragment *pf = rsc->mStateFragment.mPF;
+    pf->incRef();
+    rsc->mStateFragment.mPF = 0;
+    return pf;
+}
+
+void rsi_ProgramFragmentDestroy(Context *rsc, RsProgramFragment vpf)
+{
+    ProgramFragment *pf = (ProgramFragment *)vpf;
+    if (pf->getName()) {
+        rsc->removeName(pf);
+    }
+    pf->decRef();
+}
+
+
+}
+}
+
diff --git a/libs/rs/rsProgramFragment.h b/libs/rs/rsProgramFragment.h
new file mode 100644
index 0000000..896d8dd
--- /dev/null
+++ b/libs/rs/rsProgramFragment.h
@@ -0,0 +1,99 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_PROGRAM_FRAGMENT_H
+#define ANDROID_RS_PROGRAM_FRAGMENT_H
+
+#include "rsProgram.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+
+class ProgramFragment : public Program
+{
+public:
+    const static uint32_t MAX_TEXTURE = 2;
+    const static uint32_t MAX_CONSTANTS = 2;
+
+
+
+    ProgramFragment(Element *in, Element *out);
+    virtual ~ProgramFragment();
+
+    virtual void setupGL();
+
+
+
+    void bindTexture(uint32_t slot, Allocation *);
+    void bindSampler(uint32_t slot, Sampler *);
+    void setType(uint32_t slot, const Element *, uint32_t dim);
+
+    void setEnvMode(uint32_t slot, RsTexEnvMode);
+    void setTexEnable(uint32_t slot, bool);
+
+
+
+protected:
+    // The difference between Textures and Constants is how they are accessed
+    // Texture lookups go though a sampler which in effect converts normalized
+    // coordinates into type specific.  Multiple samples may also be taken
+    // and filtered.
+    // 
+    // Constants are strictly accessed by programetic loads.
+    ObjectBaseRef<Allocation> mTextures[MAX_TEXTURE];
+    ObjectBaseRef<Sampler> mSamplers[MAX_TEXTURE];
+    ObjectBaseRef<const Element> mTextureFormats[MAX_TEXTURE];
+    uint32_t mTextureDimensions[MAX_TEXTURE];
+
+
+    ObjectBaseRef<Allocation> mConstants[MAX_CONSTANTS];
+    ObjectBaseRef<Type> mConstantTypes[MAX_CONSTANTS];
+
+
+    // Hacks to create a program for now
+    RsTexEnvMode mEnvModes[MAX_TEXTURE];
+    uint32_t mTextureEnableMask;
+
+
+
+
+
+};
+
+class ProgramFragmentState 
+{
+public:
+    ProgramFragmentState();
+    ~ProgramFragmentState();
+
+    ProgramFragment *mPF;
+    void init(Context *rsc, int32_t w, int32_t h);
+
+    ObjectBaseRef<Type> mTextureTypes[ProgramFragment::MAX_TEXTURE];
+    ObjectBaseRef<ProgramFragment> mDefault;
+    Vector<ProgramFragment *> mPrograms;
+};
+
+
+}
+}
+#endif
+
+
+
+
diff --git a/libs/rs/rsProgramFragmentStore.cpp b/libs/rs/rsProgramFragmentStore.cpp
new file mode 100644
index 0000000..9ee270f
--- /dev/null
+++ b/libs/rs/rsProgramFragmentStore.cpp
@@ -0,0 +1,272 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+#include "rsProgramFragmentStore.h"
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+using namespace android;
+using namespace android::renderscript;
+
+
+ProgramFragmentStore::ProgramFragmentStore(Element *in, Element *out) :
+    Program(in, out)
+{
+    mDitherEnable = true;
+    mBlendEnable = false;
+    mColorRWriteEnable = true;
+    mColorGWriteEnable = true;
+    mColorBWriteEnable = true;
+    mColorAWriteEnable = true;
+    mBlendSrc = GL_ONE;
+    mBlendDst = GL_ZERO;
+
+
+    mDepthTestEnable = false;
+    mDepthWriteEnable = true;
+    mDepthFunc = GL_LESS;
+
+
+}
+
+ProgramFragmentStore::~ProgramFragmentStore()
+{
+}
+
+void ProgramFragmentStore::setupGL()
+{
+    glColorMask(mColorRWriteEnable,
+                mColorGWriteEnable,
+                mColorBWriteEnable,
+                mColorAWriteEnable);
+    if (mBlendEnable) {
+        glEnable(GL_BLEND);
+        glBlendFunc(mBlendSrc, mBlendDst);
+    } else {
+        glDisable(GL_BLEND);
+    }
+
+    //LOGE("pfs  %i, %i, %x", mDepthWriteEnable, mDepthTestEnable, mDepthFunc);
+
+    glDepthMask(mDepthWriteEnable);
+    if(mDepthTestEnable || mDepthWriteEnable) {
+        glEnable(GL_DEPTH_TEST);
+        glDepthFunc(mDepthFunc);
+    } else {
+        glDisable(GL_DEPTH_TEST);
+    }
+
+    if (mDitherEnable) {
+        glEnable(GL_DITHER);
+    } else {
+        glDisable(GL_DITHER);
+    }
+
+
+}
+
+void ProgramFragmentStore::setDitherEnable(bool enable)
+{
+    mDitherEnable = enable;
+}
+
+void ProgramFragmentStore::setDepthFunc(RsDepthFunc func)
+{
+    mDepthTestEnable = true;
+
+    switch(func) {
+    case RS_DEPTH_FUNC_ALWAYS:
+        mDepthTestEnable = false;
+        mDepthFunc = GL_ALWAYS;
+        break;
+    case RS_DEPTH_FUNC_LESS:
+        mDepthFunc = GL_LESS;
+        break;
+    case RS_DEPTH_FUNC_LEQUAL:
+        mDepthFunc = GL_LEQUAL;
+        break;
+    case RS_DEPTH_FUNC_GREATER:
+        mDepthFunc = GL_GREATER;
+        break;
+    case RS_DEPTH_FUNC_GEQUAL:
+        mDepthFunc = GL_GEQUAL;
+        break;
+    case RS_DEPTH_FUNC_EQUAL:
+        mDepthFunc = GL_EQUAL;
+        break;
+    case RS_DEPTH_FUNC_NOTEQUAL:
+        mDepthFunc = GL_NOTEQUAL;
+        break;
+    }
+}
+
+void ProgramFragmentStore::setDepthMask(bool mask)
+{
+    mDepthWriteEnable = mask;
+}
+
+void ProgramFragmentStore::setBlendFunc(RsBlendSrcFunc src, RsBlendDstFunc dst)
+{
+    mBlendEnable = true;
+    if ((src == RS_BLEND_SRC_ONE) && 
+        (dst == RS_BLEND_DST_ZERO)) {
+        mBlendEnable = false;
+    }
+
+    switch(src) {
+    case RS_BLEND_SRC_ZERO:
+        mBlendSrc = GL_ZERO;
+        break;
+    case RS_BLEND_SRC_ONE:
+        mBlendSrc = GL_ONE;
+        break;
+    case RS_BLEND_SRC_DST_COLOR:
+        mBlendSrc = GL_DST_COLOR;
+        break;
+    case RS_BLEND_SRC_ONE_MINUS_DST_COLOR:
+        mBlendSrc = GL_ONE_MINUS_DST_COLOR;
+        break;
+    case RS_BLEND_SRC_SRC_ALPHA:
+        mBlendSrc = GL_SRC_ALPHA;
+        break;
+    case RS_BLEND_SRC_ONE_MINUS_SRC_ALPHA:
+        mBlendSrc = GL_ONE_MINUS_SRC_ALPHA;
+        break;
+    case RS_BLEND_SRC_DST_ALPHA:
+        mBlendSrc = GL_DST_ALPHA;
+        break;
+    case RS_BLEND_SRC_ONE_MINUS_DST_ALPHA:
+        mBlendSrc = GL_ONE_MINUS_DST_ALPHA;
+        break;
+    case RS_BLEND_SRC_SRC_ALPHA_SATURATE:
+        mBlendSrc = GL_SRC_ALPHA_SATURATE;
+        break;
+    }
+
+    switch(dst) {
+    case RS_BLEND_DST_ZERO:
+        mBlendDst = GL_ZERO;
+        break;
+    case RS_BLEND_DST_ONE:
+        mBlendDst = GL_ONE;
+        break;
+    case RS_BLEND_DST_SRC_COLOR:
+        mBlendDst = GL_SRC_COLOR;
+        break;
+    case RS_BLEND_DST_ONE_MINUS_SRC_COLOR:
+        mBlendDst = GL_ONE_MINUS_SRC_COLOR;
+        break;
+    case RS_BLEND_DST_SRC_ALPHA:
+        mBlendDst = GL_SRC_ALPHA;
+        break;
+    case RS_BLEND_DST_ONE_MINUS_SRC_ALPHA:
+        mBlendDst = GL_ONE_MINUS_SRC_ALPHA;
+        break;
+    case RS_BLEND_DST_DST_ALPHA:
+        mBlendDst = GL_DST_ALPHA;
+        break;
+    case RS_BLEND_DST_ONE_MINUS_DST_ALPHA:
+        mBlendDst = GL_ONE_MINUS_DST_ALPHA;
+        break;
+    }
+}
+
+void ProgramFragmentStore::setColorMask(bool r, bool g, bool b, bool a)
+{
+    mColorRWriteEnable = r;
+    mColorGWriteEnable = g;
+    mColorBWriteEnable = b;
+    mColorAWriteEnable = a;
+}
+
+
+ProgramFragmentStoreState::ProgramFragmentStoreState()
+{
+    mPFS = NULL;
+}
+
+ProgramFragmentStoreState::~ProgramFragmentStoreState()
+{
+    delete mPFS;
+
+}
+
+void ProgramFragmentStoreState::init(Context *rsc, int32_t w, int32_t h)
+{
+    ProgramFragmentStore *pfs = new ProgramFragmentStore(NULL, NULL);
+    mDefault.set(pfs);
+}
+
+
+namespace android {
+namespace renderscript {
+
+void rsi_ProgramFragmentStoreBegin(Context * rsc, RsElement in, RsElement out)
+{
+    delete rsc->mStateFragmentStore.mPFS;
+    rsc->mStateFragmentStore.mPFS = new ProgramFragmentStore((Element *)in, (Element *)out);
+
+}
+
+void rsi_ProgramFragmentStoreDepthFunc(Context *rsc, RsDepthFunc func)
+{
+    rsc->mStateFragmentStore.mPFS->setDepthFunc(func);
+}
+
+void rsi_ProgramFragmentStoreDepthMask(Context *rsc, bool mask)
+{
+    rsc->mStateFragmentStore.mPFS->setDepthMask(mask);
+}
+
+void rsi_ProgramFragmentStoreColorMask(Context *rsc, bool r, bool g, bool b, bool a)
+{
+    rsc->mStateFragmentStore.mPFS->setColorMask(r, g, b, a);
+}
+
+void rsi_ProgramFragmentStoreBlendFunc(Context *rsc, RsBlendSrcFunc src, RsBlendDstFunc dst)
+{
+    rsc->mStateFragmentStore.mPFS->setBlendFunc(src, dst);
+}
+
+RsProgramFragmentStore rsi_ProgramFragmentStoreCreate(Context *rsc)
+{
+    ProgramFragmentStore *pfs = rsc->mStateFragmentStore.mPFS;
+    pfs->incRef();
+    rsc->mStateFragmentStore.mPFS = 0;
+    return pfs;
+}
+
+void rsi_ProgramFragmentStoreDither(Context *rsc, bool enable)
+{
+    rsc->mStateFragmentStore.mPFS->setDitherEnable(enable);
+}
+
+void rsi_ProgramFragmentStoreDestroy(Context *rsc, RsProgramFragmentStore vpfs)
+{
+    ProgramFragmentStore *pfs = (ProgramFragmentStore *)vpfs;
+    if (pfs->getName()) {
+        rsc->removeName(pfs);
+    }
+    pfs->decRef();
+}
+
+
+
+
+}
+}
diff --git a/libs/rs/rsProgramFragmentStore.h b/libs/rs/rsProgramFragmentStore.h
new file mode 100644
index 0000000..bd3a9f4
--- /dev/null
+++ b/libs/rs/rsProgramFragmentStore.h
@@ -0,0 +1,89 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_PROGRAM_FRAGMENT_STORE_H
+#define ANDROID_RS_PROGRAM_FRAGMENT_STORE_H
+
+#include "rsProgram.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+
+class ProgramFragmentStore : public Program
+{
+public:
+
+
+
+    ProgramFragmentStore(Element *in, Element *out);
+    virtual ~ProgramFragmentStore();
+
+    virtual void setupGL();
+
+
+    void setDepthFunc(RsDepthFunc);
+    void setDepthMask(bool);
+
+    void setBlendFunc(RsBlendSrcFunc src, RsBlendDstFunc dst);
+    void setColorMask(bool, bool, bool, bool);
+
+    void setDitherEnable(bool);
+
+protected:
+    bool mDitherEnable;
+
+    bool mBlendEnable;
+    bool mColorRWriteEnable;
+    bool mColorGWriteEnable;
+    bool mColorBWriteEnable;
+    bool mColorAWriteEnable;
+    int32_t mBlendSrc;
+    int32_t mBlendDst;
+
+
+
+    bool mDepthTestEnable;
+    bool mDepthWriteEnable;
+    int32_t mDepthFunc;
+
+
+
+    bool mStencilTestEnable;
+
+
+
+};
+
+class ProgramFragmentStoreState 
+{
+public:
+    ProgramFragmentStoreState();
+    ~ProgramFragmentStoreState();
+    void init(Context *rsc, int32_t w, int32_t h);
+
+    ObjectBaseRef<ProgramFragmentStore> mDefault;
+    ProgramFragmentStore *mPFS;
+};
+
+
+}
+}
+#endif
+
+
+
diff --git a/libs/rs/rsProgramVertex.cpp b/libs/rs/rsProgramVertex.cpp
new file mode 100644
index 0000000..417ba6a
--- /dev/null
+++ b/libs/rs/rsProgramVertex.cpp
@@ -0,0 +1,176 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+#include "rsProgramVertex.h"
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+using namespace android;
+using namespace android::renderscript;
+
+
+ProgramVertex::ProgramVertex(Element *in, Element *out) :
+    Program(in, out)
+{
+    mTextureMatrixEnable = false;
+    mLightCount = 0;
+}
+
+ProgramVertex::~ProgramVertex()
+{
+}
+
+static void logMatrix(const char *txt, const float *f)
+{
+    LOGV("Matrix %s, %p", txt, f);
+    LOGV("%6.2f, %6.2f, %6.2f, %6.2f", f[0], f[4], f[8], f[12]);
+    LOGV("%6.2f, %6.2f, %6.2f, %6.2f", f[1], f[5], f[9], f[13]);
+    LOGV("%6.2f, %6.2f, %6.2f, %6.2f", f[2], f[6], f[10], f[14]);
+    LOGV("%6.2f, %6.2f, %6.2f, %6.2f", f[3], f[7], f[11], f[15]);
+}
+
+void ProgramVertex::setupGL()
+{
+    const float *f = static_cast<const float *>(mConstants[0]->getPtr());
+
+    glMatrixMode(GL_TEXTURE);
+    if (mTextureMatrixEnable) {
+        glLoadMatrixf(&f[RS_PROGRAM_VERTEX_TEXTURE_OFFSET]);
+    } else {
+        glLoadIdentity();
+    }
+
+
+    LOGE("lights %i ", mLightCount);
+    glMatrixMode(GL_MODELVIEW);
+    glLoadIdentity();
+    if (mLightCount) {
+        int v = 1;
+        glEnable(GL_LIGHTING);
+        glLightModelxv(GL_LIGHT_MODEL_TWO_SIDE, &v);
+        for (uint32_t ct = 0; ct < mLightCount; ct++) {
+            const Light *l = mLights[ct].get();
+            glEnable(GL_LIGHT0 + ct);
+            l->setupGL(ct);
+        }
+        for (uint32_t ct = mLightCount; ct < MAX_LIGHTS; ct++) {
+            glDisable(GL_LIGHT0 + ct);
+        }
+    } else {
+        glDisable(GL_LIGHTING);
+    }
+    
+    if (!f) {
+        LOGE("Must bind constants to vertex program");
+    }
+
+    glMatrixMode(GL_PROJECTION);
+    glLoadMatrixf(&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET]);
+    glMatrixMode(GL_MODELVIEW);
+    glLoadMatrixf(&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET]);
+}
+
+void ProgramVertex::setConstantType(uint32_t slot, const Type *t)
+{
+    mConstantTypes[slot].set(t);
+}
+
+void ProgramVertex::bindAllocation(uint32_t slot, Allocation *a)
+{
+    mConstants[slot].set(a);
+}
+
+void ProgramVertex::addLight(const Light *l)
+{
+    if (mLightCount < MAX_LIGHTS) {
+        mLights[mLightCount].set(l);
+        mLightCount++;
+    }
+}
+
+
+ProgramVertexState::ProgramVertexState()
+{
+    mPV = NULL;
+}
+
+ProgramVertexState::~ProgramVertexState()
+{
+    delete mPV;
+}
+
+void ProgramVertexState::init(Context *rsc, int32_t w, int32_t h)
+{
+    ProgramVertex *pv = new ProgramVertex(NULL, NULL);
+    Allocation *alloc = (Allocation *)
+        rsi_AllocationCreatePredefSized(rsc, RS_ELEMENT_USER_FLOAT, 48);
+    mDefaultAlloc.set(alloc);
+    mDefault.set(pv);
+
+    pv->bindAllocation(0, alloc);
+    
+    Matrix m;
+    m.loadOrtho(0,w, h,0, -1,1);
+    alloc->subData(RS_PROGRAM_VERTEX_PROJECTION_OFFSET, 16, &m.m[0]);
+
+    m.loadIdentity();
+    alloc->subData(RS_PROGRAM_VERTEX_MODELVIEW_OFFSET, 16, &m.m[0]);
+}
+
+
+namespace android {
+namespace renderscript {
+
+void rsi_ProgramVertexBegin(Context *rsc, RsElement in, RsElement out)
+{
+    delete rsc->mStateVertex.mPV;
+    rsc->mStateVertex.mPV = new ProgramVertex((Element *)in, (Element *)out);
+}
+
+RsProgramVertex rsi_ProgramVertexCreate(Context *rsc)
+{
+    ProgramVertex *pv = rsc->mStateVertex.mPV;
+    pv->incRef();
+    rsc->mStateVertex.mPV = 0;
+    return pv;
+}
+
+void rsi_ProgramVertexBindAllocation(Context *rsc, RsProgramVertex vpgm, uint32_t slot, RsAllocation constants)
+{
+    ProgramVertex *pv = static_cast<ProgramVertex *>(vpgm);
+    pv->bindAllocation(slot, static_cast<Allocation *>(constants));
+}
+
+void rsi_ProgramVertexSetType(Context *rsc, uint32_t slot, RsType constants)
+{
+    rsc->mStateVertex.mPV->setConstantType(slot, static_cast<const Type *>(constants));
+}
+
+void rsi_ProgramVertexSetTextureMatrixEnable(Context *rsc, bool enable)
+{
+    rsc->mStateVertex.mPV->setTextureMatrixEnable(enable);
+}
+
+void rsi_ProgramVertexAddLight(Context *rsc, RsLight light)
+{
+    rsc->mStateVertex.mPV->addLight(static_cast<const Light *>(light));
+}
+
+
+}
+}
diff --git a/libs/rs/rsProgramVertex.h b/libs/rs/rsProgramVertex.h
new file mode 100644
index 0000000..ac15b70
--- /dev/null
+++ b/libs/rs/rsProgramVertex.h
@@ -0,0 +1,84 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_PROGRAM_VERTEX_H
+#define ANDROID_RS_PROGRAM_VERTEX_H
+
+#include "rsProgram.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+
+class ProgramVertex : public Program
+{
+public:
+    const static uint32_t MAX_CONSTANTS = 2;
+    const static uint32_t MAX_LIGHTS = 8;
+
+    ProgramVertex(Element *in, Element *out);
+    virtual ~ProgramVertex();
+
+    virtual void setupGL();
+
+
+    void setConstantType(uint32_t slot, const Type *);
+    void bindAllocation(uint32_t slot, Allocation *);
+    void setTextureMatrixEnable(bool e) {mTextureMatrixEnable = e;}
+    void addLight(const Light *);
+
+protected:
+    bool mDirty;
+    uint32_t mLightCount;
+
+    ObjectBaseRef<Allocation> mConstants[MAX_CONSTANTS];
+    ObjectBaseRef<const Type> mConstantTypes[MAX_CONSTANTS];
+    ObjectBaseRef<const Light> mLights[MAX_LIGHTS];
+
+
+    // Hacks to create a program for now
+    bool mTextureMatrixEnable;
+
+};
+
+
+class ProgramVertexState 
+{
+public:
+    ProgramVertexState();
+    ~ProgramVertexState();
+
+    void init(Context *rsc, int32_t w, int32_t h);
+
+    ObjectBaseRef<ProgramVertex> mDefault;
+    ObjectBaseRef<Allocation> mDefaultAlloc;
+    
+
+
+    ProgramVertex *mPV;
+
+    //ObjectBaseRef<Type> mTextureTypes[ProgramFragment::MAX_TEXTURE];
+
+
+};
+
+
+}
+}
+#endif
+
+
diff --git a/libs/rs/rsSampler.cpp b/libs/rs/rsSampler.cpp
new file mode 100644
index 0000000..418f127
--- /dev/null
+++ b/libs/rs/rsSampler.cpp
@@ -0,0 +1,157 @@
+/*
+ * 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.
+ */
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+#include "rsContext.h"
+#include "rsSampler.h"
+
+
+using namespace android;
+using namespace android::renderscript;
+
+
+Sampler::Sampler()
+{
+    // Should not get called.
+    rsAssert(0);
+}
+
+Sampler::Sampler(RsSamplerValue magFilter,
+                 RsSamplerValue minFilter,
+                 RsSamplerValue wrapS,
+                 RsSamplerValue wrapT,
+                 RsSamplerValue wrapR)
+{
+    mMagFilter = magFilter;
+    mMinFilter = minFilter;
+    mWrapS = wrapS;
+    mWrapT = wrapT;
+    mWrapR = wrapR;
+}
+
+Sampler::~Sampler()
+{
+}
+
+void Sampler::setupGL()
+{
+    GLenum trans[] = {
+        GL_NEAREST, //RS_SAMPLER_NEAREST,
+        GL_LINEAR, //RS_SAMPLER_LINEAR,
+        GL_LINEAR_MIPMAP_LINEAR, //RS_SAMPLER_LINEAR_MIP_LINEAR,
+        GL_REPEAT, //RS_SAMPLER_WRAP,
+        GL_CLAMP_TO_EDGE, //RS_SAMPLER_CLAMP
+
+    };
+
+
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, trans[mMinFilter]);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, trans[mMagFilter]);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, trans[mWrapS]);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, trans[mWrapT]);
+
+}
+
+void Sampler::bindToContext(SamplerState *ss, uint32_t slot)
+{
+    ss->mSamplers[slot].set(this);
+    mBoundSlot = slot;
+}
+
+void Sampler::unbindFromContext(SamplerState *ss)
+{
+    int32_t slot = mBoundSlot;
+    mBoundSlot = -1;
+    ss->mSamplers[slot].clear();
+}
+
+void SamplerState::setupGL()
+{
+    for (uint32_t ct=0; ct < RS_MAX_SAMPLER_SLOT; ct++) {
+        Sampler *s = mSamplers[ct].get();
+        if (s) {
+            s->setupGL();
+        } else {
+            glBindTexture(GL_TEXTURE_2D, 0);
+        }
+    }
+}
+
+////////////////////////////////
+
+namespace android {
+namespace renderscript {
+
+
+void rsi_SamplerBegin(Context *rsc)
+{
+    SamplerState * ss = &rsc->mStateSampler;
+
+    ss->mMagFilter = RS_SAMPLER_LINEAR;
+    ss->mMinFilter = RS_SAMPLER_LINEAR;
+    ss->mWrapS = RS_SAMPLER_WRAP;
+    ss->mWrapT = RS_SAMPLER_WRAP;
+    ss->mWrapR = RS_SAMPLER_WRAP;
+}
+
+void rsi_SamplerSet(Context *rsc, RsSamplerParam param, RsSamplerValue value)
+{
+    SamplerState * ss = &rsc->mStateSampler;
+
+    switch(param) {
+    case RS_SAMPLER_MAG_FILTER:
+        ss->mMagFilter = value;
+        break;
+    case RS_SAMPLER_MIN_FILTER:
+        ss->mMinFilter = value;
+        break;
+    case RS_SAMPLER_WRAP_S:
+        ss->mWrapS = value;
+        break;
+    case RS_SAMPLER_WRAP_T:
+        ss->mWrapT = value;
+        break;
+    case RS_SAMPLER_WRAP_R:
+        ss->mWrapR = value;
+        break;
+    }
+
+}
+
+RsSampler rsi_SamplerCreate(Context *rsc)
+{
+    SamplerState * ss = &rsc->mStateSampler;
+
+
+    Sampler * s = new Sampler(ss->mMagFilter, 
+                              ss->mMinFilter, 
+                              ss->mWrapS, 
+                              ss->mWrapT,
+                              ss->mWrapR);
+    return s;
+}
+
+void rsi_SamplerDestroy(Context *rsc, RsSampler vs)
+{
+    Sampler * s = static_cast<Sampler *>(vs);
+    s->decRef();
+
+}
+
+
+}}
diff --git a/libs/rs/rsSampler.h b/libs/rs/rsSampler.h
new file mode 100644
index 0000000..4b504f6
--- /dev/null
+++ b/libs/rs/rsSampler.h
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_SAMPLER_H
+#define ANDROID_RS_SAMPLER_H
+
+#include "rsAllocation.h"
+#include "RenderScript.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+const static uint32_t RS_MAX_SAMPLER_SLOT = 16;
+
+class SamplerState;
+
+class Sampler : public ObjectBase
+{
+public:
+    Sampler(RsSamplerValue magFilter,
+            RsSamplerValue minFilter,
+            RsSamplerValue wrapS,
+            RsSamplerValue wrapT,
+            RsSamplerValue wrapR);
+
+    virtual ~Sampler();
+
+    void bind(Allocation *);
+    void setupGL();
+
+    void bindToContext(SamplerState *, uint32_t slot);
+    void unbindFromContext(SamplerState *);
+
+protected:
+    RsSamplerValue mMagFilter;
+    RsSamplerValue mMinFilter;
+    RsSamplerValue mWrapS;
+    RsSamplerValue mWrapT;
+    RsSamplerValue mWrapR;
+
+    int32_t mBoundSlot;
+
+private:
+    Sampler();
+
+};
+
+
+class SamplerState 
+{
+public:
+
+    RsSamplerValue mMagFilter;
+    RsSamplerValue mMinFilter;
+    RsSamplerValue mWrapS;
+    RsSamplerValue mWrapT;
+    RsSamplerValue mWrapR;
+
+
+    ObjectBaseRef<Sampler> mSamplers[RS_MAX_SAMPLER_SLOT];
+
+    void setupGL();
+
+};
+
+
+
+}
+}
+#endif //ANDROID_RS_SAMPLER_H
+
+
+
diff --git a/libs/rs/rsScript.cpp b/libs/rs/rsScript.cpp
new file mode 100644
index 0000000..ae85c9c
--- /dev/null
+++ b/libs/rs/rsScript.cpp
@@ -0,0 +1,55 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+Script::Script()
+{
+    memset(&mEnviroment, 0, sizeof(mEnviroment));
+    mEnviroment.mClearColor[0] = 0;
+    mEnviroment.mClearColor[1] = 0;
+    mEnviroment.mClearColor[2] = 0;
+    mEnviroment.mClearColor[3] = 1;
+    mEnviroment.mClearDepth = 1;
+}
+
+Script::~Script()
+{
+}
+
+namespace android {
+namespace renderscript {
+
+
+void rsi_ScriptDestroy(Context * rsc, RsScript vs)
+{
+    Script *s = static_cast<Script *>(vs);
+    s->decRef();
+}
+
+void rsi_ScriptBindAllocation(Context * rsc, RsScript vs, RsAllocation va, uint32_t slot)
+{
+    Script *s = static_cast<Script *>(vs);
+    s->mSlots[slot].set(static_cast<Allocation *>(va));
+}
+
+
+}
+}
+
diff --git a/libs/rs/rsScript.h b/libs/rs/rsScript.h
new file mode 100644
index 0000000..7dd2b61
--- /dev/null
+++ b/libs/rs/rsScript.h
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_SCRIPT_H
+#define ANDROID_RS_SCRIPT_H
+
+#include "rsAllocation.h"
+
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+class ProgramVertex;
+class ProgramFragment;
+class ProgramRaster;
+class ProgramFragmentStore;
+
+class Script : public ObjectBase
+{
+public:
+
+    Script();
+    virtual ~Script();
+
+
+    struct Enviroment_t {
+        bool mIsRoot;
+        float mClearColor[4];
+        float mClearDepth;
+        uint32_t mClearStencil;
+
+        ObjectBaseRef<ProgramVertex> mVertex;
+        ObjectBaseRef<ProgramFragment> mFragment;
+        //ObjectBaseRef<ProgramRaster> mRaster;
+        ObjectBaseRef<ProgramFragmentStore> mFragmentStore;
+
+    };
+    Enviroment_t mEnviroment;
+
+    const Type * mConstantBufferTypes;
+    uint32_t mCounstantBufferCount;
+
+    ObjectBaseRef<Allocation> mSlots[16];
+
+    virtual bool run(Context *, uint32_t launchID) = 0;
+};
+
+
+
+}
+}
+#endif
+
diff --git a/libs/rs/rsScriptC.cpp b/libs/rs/rsScriptC.cpp
new file mode 100644
index 0000000..842c836
--- /dev/null
+++ b/libs/rs/rsScriptC.cpp
@@ -0,0 +1,291 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+#include "rsScriptC.h"
+#include "rsMatrix.h"
+
+#include "acc/acc.h"
+#include "utils/String8.h"
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+using namespace android;
+using namespace android::renderscript;
+
+#define GET_TLS()  Context::ScriptTLSStruct * tls = \
+    (Context::ScriptTLSStruct *)pthread_getspecific(Context::gThreadTLSKey); \
+    Context * rsc = tls->mContext; \
+    ScriptC * sc = (ScriptC *) tls->mScript
+
+
+ScriptC::ScriptC()
+{
+    mAccScript = NULL;
+    memset(&mProgram, 0, sizeof(mProgram));
+}
+
+ScriptC::~ScriptC()
+{
+    if (mAccScript) {
+        accDeleteScript(mAccScript);
+    }
+}
+
+
+bool ScriptC::run(Context *rsc, uint32_t launchIndex)
+{
+    Context::ScriptTLSStruct * tls = 
+    (Context::ScriptTLSStruct *)pthread_getspecific(Context::gThreadTLSKey);
+
+    if (mEnviroment.mFragmentStore.get()) {
+        rsc->setFragmentStore(mEnviroment.mFragmentStore.get());
+    }
+    if (mEnviroment.mFragment.get()) {
+        rsc->setFragment(mEnviroment.mFragment.get());
+    }
+    if (mEnviroment.mVertex.get()) {
+        rsc->setVertex(mEnviroment.mVertex.get());
+    }
+
+    bool ret = false;
+    tls->mScript = this;
+    ret = mProgram.mScript(launchIndex) != 0;
+    tls->mScript = NULL;
+    return ret;
+}
+
+ScriptCState::ScriptCState()
+{
+    clear();
+}
+
+ScriptCState::~ScriptCState()
+{
+    if (mAccScript) {
+        accDeleteScript(mAccScript);
+    }
+}
+
+void ScriptCState::clear()
+{
+    memset(&mProgram, 0, sizeof(mProgram));
+
+    mConstantBufferTypes.clear();
+
+    memset(&mEnviroment, 0, sizeof(mEnviroment));
+    mEnviroment.mClearColor[0] = 0;
+    mEnviroment.mClearColor[1] = 0;
+    mEnviroment.mClearColor[2] = 0;
+    mEnviroment.mClearColor[3] = 1;
+    mEnviroment.mClearDepth = 1;
+    mEnviroment.mClearStencil = 0;
+    mEnviroment.mIsRoot = false;
+
+    mAccScript = NULL;
+
+}
+
+static ACCvoid* symbolLookup(ACCvoid* pContext, const ACCchar* name) 
+{
+    const ScriptCState::SymbolTable_t *sym = ScriptCState::lookupSymbol(name);
+    if (sym) {
+        return sym->mPtr;
+    }
+    LOGE("ScriptC sym lookup failed for %s", name);
+    return NULL;
+}
+
+void ScriptCState::runCompiler(Context *rsc)
+{
+    mAccScript = accCreateScript();
+    String8 tmp;
+
+    rsc->appendNameDefines(&tmp);
+    appendDecls(&tmp);
+    tmp.append("#line 1\n");
+
+    const char* scriptSource[] = {tmp.string(), mProgram.mScriptText};
+    int scriptLength[] = {tmp.length(), mProgram.mScriptTextLength} ;
+    accScriptSource(mAccScript, sizeof(scriptLength) / sizeof(int), scriptSource, scriptLength);
+    accRegisterSymbolCallback(mAccScript, symbolLookup, NULL);
+    accCompileScript(mAccScript);
+    accGetScriptLabel(mAccScript, "main", (ACCvoid**) &mProgram.mScript);
+    rsAssert(mProgram.mScript);
+
+    if (!mProgram.mScript) {
+        ACCchar buf[4096];
+        ACCsizei len;
+        accGetScriptInfoLog(mAccScript, sizeof(buf), &len, buf);
+        LOGE(buf);
+
+    }
+
+    mEnviroment.mFragment.set(rsc->getDefaultProgramFragment());
+    mEnviroment.mVertex.set(rsc->getDefaultProgramVertex());
+    mEnviroment.mFragmentStore.set(rsc->getDefaultProgramFragmentStore());
+
+    if (mProgram.mScript) {
+        const static int pragmaMax = 16;
+        ACCsizei pragmaCount;
+        ACCchar * str[pragmaMax];
+        accGetPragmas(mAccScript, &pragmaCount, pragmaMax, &str[0]);
+
+        for (int ct=0; ct < pragmaCount; ct+=2) {
+            if (!strcmp(str[ct], "version")) {
+                continue;
+            }
+
+            if (!strcmp(str[ct], "stateVertex")) {
+                if (!strcmp(str[ct+1], "default")) {
+                    continue;
+                }
+                if (!strcmp(str[ct+1], "parent")) {
+                    mEnviroment.mVertex.clear();
+                    continue;
+                }
+                ProgramVertex * pv = (ProgramVertex *)rsc->lookupName(str[ct+1]);
+                if (pv != NULL) {
+                    mEnviroment.mVertex.set(pv);
+                    continue;
+                }
+                LOGE("Unreconized value %s passed to stateVertex", str[ct+1]);
+            }
+
+            if (!strcmp(str[ct], "stateRaster")) {
+                LOGE("Unreconized value %s passed to stateRaster", str[ct+1]);
+            }
+
+            if (!strcmp(str[ct], "stateFragment")) {
+                if (!strcmp(str[ct+1], "default")) {
+                    continue;
+                }
+                if (!strcmp(str[ct+1], "parent")) {
+                    mEnviroment.mFragment.clear();
+                    continue;
+                }
+                ProgramFragment * pf = (ProgramFragment *)rsc->lookupName(str[ct+1]);
+                if (pf != NULL) {
+                    mEnviroment.mFragment.set(pf);
+                    continue;
+                }
+                LOGE("Unreconized value %s passed to stateFragment", str[ct+1]);
+            }
+
+            if (!strcmp(str[ct], "stateFragmentStore")) {
+                if (!strcmp(str[ct+1], "default")) {
+                    continue;
+                }
+                if (!strcmp(str[ct+1], "parent")) {
+                    mEnviroment.mFragmentStore.clear();
+                    continue;
+                }
+                ProgramFragmentStore * pfs = 
+                    (ProgramFragmentStore *)rsc->lookupName(str[ct+1]);
+                if (pfs != NULL) {
+                    mEnviroment.mFragmentStore.set(pfs);
+                    continue;
+                }
+                LOGE("Unreconized value %s passed to stateFragmentStore", str[ct+1]);
+            }
+
+        }
+
+            
+    } else {
+        // Deal with an error.
+    }
+
+}
+
+namespace android {
+namespace renderscript {
+
+void rsi_ScriptCBegin(Context * rsc)
+{
+    ScriptCState *ss = &rsc->mScriptC;
+    ss->clear();
+}
+
+void rsi_ScriptCSetClearColor(Context * rsc, float r, float g, float b, float a)
+{
+    ScriptCState *ss = &rsc->mScriptC;
+    ss->mEnviroment.mClearColor[0] = r;
+    ss->mEnviroment.mClearColor[1] = g;
+    ss->mEnviroment.mClearColor[2] = b;
+    ss->mEnviroment.mClearColor[3] = a;
+}
+
+void rsi_ScriptCSetClearDepth(Context * rsc, float v)
+{
+    ScriptCState *ss = &rsc->mScriptC;
+    ss->mEnviroment.mClearDepth = v;
+}
+
+void rsi_ScriptCSetClearStencil(Context * rsc, uint32_t v)
+{
+    ScriptCState *ss = &rsc->mScriptC;
+    ss->mEnviroment.mClearStencil = v;
+}
+
+void rsi_ScriptCAddType(Context * rsc, RsType vt)
+{
+    ScriptCState *ss = &rsc->mScriptC;
+    ss->mConstantBufferTypes.add(static_cast<const Type *>(vt));
+}
+
+void rsi_ScriptCSetScript(Context * rsc, void *vp)
+{
+    ScriptCState *ss = &rsc->mScriptC;
+    ss->mProgram.mScript = reinterpret_cast<ScriptC::RunScript_t>(vp);
+}
+
+void rsi_ScriptCSetRoot(Context * rsc, bool isRoot)
+{
+    ScriptCState *ss = &rsc->mScriptC;
+    ss->mEnviroment.mIsRoot = isRoot;
+}
+
+void rsi_ScriptCSetText(Context *rsc, const char *text, uint32_t len)
+{
+    ScriptCState *ss = &rsc->mScriptC;
+    ss->mProgram.mScriptText = text;
+    ss->mProgram.mScriptTextLength = len;
+}
+
+
+RsScript rsi_ScriptCCreate(Context * rsc)
+{
+    ScriptCState *ss = &rsc->mScriptC;
+
+    ss->runCompiler(rsc);
+
+    ScriptC *s = new ScriptC();
+    s->incRef();
+    s->mAccScript = ss->mAccScript;
+    ss->mAccScript = NULL;
+    s->mEnviroment = ss->mEnviroment;
+    s->mProgram = ss->mProgram;
+    ss->clear();
+
+    return s;
+}
+
+}
+}
+
+
diff --git a/libs/rs/rsScriptC.h b/libs/rs/rsScriptC.h
new file mode 100644
index 0000000..860b4d1
--- /dev/null
+++ b/libs/rs/rsScriptC.h
@@ -0,0 +1,91 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_SCRIPT_C_H
+#define ANDROID_RS_SCRIPT_C_H
+
+#include "rsScript.h"
+
+#include "RenderScriptEnv.h"
+
+struct ACCscript;
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+
+
+class ScriptC : public Script
+{
+public:
+    typedef int (*RunScript_t)(uint32_t launchIndex);
+
+    ScriptC();
+    virtual ~ScriptC();
+
+    struct Program_t {
+        const char * mScriptText;
+        uint32_t mScriptTextLength;
+
+
+        int mVersionMajor;
+        int mVersionMinor;
+
+        RunScript_t mScript;
+    };
+
+    Program_t mProgram;
+
+    ACCscript*    mAccScript;
+
+    virtual bool run(Context *, uint32_t launchID);
+};
+
+class ScriptCState
+{
+public:
+    ScriptCState();
+    ~ScriptCState();
+
+    ACCscript* mAccScript;
+
+    ScriptC::Program_t mProgram;
+    Script::Enviroment_t mEnviroment;
+
+    Vector<const Type *> mConstantBufferTypes;
+
+    void clear();
+    void runCompiler(Context *rsc);
+
+    struct SymbolTable_t {
+        const char * mName;
+        void * mPtr;
+        const char * mRet;
+        const char * mParam;
+    };
+    static SymbolTable_t gSyms[];
+    static const SymbolTable_t * lookupSymbol(const char *);
+    static void appendDecls(String8 *str);
+};
+
+
+}
+}
+#endif
+
+
+
diff --git a/libs/rs/rsScriptC_Lib.cpp b/libs/rs/rsScriptC_Lib.cpp
new file mode 100644
index 0000000..129b19f
--- /dev/null
+++ b/libs/rs/rsScriptC_Lib.cpp
@@ -0,0 +1,531 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+#include "rsScriptC.h"
+#include "rsMatrix.h"
+
+#include "acc/acc.h"
+#include "utils/String8.h"
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+using namespace android;
+using namespace android::renderscript;
+
+#define GET_TLS()  Context::ScriptTLSStruct * tls = \
+    (Context::ScriptTLSStruct *)pthread_getspecific(Context::gThreadTLSKey); \
+    Context * rsc = tls->mContext; \
+    ScriptC * sc = (ScriptC *) tls->mScript
+
+
+//////////////////////////////////////////////////////////////////////////////
+// IO routines
+//////////////////////////////////////////////////////////////////////////////
+
+static float SC_loadF(uint32_t bank, uint32_t offset)
+{
+    GET_TLS();
+    const void *vp = sc->mSlots[bank]->getPtr();
+    const float *f = static_cast<const float *>(vp);
+    //LOGE("loadF %i %i = %f %x", bank, offset, f, ((int *)&f)[0]);
+    return f[offset];
+}
+
+static int32_t SC_loadI32(uint32_t bank, uint32_t offset)
+{
+    GET_TLS();
+    const void *vp = sc->mSlots[bank]->getPtr();
+    const int32_t *i = static_cast<const int32_t *>(vp);
+    //LOGE("loadI32 %i %i = %i", bank, offset, t);
+    return i[offset];
+}
+
+static uint32_t SC_loadU32(uint32_t bank, uint32_t offset)
+{
+    GET_TLS();
+    const void *vp = sc->mSlots[bank]->getPtr();
+    const uint32_t *i = static_cast<const uint32_t *>(vp);
+    return i[offset];
+}
+
+static void SC_loadVec4(uint32_t bank, uint32_t offset, rsc_Vector4 *v)
+{
+    GET_TLS();
+    const void *vp = sc->mSlots[bank]->getPtr();
+    const float *f = static_cast<const float *>(vp);
+    memcpy(v, &f[offset], sizeof(rsc_Vector4));
+}
+
+static void SC_loadMatrix(uint32_t bank, uint32_t offset, rsc_Matrix *m)
+{
+    GET_TLS();
+    const void *vp = sc->mSlots[bank]->getPtr();
+    const float *f = static_cast<const float *>(vp);
+    memcpy(m, &f[offset], sizeof(rsc_Matrix));
+}
+
+
+static void SC_storeF(uint32_t bank, uint32_t offset, float v)
+{
+    //LOGE("storeF %i %i %f", bank, offset, v);
+    GET_TLS();
+    void *vp = sc->mSlots[bank]->getPtr();
+    float *f = static_cast<float *>(vp);
+    f[offset] = v;
+}
+
+static void SC_storeI32(uint32_t bank, uint32_t offset, int32_t v)
+{
+    GET_TLS();
+    void *vp = sc->mSlots[bank]->getPtr();
+    int32_t *f = static_cast<int32_t *>(vp);
+    static_cast<int32_t *>(sc->mSlots[bank]->getPtr())[offset] = v;
+}
+
+static void SC_storeU32(uint32_t bank, uint32_t offset, uint32_t v)
+{
+    GET_TLS();
+    void *vp = sc->mSlots[bank]->getPtr();
+    uint32_t *f = static_cast<uint32_t *>(vp);
+    static_cast<uint32_t *>(sc->mSlots[bank]->getPtr())[offset] = v;
+}
+
+static void SC_storeVec4(uint32_t bank, uint32_t offset, const rsc_Vector4 *v)
+{
+    GET_TLS();
+    void *vp = sc->mSlots[bank]->getPtr();
+    float *f = static_cast<float *>(vp);
+    memcpy(&f[offset], v, sizeof(rsc_Vector4));
+}
+
+static void SC_storeMatrix(uint32_t bank, uint32_t offset, const rsc_Matrix *m)
+{
+    GET_TLS();
+    void *vp = sc->mSlots[bank]->getPtr();
+    float *f = static_cast<float *>(vp);
+    memcpy(&f[offset], m, sizeof(rsc_Matrix));
+}
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Math routines
+//////////////////////////////////////////////////////////////////////////////
+
+static float SC_randf(float max)
+{
+    float r = (float)rand();
+    return r / RAND_MAX * max;
+}
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Matrix routines
+//////////////////////////////////////////////////////////////////////////////
+
+
+static void SC_matrixLoadIdentity(rsc_Matrix *mat)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->loadIdentity();
+}
+
+static void SC_matrixLoadFloat(rsc_Matrix *mat, const float *f)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->load(f);
+}
+
+static void SC_matrixLoadMat(rsc_Matrix *mat, const rsc_Matrix *newmat)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->load(reinterpret_cast<const Matrix *>(newmat));
+}
+
+static void SC_matrixLoadRotate(rsc_Matrix *mat, float rot, float x, float y, float z)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->loadRotate(rot, x, y, z);
+}
+
+static void SC_matrixLoadScale(rsc_Matrix *mat, float x, float y, float z)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->loadScale(x, y, z);
+}
+
+static void SC_matrixLoadTranslate(rsc_Matrix *mat, float x, float y, float z)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->loadTranslate(x, y, z);
+}
+
+static void SC_matrixLoadMultiply(rsc_Matrix *mat, const rsc_Matrix *lhs, const rsc_Matrix *rhs)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->loadMultiply(reinterpret_cast<const Matrix *>(lhs),
+                    reinterpret_cast<const Matrix *>(rhs));
+}
+
+static void SC_matrixMultiply(rsc_Matrix *mat, const rsc_Matrix *rhs)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->multiply(reinterpret_cast<const Matrix *>(rhs));
+}
+
+static void SC_matrixRotate(rsc_Matrix *mat, float rot, float x, float y, float z)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->rotate(rot, x, y, z);
+}
+
+static void SC_matrixScale(rsc_Matrix *mat, float x, float y, float z)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->scale(x, y, z);
+}
+
+static void SC_matrixTranslate(rsc_Matrix *mat, float x, float y, float z)
+{
+    Matrix *m = reinterpret_cast<Matrix *>(mat);
+    m->translate(x, y, z);
+}
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Context
+//////////////////////////////////////////////////////////////////////////////
+
+static void SC_bindTexture(RsProgramFragment vpf, uint32_t slot, RsAllocation va)
+{
+    GET_TLS();
+    rsi_ProgramFragmentBindTexture(rsc,
+                                   static_cast<ProgramFragment *>(vpf),
+                                   slot,
+                                   static_cast<Allocation *>(va));
+
+}
+
+static void SC_bindSampler(RsProgramFragment vpf, uint32_t slot, RsSampler vs)
+{
+    GET_TLS();
+    rsi_ProgramFragmentBindSampler(rsc,
+                                   static_cast<ProgramFragment *>(vpf),
+                                   slot,
+                                   static_cast<Sampler *>(vs));
+
+}
+
+static void SC_bindProgramFragmentStore(RsProgramFragmentStore pfs)
+{
+    GET_TLS();
+    rsi_ContextBindProgramFragmentStore(rsc, pfs);
+
+}
+
+static void SC_bindProgramFragment(RsProgramFragment pf)
+{
+    GET_TLS();
+    rsi_ContextBindProgramFragment(rsc, pf);
+
+}
+
+static void SC_bindProgramVertex(RsProgramVertex pv)
+{
+    GET_TLS();
+    rsi_ContextBindProgramVertex(rsc, pv);
+
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Drawing
+//////////////////////////////////////////////////////////////////////////////
+
+static void SC_drawTriangleMesh(RsTriangleMesh mesh)
+{
+    GET_TLS();
+    rsi_TriangleMeshRender(rsc, mesh);
+}
+
+static void SC_drawTriangleMeshRange(RsTriangleMesh mesh, uint32_t start, uint32_t count)
+{
+    GET_TLS();
+    rsi_TriangleMeshRenderRange(rsc, mesh, start, count);
+}
+
+// Assumes (GL_FIXED) x,y,z (GL_UNSIGNED_BYTE)r,g,b,a
+static void SC_drawTriangleArray(int ialloc, uint32_t count)
+{
+    GET_TLS();
+    RsAllocation alloc = (RsAllocation)ialloc;
+
+    const Allocation *a = (const Allocation *)alloc;
+    const uint32_t *ptr = (const uint32_t *)a->getPtr();
+
+    rsc->setupCheck();
+
+    glBindBuffer(GL_ARRAY_BUFFER, 0);
+    //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, tm->mBufferObjects[1]);
+
+    glEnableClientState(GL_VERTEX_ARRAY);
+    glDisableClientState(GL_NORMAL_ARRAY);
+    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+    glEnableClientState(GL_COLOR_ARRAY);
+
+    glVertexPointer(2, GL_FIXED, 12, ptr + 1);
+    //glTexCoordPointer(2, GL_FIXED, 24, ptr + 1);
+    glColorPointer(4, GL_UNSIGNED_BYTE, 12, ptr);
+
+    glDrawArrays(GL_TRIANGLES, 0, count * 3);
+}
+
+static void SC_drawQuad(float x1, float y1, float z1,
+                        float x2, float y2, float z2,
+                        float x3, float y3, float z3,
+                        float x4, float y4, float z4)
+{
+    GET_TLS();
+
+    //LOGE("Quad");
+    //LOGE("%4.2f, %4.2f, %4.2f", x1, y1, z1);
+    //LOGE("%4.2f, %4.2f, %4.2f", x2, y2, z2);
+    //LOGE("%4.2f, %4.2f, %4.2f", x3, y3, z3);
+    //LOGE("%4.2f, %4.2f, %4.2f", x4, y4, z4);
+
+    float vtx[] = {x1,y1,z1, x2,y2,z2, x3,y3,z3, x4,y4,z4};
+    static const float tex[] = {0,1, 1,1, 1,0, 0,0};
+
+
+    rsc->setupCheck();
+
+    glBindBuffer(GL_ARRAY_BUFFER, 0);
+    //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, tm->mBufferObjects[1]);
+
+    glEnableClientState(GL_VERTEX_ARRAY);
+    glVertexPointer(3, GL_FLOAT, 0, vtx);
+
+    glClientActiveTexture(GL_TEXTURE0);
+    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+    glTexCoordPointer(2, GL_FLOAT, 0, tex);
+    glClientActiveTexture(GL_TEXTURE1);
+    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+    glTexCoordPointer(2, GL_FLOAT, 0, tex);
+    glClientActiveTexture(GL_TEXTURE0);
+
+    glDisableClientState(GL_NORMAL_ARRAY);
+    glDisableClientState(GL_COLOR_ARRAY);
+
+    //glColorPointer(4, GL_UNSIGNED_BYTE, 12, ptr);
+
+    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//////////////////////////////////////////////////////////////////////////////
+
+extern "C" const void * loadVp(uint32_t bank, uint32_t offset)
+{
+    GET_TLS();
+    return &static_cast<const uint8_t *>(sc->mSlots[bank]->getPtr())[offset];
+}
+
+
+
+static void SC_color(float r, float g, float b, float a)
+{
+    glColor4f(r, g, b, a);
+}
+
+
+extern "C" void materialDiffuse(float r, float g, float b, float a)
+{
+    float v[] = {r, g, b, a};
+    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, v);
+}
+
+extern "C" void materialSpecular(float r, float g, float b, float a)
+{
+    float v[] = {r, g, b, a};
+    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, v);
+}
+
+extern "C" void lightPosition(float x, float y, float z, float w)
+{
+    float v[] = {x, y, z, w};
+    glLightfv(GL_LIGHT0, GL_POSITION, v);
+}
+
+extern "C" void materialShininess(float s)
+{
+    glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &s);
+}
+
+extern "C" void uploadToTexture(RsAllocation va, uint32_t baseMipLevel)
+{
+    GET_TLS();
+    rsi_AllocationUploadToTexture(rsc, va, baseMipLevel);
+}
+
+extern "C" void enable(uint32_t p)
+{
+    glEnable(p);
+}
+
+extern "C" void disable(uint32_t p)
+{
+    glDisable(p);
+}
+
+
+
+static void SC_ClearColor(float r, float g, float b, float a)
+{
+    //LOGE("c %f %f %f %f", r, g, b, a);
+    GET_TLS();
+    sc->mEnviroment.mClearColor[0] = r;
+    sc->mEnviroment.mClearColor[1] = g;
+    sc->mEnviroment.mClearColor[2] = b;
+    sc->mEnviroment.mClearColor[3] = a;
+}
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Class implementation
+//////////////////////////////////////////////////////////////////////////////
+
+ScriptCState::SymbolTable_t ScriptCState::gSyms[] = {
+    // IO
+    { "loadI32", (void *)&SC_loadI32,
+        "int", "(int, int)" },
+    //{ "loadU32", (void *)&SC_loadU32, "unsigned int", "(int, int)" },
+    { "loadF", (void *)&SC_loadF,
+        "float", "(int, int)" },
+    { "loadVec4", (void *)&SC_loadVec4,
+        "void", "(int, int, float *)" },
+    { "loadMatrix", (void *)&SC_loadMatrix,
+        "void", "(int, int, float *)" },
+    { "storeI32", (void *)&SC_storeI32,
+        "void", "(int, int, int)" },
+    //{ "storeU32", (void *)&SC_storeU32, "void", "(int, int, unsigned int)" },
+    { "storeF", (void *)&SC_storeF,
+        "void", "(int, int, float)" },
+    { "storeVec4", (void *)&SC_storeVec4,
+        "void", "(int, int, float *)" },
+    { "storeMatrix", (void *)&SC_storeMatrix,
+        "void", "(int, int, float *)" },
+
+    // math
+    { "sinf", (void *)&sinf,
+        "float", "(float)" },
+    { "cosf", (void *)&cosf,
+        "float", "(float)" },
+    { "fabs", (void *)&fabs,
+        "float", "(float)" },
+    { "randf", (void *)&SC_randf,
+        "float", "(float)" },
+
+    // matrix
+    { "matrixLoadIdentity", (void *)&SC_matrixLoadIdentity,
+        "void", "(float *mat)" },
+    { "matrixLoadFloat", (void *)&SC_matrixLoadFloat,
+        "void", "(float *mat, float *f)" },
+    { "matrixLoadMat", (void *)&SC_matrixLoadMat,
+        "void", "(float *mat, float *newmat)" },
+    { "matrixLoadRotate", (void *)&SC_matrixLoadRotate,
+        "void", "(float *mat, float rot, float x, float y, float z)" },
+    { "matrixLoadScale", (void *)&SC_matrixLoadScale,
+        "void", "(float *mat, float x, float y, float z)" },
+    { "matrixLoadTranslate", (void *)&SC_matrixLoadTranslate,
+        "void", "(float *mat, float x, float y, float z)" },
+    { "matrixLoadMultiply", (void *)&SC_matrixLoadMultiply,
+        "void", "(float *mat, float *lhs, float *rhs)" },
+    { "matrixMultiply", (void *)&SC_matrixMultiply,
+        "void", "(float *mat, float *rhs)" },
+    { "matrixRotate", (void *)&SC_matrixRotate,
+        "void", "(float *mat, float rot, float x, float y, float z)" },
+    { "matrixScale", (void *)&SC_matrixScale,
+        "void", "(float *mat, float x, float y, float z)" },
+    { "matrixTranslate", (void *)&SC_matrixTranslate,
+        "void", "(float *mat, float x, float y, float z)" },
+
+    // context
+    { "bindProgramFragment", (void *)&SC_bindProgramFragment,
+        "void", "(int)" },
+    { "bindProgramFragmentStore", (void *)&SC_bindProgramFragmentStore,
+        "void", "(int)" },
+    { "bindProgramVertex", (void *)&SC_bindProgramVertex,
+        "void", "(int)" },
+    { "bindSampler", (void *)&SC_bindSampler,
+        "void", "(int, int, int)" },
+    { "bindTexture", (void *)&SC_bindTexture,
+        "void", "(int, int, int)" },
+
+    // drawing
+    { "drawQuad", (void *)&SC_drawQuad,
+        "void", "(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4)" },
+    { "drawTriangleArray", (void *)&SC_drawTriangleArray,
+        "void", "(int ialloc, int count)" },
+    { "drawTriangleMesh", (void *)&SC_drawTriangleMesh,
+        "void", "(int mesh)" },
+    { "drawTriangleMeshRange", (void *)&SC_drawTriangleMeshRange,
+        "void", "(int mesh, int start, int count)" },
+
+
+    // misc
+    { "pfClearColor", (void *)&SC_ClearColor,
+        "void", "(float, float, float, float)" },
+
+    { "color", (void *)&SC_color,
+        "void", "(float, float, float, float)" },
+
+    { NULL, NULL, NULL, NULL }
+};
+
+const ScriptCState::SymbolTable_t * ScriptCState::lookupSymbol(const char *sym)
+{
+    ScriptCState::SymbolTable_t *syms = gSyms;
+
+    while (syms->mPtr) {
+        if (!strcmp(syms->mName, sym)) {
+            return syms;
+        }
+        syms++;
+    }
+    return NULL;
+}
+
+void ScriptCState::appendDecls(String8 *str)
+{
+    ScriptCState::SymbolTable_t *syms = gSyms;
+    while (syms->mPtr) {
+        str->append(syms->mRet);
+        str->append(" ");
+        str->append(syms->mName);
+        str->append(syms->mParam);
+        str->append(";\n");
+        syms++;
+    }
+}
+
+
diff --git a/libs/rs/rsThreadIO.cpp b/libs/rs/rsThreadIO.cpp
new file mode 100644
index 0000000..89df59d
--- /dev/null
+++ b/libs/rs/rsThreadIO.cpp
@@ -0,0 +1,52 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+
+#include "rsThreadIO.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+ThreadIO *android::renderscript::gIO = NULL;
+
+ThreadIO::ThreadIO()
+{
+    mToCore.init(16 * 1024);
+}
+
+ThreadIO::~ThreadIO()
+{
+}
+
+bool ThreadIO::playCoreCommands(Context *con, bool waitForCommand)
+{
+    uint32_t cmdID = 0;
+    uint32_t cmdSize = 0;
+    bool ret = false;
+    while(!mToCore.isEmpty() || waitForCommand) {
+        ret = true;
+        const void * data = mToCore.get(&cmdID, &cmdSize);
+        waitForCommand = false;
+        //LOGV("playCoreCommands 3 %i %i", cmdID, cmdSize);
+
+        gPlaybackFuncs[cmdID](con, data);
+        mToCore.next();
+    }
+    return ret;
+}
+
+
diff --git a/libs/rs/rsThreadIO.h b/libs/rs/rsThreadIO.h
new file mode 100644
index 0000000..72746c5
--- /dev/null
+++ b/libs/rs/rsThreadIO.h
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_THREAD_IO_H
+#define ANDROID_RS_THREAD_IO_H
+
+#include "rsUtils.h"
+#include "rsLocklessFifo.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+class Context;
+
+class ThreadIO {
+public:
+    ThreadIO();
+    ~ThreadIO();
+
+    // Plays back commands from the client.
+    // Returns true if any commands were processed.
+    bool playCoreCommands(Context *con, bool waitForCommand);
+
+
+    LocklessCommandFifo mToCore;
+    //LocklessCommandFifo mToClient;
+
+    intptr_t mToCoreRet;
+
+};
+
+extern ThreadIO *gIO;
+
+
+
+}
+}
+#endif
+
diff --git a/libs/rs/rsTriangleMesh.cpp b/libs/rs/rsTriangleMesh.cpp
new file mode 100644
index 0000000..8c7bc92
--- /dev/null
+++ b/libs/rs/rsTriangleMesh.cpp
@@ -0,0 +1,286 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+TriangleMesh::TriangleMesh()
+{
+    mVertexElement = NULL;
+    mIndexElement = NULL;
+    mVertexData = NULL;
+    mIndexData = NULL;
+    mTriangleCount = 0;
+    mVertexDataSize = 0;
+    mIndexDataSize = 0;
+
+    mBufferObjects[0] = 0;
+    mBufferObjects[1] = 0;
+
+    mOffsetCoord = 0;
+    mOffsetTex = 0;
+    mOffsetNorm = 0;
+
+    mSizeCoord = 0;
+    mSizeTex = 0;
+    mSizeNorm = 0;
+
+}
+
+TriangleMesh::~TriangleMesh()
+{
+    free(mVertexData);
+    free(mIndexData);
+}
+
+
+
+TriangleMeshContext::TriangleMeshContext()
+{
+    clear();
+}
+
+TriangleMeshContext::~TriangleMeshContext()
+{
+}
+
+void TriangleMeshContext::clear()
+{
+    mVertexElement = NULL;
+    mVertexSizeBits = 0;
+    mIndexElement = NULL;
+    mIndexSizeBits = 0;
+    mTriangleCount = 0;
+    mVertexData.clear();
+    mIndexData.clear();
+}
+
+void TriangleMesh::analyzeElement()
+{
+    for (uint32_t ct=0; ct < mVertexElement->getComponentCount(); ct++) {
+        const Component *c = mVertexElement->getComponent(ct);
+
+        if (c->getKind() == Component::X) {
+            rsAssert(mSizeCoord == 0);
+            mSizeCoord = 1;
+            mOffsetCoord = ct;
+        }
+        if (c->getKind() == Component::Y) {
+            rsAssert(mSizeCoord == 1);
+            mSizeCoord = 2;
+        }
+        if (c->getKind() == Component::Z) {
+            rsAssert(mSizeCoord == 2);
+            mSizeCoord = 3;
+        }
+        if (c->getKind() == Component::W) {
+            rsAssert(mSizeCoord == 4);
+            mSizeCoord = 4;
+        }
+
+        if (c->getKind() == Component::NX) {
+            rsAssert(mSizeNorm == 0);
+            mSizeNorm = 1;
+            mOffsetNorm = ct;
+        }
+        if (c->getKind() == Component::NY) {
+            rsAssert(mSizeNorm == 1);
+            mSizeNorm = 2;
+        }
+        if (c->getKind() == Component::NZ) {
+            rsAssert(mSizeNorm == 2);
+            mSizeNorm = 3;
+        }
+
+        if (c->getKind() == Component::S) {
+            rsAssert(mSizeTex == 0);
+            mSizeTex = 1;
+            mOffsetTex = ct;
+        }
+        if (c->getKind() == Component::T) {
+            rsAssert(mSizeTex == 1);
+            mSizeTex = 2;
+        }
+    }
+    LOGV("TriangleMesh %i,%i  %i,%i  %i,%i", mSizeCoord, mOffsetCoord, mSizeNorm, mOffsetNorm, mSizeTex, mOffsetTex);
+
+}
+
+
+namespace android {
+namespace renderscript {
+
+void rsi_TriangleMeshBegin(Context *rsc, RsElement vertex, RsElement index)
+{
+    TriangleMeshContext *tmc = &rsc->mStateTriangleMesh;
+
+    tmc->clear();
+    tmc->mVertexElement = static_cast<Element *>(vertex);
+    tmc->mVertexSizeBits = tmc->mVertexElement->getSizeBits();
+    tmc->mIndexElement = static_cast<Element *>(index);
+    tmc->mIndexSizeBits = tmc->mIndexElement->getSizeBits();
+
+    assert(!(tmc->mVertexSizeBits & 0x7));
+    assert(!(tmc->mIndexSizeBits & 0x7));
+}
+
+void rsi_TriangleMeshAddVertex(Context *rsc, const void *data)
+{
+    TriangleMeshContext *tmc = &rsc->mStateTriangleMesh;
+
+    // todo: Make this efficient.
+    for (uint32_t ct = 0; (ct * 8) < tmc->mVertexSizeBits; ct++) {
+        tmc->mVertexData.add(static_cast<const uint8_t *>(data) [ct]);
+    }
+}
+
+void rsi_TriangleMeshAddTriangle(Context *rsc, uint32_t idx1, uint32_t idx2, uint32_t idx3)
+{
+    TriangleMeshContext *tmc = &rsc->mStateTriangleMesh;
+
+    // todo: Make this efficient.
+    switch(tmc->mIndexSizeBits) {
+    case 16:
+        tmc->mIndexData.add(idx1);
+        tmc->mIndexData.add(idx2);
+        tmc->mIndexData.add(idx3);
+        break;
+    default:
+        assert(0);
+    }
+
+    tmc->mTriangleCount++;
+}
+
+RsTriangleMesh rsi_TriangleMeshCreate(Context *rsc)
+{
+    TriangleMeshContext *tmc = &rsc->mStateTriangleMesh;
+
+    TriangleMesh * tm = new TriangleMesh();
+    if (!tm) {
+        LOGE("rsTriangleMeshCreate: Error OUT OF MEMORY");
+        // error
+        return 0;
+    }
+
+    tm->mTriangleCount = tmc->mTriangleCount;
+    tm->mIndexDataSize = tmc->mIndexData.size() * tmc->mIndexSizeBits >> 3;
+    tm->mVertexDataSize = tmc->mVertexData.size();
+    tm->mIndexElement = tmc->mIndexElement;
+    tm->mVertexElement = tmc->mVertexElement;
+
+    tm->mIndexData = malloc(tm->mIndexDataSize);
+    tm->mVertexData = malloc(tm->mVertexDataSize);
+    if (!tm->mIndexData || !tm->mVertexData) {
+        LOGE("rsTriangleMeshCreate: Error OUT OF MEMORY");
+        delete tm;
+        return 0;
+    }
+
+    memcpy(tm->mVertexData, tmc->mVertexData.array(), tm->mVertexDataSize);
+    memcpy(tm->mIndexData, tmc->mIndexData.array(), tm->mIndexDataSize);
+    tm->analyzeElement();
+
+    return tm;
+}
+
+void rsi_TriangleMeshDestroy(Context *rsc, RsTriangleMesh vtm)
+{
+    TriangleMeshContext *tmc = &rsc->mStateTriangleMesh;
+    TriangleMesh * tm = static_cast<TriangleMesh *>(vtm);
+
+    free(tm->mIndexData);
+    free(tm->mVertexData);
+    delete tm;
+}
+
+
+
+void rsi_TriangleMeshRenderRange(Context *rsc, RsTriangleMesh vtm, uint32_t first, uint32_t count)
+{
+    TriangleMesh * tm = static_cast<TriangleMesh *>(vtm);
+
+    rsc->setupCheck();
+
+    if (!tm->mBufferObjects[0]) {
+        glGenBuffers(2, &tm->mBufferObjects[0]);
+
+        glBindBuffer(GL_ARRAY_BUFFER, tm->mBufferObjects[0]);
+        glBufferData(GL_ARRAY_BUFFER, tm->mVertexDataSize, tm->mVertexData, GL_STATIC_DRAW);
+        glBindBuffer(GL_ARRAY_BUFFER, 0);
+
+        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, tm->mBufferObjects[1]);
+        glBufferData(GL_ELEMENT_ARRAY_BUFFER, tm->mIndexDataSize, tm->mIndexData, GL_STATIC_DRAW);
+        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+    }
+
+    if (first >= tm->mTriangleCount) {
+        return;
+    }
+    if (count >= (tm->mTriangleCount - first)) {
+        count = tm->mTriangleCount - first;
+    }
+    if (!count) {
+        return;
+    }
+
+    const float *f = (const float *)tm->mVertexData;
+
+    glBindBuffer(GL_ARRAY_BUFFER, tm->mBufferObjects[0]);
+    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, tm->mBufferObjects[1]);
+
+    glEnableClientState(GL_VERTEX_ARRAY);
+    glVertexPointer(tm->mSizeCoord, 
+                    GL_FLOAT, 
+                    tm->mVertexElement->getSizeBytes(), 
+                    (void *)tm->mVertexElement->getComponentOffsetBytes(tm->mOffsetCoord));
+
+    if (tm->mSizeTex) {
+        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+        glTexCoordPointer(tm->mSizeTex, 
+                          GL_FLOAT, 
+                          tm->mVertexElement->getSizeBytes(), 
+                          (void *)tm->mVertexElement->getComponentOffsetBytes(tm->mOffsetTex));
+    } else {
+        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+    }
+
+    if (tm->mSizeNorm) {
+        glEnableClientState(GL_NORMAL_ARRAY);
+        glNormalPointer(GL_FLOAT, 
+                        tm->mVertexElement->getSizeBytes(), 
+                        (void *)tm->mVertexElement->getComponentOffsetBytes(tm->mOffsetNorm));
+    } else {
+        glDisableClientState(GL_NORMAL_ARRAY);
+    }
+
+    glDrawElements(GL_TRIANGLES, count * 3, GL_UNSIGNED_SHORT, (GLvoid *)(first * 3 * 2));
+
+    glBindBuffer(GL_ARRAY_BUFFER, 0);
+    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+}
+
+void rsi_TriangleMeshRender(Context *rsc, RsTriangleMesh vtm)
+{
+    rsi_TriangleMeshRenderRange(rsc, vtm, 0, 0xffffff);
+}
+
+}}
diff --git a/libs/rs/rsTriangleMesh.h b/libs/rs/rsTriangleMesh.h
new file mode 100644
index 0000000..e56c7c2
--- /dev/null
+++ b/libs/rs/rsTriangleMesh.h
@@ -0,0 +1,83 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_TRIANGLE_MESH_H
+#define ANDROID_RS_TRIANGLE_MESH_H
+
+
+#include "RenderScript.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+
+// An element is a group of Components that occupies one cell in a structure.
+class TriangleMesh : public ObjectBase
+{
+public:
+    TriangleMesh();
+    ~TriangleMesh();
+
+    const Element * mVertexElement;
+    const Element * mIndexElement;
+
+    void * mVertexData;
+    void * mIndexData;
+
+    size_t mVertexDataSize;
+    size_t mIndexDataSize;
+    uint32_t mTriangleCount;
+
+    size_t mOffsetCoord;
+    size_t mOffsetTex;
+    size_t mOffsetNorm;
+
+    size_t mSizeCoord;
+    size_t mSizeTex;
+    size_t mSizeNorm;
+
+    // GL buffer info
+    uint32_t mBufferObjects[2];
+
+    void analyzeElement();
+protected:
+};
+
+class TriangleMeshContext
+{
+public:
+    TriangleMeshContext();
+    ~TriangleMeshContext();
+
+    const Element * mVertexElement;
+    const Element * mIndexElement;
+    size_t mVertexSizeBits;
+    size_t mIndexSizeBits;
+
+    Vector<uint8_t> mVertexData; 
+    Vector<uint16_t> mIndexData; 
+
+    uint32_t mTriangleCount;
+
+    void clear();
+};
+
+
+}
+}
+#endif //ANDROID_RS_TRIANGLE_MESH_H
+
diff --git a/libs/rs/rsType.cpp b/libs/rs/rsType.cpp
new file mode 100644
index 0000000..bbe9720
--- /dev/null
+++ b/libs/rs/rsType.cpp
@@ -0,0 +1,222 @@
+/*
+ * 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.
+ */
+
+#include "rsContext.h"
+
+using namespace android;
+using namespace android::renderscript;
+
+Type::Type()
+{
+    mLODs = 0;
+    mLODCount = 0;
+    clear();
+}
+
+Type::~Type()
+{
+    if (mLODs) {
+        delete [] mLODs;
+    }
+}
+
+void Type::clear()
+{
+    if (mLODs) {
+        delete [] mLODs;
+        mLODs = NULL;
+    }
+    mDimX = 0;
+    mDimY = 0;
+    mDimZ = 0;
+    mDimLOD = 0;
+    mFaces = false;
+    mElement.clear();
+}
+
+TypeState::TypeState()
+{
+}
+
+TypeState::~TypeState()
+{
+}
+
+size_t Type::getOffsetForFace(uint32_t face) const
+{
+    rsAssert(mFaces);
+    return 0;
+}
+
+void Type::compute()
+{
+    uint32_t oldLODCount = mLODCount;
+    if (mDimLOD) {
+        uint32_t l2x = rsFindHighBit(mDimX) + 1;
+        uint32_t l2y = rsFindHighBit(mDimY) + 1;
+        uint32_t l2z = rsFindHighBit(mDimZ) + 1;
+
+        mLODCount = rsMax(l2x, l2y);
+        mLODCount = rsMax(mLODCount, l2z);
+    } else {
+        mLODCount = 1;
+    }
+    if (mLODCount != oldLODCount) {
+        delete [] mLODs;
+        mLODs = new LOD[mLODCount];
+    }
+
+    uint32_t tx = mDimX;
+    uint32_t ty = mDimY;
+    uint32_t tz = mDimZ;
+    size_t offset = 0;
+    for (uint32_t lod=0; lod < mLODCount; lod++) {
+        mLODs[lod].mX = tx;
+        mLODs[lod].mY = ty;
+        mLODs[lod].mZ = tz;
+        mLODs[lod].mOffset = offset;
+        offset += tx * rsMax(ty, 1u) * rsMax(tz, 1u) * mElement->getSizeBytes();
+        tx = (tx + 1) >> 1;
+        ty = (ty + 1) >> 1;
+        tz = (tz + 1) >> 1;
+    }
+
+    // At this point the offset is the size of a mipmap chain;
+    mMipChainSizeBytes = offset;
+
+    if (mFaces) {
+        offset *= 6;
+    }
+    mTotalSizeBytes = offset;
+
+}
+
+uint32_t Type::getLODOffset(uint32_t lod, uint32_t x) const
+{
+    uint32_t offset = mLODs[lod].mOffset;
+    offset += x * mElement->getSizeBytes();
+    return offset;
+}
+
+uint32_t Type::getLODOffset(uint32_t lod, uint32_t x, uint32_t y) const
+{
+    uint32_t offset = mLODs[lod].mOffset;
+    offset += (x + y * mLODs[lod].mX) * mElement->getSizeBytes();
+    return offset;
+}
+
+uint32_t Type::getLODOffset(uint32_t lod, uint32_t x, uint32_t y, uint32_t z) const
+{
+    uint32_t offset = mLODs[lod].mOffset;
+    offset += (x + y*mLODs[lod].mX + z*mLODs[lod].mX*mLODs[lod].mY) * mElement->getSizeBytes();
+    return offset;
+}
+
+
+//////////////////////////////////////////////////
+// 
+namespace android {
+namespace renderscript {
+
+void rsi_TypeBegin(Context *rsc, RsElement vse)
+{
+    TypeState * stc = &rsc->mStateType;
+
+    stc->mX = 0;
+    stc->mY = 0;
+    stc->mZ = 0;
+    stc->mLOD = false;
+    stc->mFaces = false;
+    stc->mElement.set(static_cast<const Element *>(vse));
+}
+
+void rsi_TypeAdd(Context *rsc, RsDimension dim, size_t value)
+{
+    TypeState * stc = &rsc->mStateType;
+
+    if (dim < 0) {
+        //error
+        return;
+    }
+
+
+    switch (dim) {
+    case RS_DIMENSION_X:
+        stc->mX = value;
+        return;
+    case RS_DIMENSION_Y:
+        stc->mY = value;
+        return;
+    case RS_DIMENSION_Z:
+        stc->mZ = value;
+        return;
+    case RS_DIMENSION_FACE:
+        stc->mFaces = (value != 0);
+        return;
+    case RS_DIMENSION_LOD:
+        stc->mLOD = (value != 0);
+        return;
+    default:
+        break;
+    }
+
+
+    int32_t arrayNum = dim - RS_DIMENSION_ARRAY_0;
+    if ((dim < 0) || (dim > RS_DIMENSION_MAX)) {
+        LOGE("rsTypeAdd: Bad dimension");
+        //error
+        return;
+    }
+
+    // todo: implement array support
+
+}
+
+RsType rsi_TypeCreate(Context *rsc)
+{
+    TypeState * stc = &rsc->mStateType;
+
+    Type * st = new Type();
+    st->setDimX(stc->mX);
+    st->setDimY(stc->mY);
+    st->setDimZ(stc->mZ);
+    st->setElement(stc->mElement.get());
+    st->setDimLOD(stc->mLOD);
+    st->setDimFaces(stc->mFaces);
+    st->compute();
+
+    stc->mAllTypes.add(st);
+
+    return st;
+}
+
+void rsi_TypeDestroy(Context *rsc, RsType vst)
+{
+    TypeState * stc = &rsc->mStateType;
+    Type * st = static_cast<Type *>(vst);
+
+    for (size_t ct = 0; ct < stc->mAllTypes.size(); ct++) {
+        if (stc->mAllTypes[ct] == st) {
+            stc->mAllTypes.removeAt(ct);
+            break;
+        }
+    }
+    delete st;
+}
+
+}
+}
+
diff --git a/libs/rs/rsType.h b/libs/rs/rsType.h
new file mode 100644
index 0000000..a717893
--- /dev/null
+++ b/libs/rs/rsType.h
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_STRUCTURED_TYPE_H
+#define ANDROID_STRUCTURED_TYPE_H
+
+#include "rsElement.h"
+
+// ---------------------------------------------------------------------------
+namespace android {
+namespace renderscript {
+
+    
+class Type : public ObjectBase
+{
+public:
+    Type();
+    virtual ~Type();
+
+    Type * createTex2D(const Element *, size_t w, size_t h, bool mip);
+
+
+    size_t getOffsetForFace(uint32_t face) const;
+
+    size_t getSizeBytes() const {return mTotalSizeBytes;}
+    size_t getElementSizeBytes() const {return mElement->getSizeBytes();}
+    const Element * getElement() const {return mElement.get();}
+
+    uint32_t getDimX() const {return mDimX;}
+    uint32_t getDimY() const {return mDimY;}
+    uint32_t getDimZ() const {return mDimZ;}
+    uint32_t getDimLOD() const {return mDimLOD;}
+    bool getDimFaces() const {return mFaces;}
+
+    uint32_t getLODDimX(uint32_t lod) const {rsAssert(lod < mLODCount); return mLODs[lod].mX;}
+    uint32_t getLODDimY(uint32_t lod) const {rsAssert(lod < mLODCount); return mLODs[lod].mY;}
+    uint32_t getLODDimZ(uint32_t lod) const {rsAssert(lod < mLODCount); return mLODs[lod].mZ;}
+    uint32_t getLODOffset(uint32_t lod) const {rsAssert(lod < mLODCount); return mLODs[lod].mOffset;}
+
+    uint32_t getLODOffset(uint32_t lod, uint32_t x) const;
+    uint32_t getLODOffset(uint32_t lod, uint32_t x, uint32_t y) const;
+    uint32_t getLODOffset(uint32_t lod, uint32_t x, uint32_t y, uint32_t z) const;
+
+    uint32_t getLODCount() const {return mLODCount;}
+
+
+    void setElement(const Element *e) {mElement.set(e);}
+    void setDimX(uint32_t v) {mDimX = v;}
+    void setDimY(uint32_t v) {mDimY = v;}
+    void setDimZ(uint32_t v) {mDimZ = v;}
+    void setDimFaces(bool v) {mFaces = v;}
+    void setDimLOD(bool v) {mDimLOD = v;}
+
+    void clear();
+    void compute();
+
+
+protected:
+    struct LOD {
+        size_t mX;
+        size_t mY;
+        size_t mZ;
+        size_t mOffset;
+    };
+
+    void makeLODTable();
+
+    // Internal structure from most to least significant.
+    // * Array dimensions
+    // * Faces
+    // * Mipmaps
+    // * xyz
+
+    ObjectBaseRef<const Element> mElement;
+
+    // Size of the structure in the various dimensions.  A missing Dimension is
+    // specified as a 0 and not a 1.
+    size_t mDimX;
+    size_t mDimY;
+    size_t mDimZ;
+    bool mDimLOD;
+    bool mFaces;
+
+    // A list of array dimensions.  The count is the number of array dimensions and the 
+    // sizes is a per array size.
+    //Vector<size_t> mDimArraysSizes;
+
+    // count of mipmap levels, 0 indicates no mipmapping
+
+    size_t mMipChainSizeBytes;
+    size_t mTotalSizeBytes;
+    LOD *mLODs;
+    uint32_t mLODCount;
+
+private:
+    Type(const Type &);
+};
+
+
+class TypeState {
+public:
+    TypeState();
+    ~TypeState();
+
+    Vector<Type *> mAllTypes;
+
+    size_t mX;
+    size_t mY;
+    size_t mZ;
+    uint32_t mLOD;
+    bool mFaces;
+    ObjectBaseRef<const Element> mElement;
+
+
+    
+};
+
+
+}
+}
+#endif //ANDROID_STRUCTURED_TYPE
diff --git a/libs/rs/rsUtils.h b/libs/rs/rsUtils.h
new file mode 100644
index 0000000..b13e88f
--- /dev/null
+++ b/libs/rs/rsUtils.h
@@ -0,0 +1,128 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RS_UTILS_H
+#define ANDROID_RS_UTILS_H
+
+#define LOG_NDEBUG 0 
+#define LOG_TAG "rs"
+#include <utils/Log.h>
+#include <utils/Vector.h>
+#include <stdlib.h>
+#include <pthread.h>
+
+#include <EGL/egl.h>
+#include <math.h>
+
+#include "RenderScript.h"
+
+namespace android {
+namespace renderscript {
+
+#if 1
+#define rsAssert(v) do {if(!(v)) LOGE("rsAssert failed: %s, in %s at %i", #v, __FILE__, __LINE__);} while(0)
+#else
+#define rsAssert(v) while(0)
+#endif
+
+template<typename T>
+T rsMin(T in1, T in2)
+{
+    if (in1 > in2) {
+        return in2;
+    }
+    return in1;
+}
+
+template<typename T>
+T rsMax(T in1, T in2)
+{
+    if (in1 < in2) {
+        return in2;
+    }
+    return in1;
+}
+
+template<typename T>
+T rsFindHighBit(T val)
+{
+    uint32_t bit = 0;
+    while(val > 1) {
+        bit++;
+        val>>=1;
+    }
+    return bit;
+}
+
+template<typename T>
+bool rsIsPow2(T val)
+{
+    return (val & (val-1)) == 0;
+}
+
+template<typename T>
+T rsHigherPow2(T v)
+{
+    if (rsIsPow2(v)) {
+        return v;
+    }
+    return 1 << (rsFindHighBit(v) + 1);
+}
+
+template<typename T>
+T rsLowerPow2(T v)
+{
+    if (rsIsPow2(v)) {
+        return v;
+    }
+    return 1 << rsFindHighBit(v);
+}
+
+
+static inline uint16_t rs888to565(uint32_t r, uint32_t g, uint32_t b)
+{
+    uint16_t t = 0;
+    t |= b >> 3;
+    t |= (g >> 2) << 5;
+    t |= (r >> 3) << 11;
+    return t;
+}
+
+static inline uint16_t rsBoxFilter565(uint16_t i1, uint16_t i2, uint16_t i3, uint16_t i4)
+{
+    uint32_t r = ((i1 & 0x1f) + (i2 & 0x1f) + (i3 & 0x1f) + (i4 & 0x1f));
+    uint32_t g = ((i1 >> 5) & 0x3f) + ((i2 >> 5) & 0x3f) + ((i3 >> 5) & 0x3f) + ((i4 >> 5) & 0x3f);
+    uint32_t b = ((i1 >> 11) + (i2 >> 11) + (i3 >> 11) + (i4 >> 11));
+    return (r >> 2) | ((g >> 2) << 5) | ((b >> 2) << 11);
+}
+
+static inline uint32_t rsBoxFilter8888(uint32_t i1, uint32_t i2, uint32_t i3, uint32_t i4)
+{
+    uint32_t r = (i1 & 0xff) +         (i2 & 0xff) +         (i3 & 0xff) +         (i4 & 0xff);
+    uint32_t g = ((i1 >> 8) & 0xff) +  ((i2 >> 8) & 0xff) +  ((i3 >> 8) & 0xff) +  ((i4 >> 8) & 0xff);
+    uint32_t b = ((i1 >> 16) & 0xff) + ((i2 >> 16) & 0xff) + ((i3 >> 16) & 0xff) + ((i4 >> 16) & 0xff);
+    uint32_t a = ((i1 >> 24) & 0xff) + ((i2 >> 24) & 0xff) + ((i3 >> 24) & 0xff) + ((i4 >> 24) & 0xff);
+    return (r >> 2) | ((g >> 2) << 8) | ((b >> 2) << 16) | ((a >> 2) << 24);
+}
+
+
+
+}
+}
+
+#endif //ANDROID_RS_OBJECT_BASE_H
+
+
diff --git a/libs/rs/rsgApi.cpp.rsg b/libs/rs/rsgApi.cpp.rsg
new file mode 100644
index 0000000..0cfbf08
--- /dev/null
+++ b/libs/rs/rsgApi.cpp.rsg
@@ -0,0 +1 @@
+2
diff --git a/libs/rs/rsgApiFuncDecl.h.rsg b/libs/rs/rsgApiFuncDecl.h.rsg
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/libs/rs/rsgApiFuncDecl.h.rsg
@@ -0,0 +1 @@
+1
diff --git a/libs/rs/rsgApiReplay.cpp.rsg b/libs/rs/rsgApiReplay.cpp.rsg
new file mode 100644
index 0000000..00750ed
--- /dev/null
+++ b/libs/rs/rsgApiReplay.cpp.rsg
@@ -0,0 +1 @@
+3
diff --git a/libs/rs/rsgApiStructs.h.rsg b/libs/rs/rsgApiStructs.h.rsg
new file mode 100644
index 0000000..573541a
--- /dev/null
+++ b/libs/rs/rsgApiStructs.h.rsg
@@ -0,0 +1 @@
+0
diff --git a/libs/rs/rsg_generator.c b/libs/rs/rsg_generator.c
new file mode 100644
index 0000000..a4d659d
--- /dev/null
+++ b/libs/rs/rsg_generator.c
@@ -0,0 +1,291 @@
+
+
+#include "lex.yy.c"
+
+void printFileHeader(FILE *f)
+{
+    fprintf(f, "/*\n");
+    fprintf(f, " * Copyright (C) 2009 The Android Open Source Project\n");
+    fprintf(f, " *\n");
+    fprintf(f, " * Licensed under the Apache License, Version 2.0 (the \"License\");\n");
+    fprintf(f, " * you may not use this file except in compliance with the License.\n");
+    fprintf(f, " * You may obtain a copy of the License at\n");
+    fprintf(f, " *\n");
+    fprintf(f, " *      http://www.apache.org/licenses/LICENSE-2.0\n");
+    fprintf(f, " *\n");
+    fprintf(f, " * Unless required by applicable law or agreed to in writing, software\n");
+    fprintf(f, " * distributed under the License is distributed on an \"AS IS\" BASIS,\n");
+    fprintf(f, " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n");
+    fprintf(f, " * See the License for the specific language governing permissions and\n");
+    fprintf(f, " * limitations under the License.\n");
+    fprintf(f, " */\n\n");
+}
+
+void printVarType(FILE *f, const VarType *vt)
+{
+    int ct;
+    if (vt->isConst) {
+        fprintf(f, "const ");
+    }
+
+    switch(vt->type) {
+    case 0:
+        fprintf(f, "void");
+        break;
+    case 1:
+        fprintf(f, "int%i_t", vt->bits);
+        break;
+    case 2:
+        fprintf(f, "uint%i_t", vt->bits);
+        break;
+    case 3:
+        if (vt->bits == 32)
+            fprintf(f, "float");
+        else
+            fprintf(f, "double");
+        break;
+    case 4:
+        fprintf(f, "%s", vt->typename);
+        break;
+    }
+
+    if(vt->ptrLevel) {
+        fprintf(f, " ");
+        for(ct=0; ct < vt->ptrLevel; ct++) {
+            fprintf(f, "*");
+        }
+    }
+
+    if(vt->name[0]) {
+        fprintf(f, " %s", vt->name);
+    }
+}
+
+void printArgList(FILE *f, const ApiEntry * api, int assumePrevious)
+{
+    int ct;
+    for(ct=0; ct < api->paramCount; ct++) {
+        if (ct || assumePrevious) {
+            fprintf(f, ", ");
+        }
+        printVarType(f, &api->params[ct]);
+    }
+}
+
+void printStructures(FILE *f)
+{
+    int ct;
+    int ct2;
+
+    for(ct=0; ct < apiCount; ct++) {
+        fprintf(f, "typedef struct RS_CMD_%s_rec RS_CMD_%s;\n", apis[ct].name, apis[ct].name);
+    }
+    fprintf(f, "\n");
+
+    for(ct=0; ct < apiCount; ct++) {
+        const ApiEntry * api = &apis[ct];
+        fprintf(f, "#define RS_CMD_ID_%s %i\n", api->name, ct+1);
+        fprintf(f, "struct RS_CMD_%s_rec {\n", api->name);
+        //fprintf(f, "    RsCommandHeader _hdr;\n");
+
+        for(ct2=0; ct2 < api->paramCount; ct2++) {
+            fprintf(f, "    ");
+            printVarType(f, &api->params[ct2]);
+            fprintf(f, ";\n");
+        }
+        fprintf(f, "};\n\n");
+    }
+}
+
+void printFuncDecl(FILE *f, const ApiEntry *api, const char *prefix, int addContext)
+{
+    printVarType(f, &api->ret);
+    fprintf(f, " %s%s (", prefix, api->name);
+    if (addContext) {
+        fprintf(f, "Context *");
+    }
+    printArgList(f, api, addContext);
+    fprintf(f, ")");
+}
+
+void printFuncDecls(FILE *f, const char *prefix, int addContext)
+{
+    int ct;
+    for(ct=0; ct < apiCount; ct++) {
+        printFuncDecl(f, &apis[ct], prefix, addContext);
+        fprintf(f, ";\n");
+    }
+    fprintf(f, "\n\n");
+}
+
+void printPlaybackFuncs(FILE *f, const char *prefix)
+{
+    int ct;
+    for(ct=0; ct < apiCount; ct++) {
+        fprintf(f, "void %s%s (Context *, const void *);\n", prefix, apis[ct].name);
+    }
+}
+
+void printApiCpp(FILE *f)
+{
+    int ct;
+    int ct2;
+
+    fprintf(f, "#include \"rsDevice.h\"\n");
+    fprintf(f, "#include \"rsContext.h\"\n");
+    fprintf(f, "#include \"rsThreadIO.h\"\n");
+    //fprintf(f, "#include \"rsgApiStructs.h\"\n");
+    fprintf(f, "#include \"rsgApiFuncDecl.h\"\n");
+    fprintf(f, "\n");
+    fprintf(f, "using namespace android;\n");
+    fprintf(f, "using namespace android::renderscript;\n");
+    fprintf(f, "\n");
+
+    for(ct=0; ct < apiCount; ct++) {
+        int needFlush = 0;
+        const ApiEntry * api = &apis[ct];
+
+        printFuncDecl(f, api, "rs", 0);
+        fprintf(f, "\n{\n");
+        fprintf(f, "    ThreadIO *io = gIO;\n");
+        //fprintf(f, "    LOGE(\"add command %s\\n\");\n", api->name);
+        fprintf(f, "    RS_CMD_%s *cmd = static_cast<RS_CMD_%s *>(io->mToCore.reserve(sizeof(RS_CMD_%s)));\n", api->name, api->name, api->name);
+        fprintf(f, "    uint32_t size = sizeof(RS_CMD_%s);\n", api->name);
+
+        for(ct2=0; ct2 < api->paramCount; ct2++) {
+            const VarType *vt = &api->params[ct2];
+            needFlush += vt->ptrLevel;
+            fprintf(f, "    cmd->%s = %s;\n", vt->name, vt->name);
+        }
+        if (api->ret.typename[0]) {
+            needFlush = 1;
+        }
+
+        fprintf(f, "    io->mToCore.commit");
+        if (needFlush) {
+            fprintf(f, "Sync");
+        }
+        fprintf(f, "(RS_CMD_ID_%s, size);\n", api->name);
+
+        if (api->ret.typename[0]) {
+            fprintf(f, "    return reinterpret_cast<");
+            printVarType(f, &api->ret);
+            fprintf(f, ">(io->mToCoreRet);\n");
+        }
+        fprintf(f, "};\n\n");
+    }
+}
+
+void printPlaybackCpp(FILE *f)
+{
+    int ct;
+    int ct2;
+
+    fprintf(f, "#include \"rsDevice.h\"\n");
+    fprintf(f, "#include \"rsContext.h\"\n");
+    fprintf(f, "#include \"rsThreadIO.h\"\n");
+    //fprintf(f, "#include \"rsgApiStructs.h\"\n");
+    fprintf(f, "#include \"rsgApiFuncDecl.h\"\n");
+    fprintf(f, "\n");
+    fprintf(f, "namespace android {\n");
+    fprintf(f, "namespace renderscript {\n");
+    fprintf(f, "\n");
+
+    for(ct=0; ct < apiCount; ct++) {
+        const ApiEntry * api = &apis[ct];
+
+        fprintf(f, "void rsp_%s(Context *con, const void *vp)\n", api->name);
+        fprintf(f, "{\n");
+        //fprintf(f, "    LOGE(\"play command %s\\n\");\n", api->name);
+        fprintf(f, "    const RS_CMD_%s *cmd = static_cast<const RS_CMD_%s *>(vp);\n", api->name, api->name);
+        fprintf(f, "    ");
+        if (api->ret.typename[0]) {
+            fprintf(f, "gIO->mToCoreRet = (intptr_t)");
+        }
+        fprintf(f, "rsi_%s(con", api->name);
+        for(ct2=0; ct2 < api->paramCount; ct2++) {
+            const VarType *vt = &api->params[ct2];
+            fprintf(f, ",");
+            fprintf(f, "\n           cmd->%s", vt->name);
+        }
+        fprintf(f, ");\n");
+
+        fprintf(f, "};\n\n");
+    }
+
+    fprintf(f, "RsPlaybackFunc gPlaybackFuncs[] = {\n");
+    fprintf(f, "    NULL,\n");
+    for(ct=0; ct < apiCount; ct++) {
+        fprintf(f, "    %s%s,\n", "rsp_", apis[ct].name);
+    }
+    fprintf(f, "};\n");
+
+    fprintf(f, "};\n");
+    fprintf(f, "};\n");
+}
+
+int main(int argc, char **argv)
+{
+    if (argc != 3) {
+        fprintf(stderr, "usage: %s commandFile outFile\n", argv[0]);
+        return 1;
+    }
+    const char* rsgFile = argv[1];
+    const char* outFile = argv[2];
+    FILE* input = fopen(rsgFile, "r");
+
+    char choice = fgetc(input);
+    fclose(input);
+
+    if (choice < '0' || choice > '3') {
+        fprintf(stderr, "Uknown command: \'%c\'\n", choice);
+        return -2;
+    }
+
+    yylex();
+    // printf("# of lines = %d\n", num_lines);
+
+    FILE *f = fopen(outFile, "w");
+
+    printFileHeader(f);
+    switch(choice) {
+        case '0': // rsgApiStructs.h
+        {
+            fprintf(f, "\n");
+            fprintf(f, "#include \"rsContext.h\"\n");
+            fprintf(f, "\n");
+            fprintf(f, "namespace android {\n");
+            fprintf(f, "namespace renderscript {\n");
+            printStructures(f);
+            printFuncDecls(f, "rsi_", 1);
+            printPlaybackFuncs(f, "rsp_");
+            fprintf(f, "\n\ntypedef void (*RsPlaybackFunc)(Context *, const void *);\n");
+            fprintf(f, "extern RsPlaybackFunc gPlaybackFuncs[];\n");
+
+            fprintf(f, "}\n");
+            fprintf(f, "}\n");
+        }
+        break;
+
+        case '1': // rsgApiFuncDecl.h
+        {
+            printFuncDecls(f, "rs", 0);
+        }
+        break;
+
+        case '2': // rsgApi.cpp
+        {
+            printApiCpp(f);
+        }
+        break;
+
+        case '3': // rsgApiReplay.cpp
+        {
+            printFileHeader(f);
+            printPlaybackCpp(f);
+        }
+        break;
+    }
+    fclose(f);
+    return 0;
+}
diff --git a/libs/rs/spec.lex b/libs/rs/spec.lex
new file mode 100644
index 0000000..0f8e9ab
--- /dev/null
+++ b/libs/rs/spec.lex
@@ -0,0 +1,171 @@
+%option stack
+
+%x comment
+%x api_entry
+%x api_entry2
+%x api_entry_param
+%x var_type
+
+DIGIT    [0-9]
+ID       [a-zA-Z_][a-zA-Z0-9_]*
+
+
+   int num_lines = 0;
+
+   typedef struct {
+      int isConst;
+      int type;
+      int bits;
+      int ptrLevel;
+      char name[256];
+      char typename[256];
+   } VarType;
+
+   VarType *currType = 0;
+
+   typedef struct {
+      char name[256];
+      int sync;
+      int paramCount;
+      VarType ret;
+      VarType params[16];
+   } ApiEntry;
+
+   ApiEntry apis[128];
+   int apiCount = 0;
+
+   int typeNextState;
+
+%%
+
+"/*"         BEGIN(comment);
+<comment>[^*\n]*        /* eat anything that's not a '*' */
+<comment>"*"+[^*/\n]*   /* eat up '*'s not followed by '/'s */
+<comment>\n             ++num_lines;
+<comment>"*"+"/"        BEGIN(INITIAL);
+
+<*>" "   //printf("found ' '\n");
+<*>"\n"  ++num_lines; //printf("found lf \n");
+
+{ID} {
+    memset(&apis[apiCount], 0, sizeof(ApiEntry));
+    memcpy(apis[apiCount].name, yytext, yyleng);
+    BEGIN(api_entry);
+    }
+
+<api_entry>"{" {
+    BEGIN(api_entry2);
+    }
+
+<api_entry2>"sync" {
+    apis[apiCount].sync = 1;
+    }
+
+<api_entry2>"ret" {
+    currType = &apis[apiCount].ret;
+    typeNextState = api_entry2;
+    BEGIN(var_type);
+    }
+
+<api_entry2>"param" {
+    currType = &apis[apiCount].params[apis[apiCount].paramCount];
+    apis[apiCount].paramCount++;
+    typeNextState = api_entry_param;
+    BEGIN(var_type);
+    }
+
+<var_type>"const" {
+    currType->isConst = 1;
+    }
+
+<var_type>"i8" {
+    currType->type = 1;
+    currType->bits = 8;
+    BEGIN(typeNextState);
+    }
+
+<var_type>"i16" {
+    currType->type = 1;
+    currType->bits = 16;
+    BEGIN(typeNextState);
+    }
+
+<var_type>"i32" {
+    currType->type = 1;
+    currType->bits = 32;
+    BEGIN(typeNextState);
+    }
+
+<var_type>"i64" {
+    currType->type = 1;
+    currType->bits = 64;
+    BEGIN(typeNextState);
+    }
+
+<var_type>"u8" {
+    currType->type = 2;
+    currType->bits = 8;
+    BEGIN(typeNextState);
+    }
+
+<var_type>"u16" {
+    currType->type = 2;
+    currType->bits = 16;
+    BEGIN(typeNextState);
+    }
+
+<var_type>"u32" {
+    currType->type = 2;
+    currType->bits = 32;
+    BEGIN(typeNextState);
+    }
+
+<var_type>"u64" {
+    currType->type = 2;
+    currType->bits = 64;
+    BEGIN(typeNextState);
+    }
+
+<var_type>"f" {
+    currType->type = 3;
+    currType->bits = 32;
+    BEGIN(typeNextState);
+    }
+
+<var_type>"d" {
+    currType->type = 3;
+    currType->bits = 64;
+    BEGIN(typeNextState);
+    }
+
+<var_type>{ID} {
+    currType->type = 4;
+    currType->bits = 32;
+    memcpy(currType->typename, yytext, yyleng);
+    BEGIN(typeNextState);
+    }
+
+<api_entry_param>"*" {
+    currType->ptrLevel ++;
+    }
+
+<api_entry_param>{ID} {
+    memcpy(currType->name, yytext, yyleng);
+    BEGIN(api_entry2);
+    }
+
+
+<api_entry2>"}" {
+    apiCount++;
+    BEGIN(INITIAL);
+    }
+
+
+%%
+
+
+int yywrap()
+{
+    return 1;
+}
+
diff --git a/libs/surfaceflinger/Android.mk b/libs/surfaceflinger/Android.mk
index ec5aa3f..88e76dc 100644
--- a/libs/surfaceflinger/Android.mk
+++ b/libs/surfaceflinger/Android.mk
@@ -5,44 +5,49 @@
     clz.cpp.arm \
     DisplayHardware/DisplayHardware.cpp \
     DisplayHardware/DisplayHardwareBase.cpp \
-    GPUHardware/GPUHardware.cpp \
     BlurFilter.cpp.arm \
-    CPUGauge.cpp \
+    BufferAllocator.cpp \
     Layer.cpp \
     LayerBase.cpp \
     LayerBuffer.cpp \
     LayerBlur.cpp \
     LayerBitmap.cpp \
     LayerDim.cpp \
-    LayerOrientationAnim.cpp \
-    OrientationAnimation.cpp \
+    MessageQueue.cpp \
     SurfaceFlinger.cpp \
     Tokenizer.cpp \
-    Transform.cpp \
-    VRamHeap.cpp
+    Transform.cpp
 
+LOCAL_CFLAGS:= -DLOG_TAG=\"SurfaceFlinger\"
+LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+
+ifeq ($(TARGET_BOARD_PLATFORM), msm7k)
+	LOCAL_CFLAGS += -DDIM_WITH_TEXTURE
+endif
 
 # need "-lrt" on Linux simulator to pick up clock_gettime
 ifeq ($(TARGET_SIMULATOR),true)
 	ifeq ($(HOST_OS),linux)
-		LOCAL_LDLIBS += -lrt
+		LOCAL_LDLIBS += -lrt -lpthread
 	endif
 endif
 
 LOCAL_SHARED_LIBRARIES := \
+	libcutils \
+	libpixelflinger \
 	libhardware \
 	libutils \
-	libcutils \
-	libui \
-	libcorecg \
-	libsgl \
-	libpixelflinger \
+	libskia \
 	libEGL \
-	libGLESv1_CM
+	libGLESv1_CM \
+	libbinder \
+	libui
 
 LOCAL_C_INCLUDES := \
 	$(call include-path-for, corecg graphics)
 
+LOCAL_C_INCLUDES += hardware/libhardware/modules/gralloc
+
 LOCAL_MODULE:= libsurfaceflinger
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/libs/surfaceflinger/BufferAllocator.cpp b/libs/surfaceflinger/BufferAllocator.cpp
new file mode 100644
index 0000000..cee8b64
--- /dev/null
+++ b/libs/surfaceflinger/BufferAllocator.cpp
@@ -0,0 +1,118 @@
+/* 
+**
+** Copyright 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.
+*/
+
+#include <sys/mman.h>
+#include <cutils/ashmem.h>
+#include <cutils/log.h>
+
+#include <utils/Singleton.h>
+#include <utils/String8.h>
+
+#include "BufferAllocator.h"
+
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+ANDROID_SINGLETON_STATIC_INSTANCE( BufferAllocator )
+
+Mutex BufferAllocator::sLock;
+KeyedVector<buffer_handle_t, BufferAllocator::alloc_rec_t> BufferAllocator::sAllocList;
+
+BufferAllocator::BufferAllocator()
+    : mAllocDev(0)
+{
+    hw_module_t const* module;
+    int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
+    LOGE_IF(err, "FATAL: can't find the %s module", GRALLOC_HARDWARE_MODULE_ID);
+    if (err == 0) {
+        gralloc_open(module, &mAllocDev);
+    }
+}
+
+BufferAllocator::~BufferAllocator()
+{
+    gralloc_close(mAllocDev);
+}
+
+void BufferAllocator::dump(String8& result) const
+{
+    Mutex::Autolock _l(sLock);
+    KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
+    size_t total = 0;
+    const size_t SIZE = 512;
+    char buffer[SIZE];
+    snprintf(buffer, SIZE, "Allocated buffers:\n");
+    result.append(buffer);
+    const size_t c = list.size();
+    for (size_t i=0 ; i<c ; i++) {
+        const alloc_rec_t& rec(list.valueAt(i));
+        snprintf(buffer, SIZE, "%10p: %7.2f KiB | %4u x %4u | %2d | 0x%08x\n",
+            list.keyAt(i), rec.size/1024.0f, 
+            rec.w, rec.h, rec.format, rec.usage);
+        result.append(buffer);
+        total += rec.size;
+    }
+    snprintf(buffer, SIZE, "Total allocated: %.2f KB\n", total/1024.0f);
+    result.append(buffer);
+}
+
+status_t BufferAllocator::alloc(uint32_t w, uint32_t h, PixelFormat format,
+        int usage, buffer_handle_t* handle, int32_t* stride)
+{
+    Mutex::Autolock _l(mLock);
+    
+    // we have a h/w allocator and h/w buffer is requested
+    status_t err = mAllocDev->alloc(mAllocDev,
+            w, h, format, usage, handle, stride);
+    LOGW_IF(err, "alloc(%u, %u, %d, %08x, ...) failed %d (%s)",
+            w, h, format, usage, err, strerror(-err));
+    
+    if (err == NO_ERROR) {
+        Mutex::Autolock _l(sLock);
+        KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
+        alloc_rec_t rec;
+        rec.w = w;
+        rec.h = h;
+        rec.format = format;
+        rec.usage = usage;
+        rec.vaddr = 0;
+        rec.size = h * stride[0] * bytesPerPixel(format);
+        list.add(*handle, rec);
+    }
+
+    return err;
+}
+
+status_t BufferAllocator::free(buffer_handle_t handle)
+{
+    Mutex::Autolock _l(mLock);
+
+    status_t err = mAllocDev->free(mAllocDev, handle);
+    LOGW_IF(err, "free(...) failed %d (%s)", err, strerror(-err));
+    
+    if (err == NO_ERROR) {
+        Mutex::Autolock _l(sLock);
+        KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
+        list.removeItem(handle);
+    }
+
+    return err;
+}
+
+// ---------------------------------------------------------------------------
+}; // namespace android
diff --git a/libs/surfaceflinger/BufferAllocator.h b/libs/surfaceflinger/BufferAllocator.h
new file mode 100644
index 0000000..a279ded
--- /dev/null
+++ b/libs/surfaceflinger/BufferAllocator.h
@@ -0,0 +1,96 @@
+/* 
+**
+** Copyright 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.
+*/
+
+#ifndef ANDROID_BUFFER_ALLOCATOR_H
+#define ANDROID_BUFFER_ALLOCATOR_H
+
+#include <stdint.h>
+
+#include <cutils/native_handle.h>
+
+#include <utils/Errors.h>
+#include <utils/KeyedVector.h>
+#include <utils/threads.h>
+#include <utils/Singleton.h>
+
+#include <ui/PixelFormat.h>
+
+#include <hardware/gralloc.h>
+
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+class String8;
+
+class BufferAllocator : public Singleton<BufferAllocator>
+{
+public:
+    enum {
+        USAGE_SW_READ_NEVER     = GRALLOC_USAGE_SW_READ_NEVER,
+        USAGE_SW_READ_RARELY    = GRALLOC_USAGE_SW_READ_RARELY,
+        USAGE_SW_READ_OFTEN     = GRALLOC_USAGE_SW_READ_OFTEN,
+        USAGE_SW_READ_MASK      = GRALLOC_USAGE_SW_READ_MASK,
+        
+        USAGE_SW_WRITE_NEVER    = GRALLOC_USAGE_SW_WRITE_NEVER,
+        USAGE_SW_WRITE_RARELY   = GRALLOC_USAGE_SW_WRITE_RARELY,
+        USAGE_SW_WRITE_OFTEN    = GRALLOC_USAGE_SW_WRITE_OFTEN,
+        USAGE_SW_WRITE_MASK     = GRALLOC_USAGE_SW_WRITE_MASK,
+        
+        USAGE_SOFTWARE_MASK     = USAGE_SW_READ_MASK|USAGE_SW_WRITE_MASK,
+        
+        USAGE_HW_TEXTURE        = GRALLOC_USAGE_HW_TEXTURE,
+        USAGE_HW_RENDER         = GRALLOC_USAGE_HW_RENDER,
+        USAGE_HW_2D             = GRALLOC_USAGE_HW_2D,
+        USAGE_HW_MASK           = GRALLOC_USAGE_HW_MASK
+    };
+
+    static inline BufferAllocator& get() { return getInstance(); }
+    
+
+    status_t alloc(uint32_t w, uint32_t h, PixelFormat format, int usage,
+            buffer_handle_t* handle, int32_t* stride);
+
+    status_t free(buffer_handle_t handle);
+
+    void dump(String8& res) const;
+
+private:
+    struct alloc_rec_t {
+        uint32_t w;
+        uint32_t h;
+        PixelFormat format;
+        uint32_t usage;
+        void* vaddr;
+        size_t size;
+    };
+    
+    static Mutex sLock;
+    static KeyedVector<buffer_handle_t, alloc_rec_t> sAllocList;
+    
+    friend class Singleton<BufferAllocator>;
+    BufferAllocator();
+    ~BufferAllocator();
+    
+    mutable Mutex mLock;
+    alloc_device_t  *mAllocDev;
+};
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_BUFFER_ALLOCATOR_H
diff --git a/libs/surfaceflinger/CPUGauge.cpp b/libs/surfaceflinger/CPUGauge.cpp
deleted file mode 100644
index 74a9270..0000000
--- a/libs/surfaceflinger/CPUGauge.cpp
+++ /dev/null
@@ -1,171 +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.
- */
-
-#define LOG_TAG "CPUGauge"
-
-#include <stdint.h>
-#include <limits.h>
-#include <sys/types.h>
-#include <math.h>
-
-#include <utils/threads.h>
-#include <utils/Errors.h>
-#include <utils/Log.h>
-
-#include <ui/PixelFormat.h>
-#include <ui/Rect.h>
-#include <ui/Region.h>
-#include <ui/DisplayInfo.h>
-#include <ui/ISurfaceComposer.h>
-#include <ui/ISurfaceFlingerClient.h>
-
-#include <pixelflinger/pixelflinger.h>
-
-#include "CPUGauge.h"
-
-namespace android {
-
-CPUGauge::CPUGauge( const sp<ISurfaceComposer>& composer,
-                    nsecs_t interval,
-                    int clock,
-                    int refclock)
-    :   Thread(false), 
-        mInterval(interval), mClock(clock), mRefClock(refclock),
-        mReferenceTime(0),
-        mReferenceWorkingTime(0), mCpuUsage(0),
-        mRefIdleTime(0), mIdleTime(0)
-{
-    mFd = fopen("/proc/stat", "r");
-    setvbuf(mFd, NULL, _IONBF, 0);
-
-    mSession = SurfaceComposerClient::clientForConnection(
-        composer->createConnection()->asBinder());
-}
-
-CPUGauge::~CPUGauge()
-{
-    fclose(mFd);
-}
-
-const sp<SurfaceComposerClient>& CPUGauge::session() const 
-{
-    return mSession;
-}
-
-void CPUGauge::onFirstRef()
-{
-    run("CPU Gauge");
-}
-
-status_t CPUGauge::readyToRun()
-{
-    LOGI("Starting CPU gauge...");
-    return NO_ERROR;
-}
-
-bool CPUGauge::threadLoop()
-{
-    DisplayInfo dinfo;
-    session()->getDisplayInfo(0, &dinfo);
-    sp<Surface> s(session()->createSurface(getpid(), 0, dinfo.w, 4, PIXEL_FORMAT_OPAQUE));
-    session()->openTransaction();
-    s->setLayer(INT_MAX);
-    session()->closeTransaction();
-    
-    static const GGLfixed colors[4][4] = {
-            { 0x00000, 0x10000, 0x00000, 0x10000 },
-            { 0x10000, 0x10000, 0x00000, 0x10000 },
-            { 0x10000, 0x00000, 0x00000, 0x10000 },
-            { 0x00000, 0x00000, 0x00000, 0x10000 },
-        };
-
-    GGLContext* gl;
-    gglInit(&gl);
-    gl->activeTexture(gl, 0);
-    gl->disable(gl, GGL_TEXTURE_2D);
-    gl->disable(gl, GGL_BLEND);
-
-    const int w = dinfo.w;
-
-    while(!exitPending())
-    {
-        mLock.lock();
-            const float cpuUsage = this->cpuUsage();
-            const float totalCpuUsage = 1.0f - idle();
-        mLock.unlock();
-
-        Surface::SurfaceInfo info;
-        s->lock(&info);
-            GGLSurface fb;
-                fb.version = sizeof(GGLSurface);
-                fb.width   = info.w;
-                fb.height  = info.h;
-                fb.stride  = info.w;
-                fb.format  = info.format;
-                fb.data = (GGLubyte*)info.bits;
-
-            gl->colorBuffer(gl, &fb);
-            gl->color4xv(gl, colors[3]);
-            gl->recti(gl, 0, 0, w, 4);
-            gl->color4xv(gl, colors[2]); // red
-            gl->recti(gl, 0, 0, int(totalCpuUsage*w), 2);
-            gl->color4xv(gl, colors[0]); // green
-            gl->recti(gl, 0, 2, int(cpuUsage*w), 4);
-        
-        s->unlockAndPost(); 
-
-        usleep(ns2us(mInterval));
-    }
-
-    gglUninit(gl);
-    return false;
-}
-
-void CPUGauge::sample()
-{
-    if (mLock.tryLock() == NO_ERROR) {
-        const nsecs_t now = systemTime(mRefClock);
-        const nsecs_t referenceTime = now-mReferenceTime;
-        if (referenceTime >= mInterval) {
-            const float reftime = 1.0f / referenceTime;
-            const nsecs_t nowWorkingTime = systemTime(mClock);
-            
-            char buf[256];
-            fgets(buf, 256, mFd);
-            rewind(mFd);
-            char *str = buf+5;
-            char const * const usermode = strsep(&str, " ");  (void)usermode;
-            char const * const usernice = strsep(&str, " ");  (void)usernice;
-            char const * const systemmode = strsep(&str, " ");(void)systemmode;
-            char const * const idle = strsep(&str, " ");
-            const nsecs_t nowIdleTime = atoi(idle) * 10000000LL;
-            mIdleTime = float(nowIdleTime - mRefIdleTime) * reftime;
-            mRefIdleTime = nowIdleTime;
-            
-            const nsecs_t workingTime = nowWorkingTime - mReferenceWorkingTime;
-            const float newCpuUsage = float(workingTime) * reftime;
-            if (mCpuUsage != newCpuUsage) {        
-                mCpuUsage = newCpuUsage;
-                mReferenceWorkingTime = nowWorkingTime;
-                mReferenceTime = now;
-            }
-        }
-        mLock.unlock();
-    }
-}
-
-
-}; // namespace android
diff --git a/libs/surfaceflinger/CPUGauge.h b/libs/surfaceflinger/CPUGauge.h
deleted file mode 100644
index 5bb53c0..0000000
--- a/libs/surfaceflinger/CPUGauge.h
+++ /dev/null
@@ -1,74 +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.
- */
-
-#ifndef ANDROID_CPUGAUGE_H
-#define ANDROID_CPUGAUGE_H
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Timers.h>
-
-#include <ui/SurfaceComposerClient.h>
-
-namespace android {
-
-class CPUGauge : public Thread
-{
-public:
-    CPUGauge(   const sp<ISurfaceComposer>& composer,
-                nsecs_t interval=s2ns(1),
-                int clock=SYSTEM_TIME_THREAD,
-                int refclock=SYSTEM_TIME_MONOTONIC);
-                
-    ~CPUGauge();
-
-    const sp<SurfaceComposerClient>& session() const;
-
-    void sample();
- 
-    inline float cpuUsage() const { return mCpuUsage; }
-    inline float idle() const { return mIdleTime; }
-
-private:
-    virtual void        onFirstRef();
-    virtual status_t    readyToRun();
-    virtual bool        threadLoop();
-
-    Mutex mLock;
-
-    sp<SurfaceComposerClient> mSession;
-
-    const nsecs_t mInterval;
-    const int mClock;
-    const int mRefClock;
-
-    nsecs_t mReferenceTime;
-    nsecs_t mReferenceWorkingTime;
-    float mCpuUsage;
-    nsecs_t mRefIdleTime;
-    float mIdleTime;
-    FILE*   mFd;
-};
-
-
-}; // namespace android
-
-#endif // ANDROID_CPUGAUGE_H
diff --git a/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp b/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp
index eec645e..21f87e37 100644
--- a/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp
+++ b/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
@@ -23,18 +21,23 @@
 
 #include <cutils/properties.h>
 
+#include <utils/RefBase.h>
 #include <utils/Log.h>
 
-#include <ui/EGLDisplaySurface.h>
+#include <ui/PixelFormat.h>
+#include <ui/FramebufferNativeWindow.h>
 
 #include <GLES/gl.h>
+#include <EGL/egl.h>
 #include <EGL/eglext.h>
 
+#include <pixelflinger/pixelflinger.h>
 
 #include "DisplayHardware/DisplayHardware.h"
 
 #include <hardware/copybit.h>
 #include <hardware/overlay.h>
+#include <hardware/gralloc.h>
 
 using namespace android;
 
@@ -108,17 +111,28 @@
 
 void DisplayHardware::init(uint32_t dpy)
 {
+    hw_module_t const* module;
+
+    mNativeWindow = new FramebufferNativeWindow();
+
+    mOverlayEngine = NULL;
+    if (hw_get_module(OVERLAY_HARDWARE_MODULE_ID, &module) == 0) {
+        overlay_control_open(module, &mOverlayEngine);
+    }
+
+    framebuffer_device_t const * fbDev = mNativeWindow->getDevice();
+
+    PixelFormatInfo fbFormatInfo;
+    getPixelFormatInfo(PixelFormat(fbDev->format), &fbFormatInfo);
+
     // initialize EGL
     const EGLint attribs[] = {
-            EGL_RED_SIZE,       5,
-            EGL_GREEN_SIZE,     6,
-            EGL_BLUE_SIZE,      5,
+            EGL_BUFFER_SIZE,    fbFormatInfo.bitsPerPixel,
             EGL_DEPTH_SIZE,     0,
             EGL_NONE
     };
     EGLint w, h, dummy;
-    EGLint numConfigs, n;
-    EGLConfig config;
+    EGLint numConfigs=0, n=0;
     EGLSurface surface;
     EGLContext context;
     mFlags = 0;
@@ -129,7 +143,32 @@
     EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
     eglInitialize(display, NULL, NULL);
     eglGetConfigs(display, NULL, 0, &numConfigs);
-    eglChooseConfig(display, attribs, &config, 1, &n);
+
+    // Get all the "potential match" configs...
+    EGLConfig* const configs = new EGLConfig[numConfigs];
+    eglChooseConfig(display, attribs, configs, numConfigs, &n);
+    LOGE_IF(n<=0, "no EGLConfig available!");
+    EGLConfig config = configs[0];
+    if (n > 1) {
+        // if there is more than one candidate, go through the list
+        // and pick one that matches our framebuffer format
+        int fbSzA = fbFormatInfo.getSize(PixelFormatInfo::INDEX_ALPHA);
+        int fbSzR = fbFormatInfo.getSize(PixelFormatInfo::INDEX_RED);
+        int fbSzG = fbFormatInfo.getSize(PixelFormatInfo::INDEX_GREEN);
+        int fbSzB = fbFormatInfo.getSize(PixelFormatInfo::INDEX_BLUE); 
+        for (int i=0 ; i<n ; i++) {
+            EGLint r,g,b,a;
+            eglGetConfigAttrib(display, configs[i], EGL_RED_SIZE,   &r);
+            eglGetConfigAttrib(display, configs[i], EGL_GREEN_SIZE, &g);
+            eglGetConfigAttrib(display, configs[i], EGL_BLUE_SIZE,  &b);
+            eglGetConfigAttrib(display, configs[i], EGL_ALPHA_SIZE, &a);
+            if (fbSzA == a && fbSzR == r && fbSzG == g && fbSzB  == b) {
+                config = configs[i];
+                break;
+            }
+        }
+    }
+    delete [] configs;
 
     /*
      * Gather EGL extensions
@@ -145,12 +184,11 @@
     LOGI("extensions: %s", egl_extensions);
     LOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
 
-    // TODO: get this from the devfb driver (probably should be HAL module)
-    mFlags |= SWAP_RECTANGLE_EXTENSION;
-    
-    // TODO: get the real "update_on_demand" behavior (probably should be HAL module)
-    mFlags |= UPDATE_ON_DEMAND;
 
+    if (mNativeWindow->isUpdateOnDemand()) {
+        mFlags |= UPDATE_ON_DEMAND;
+    }
+    
     if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy) == EGL_TRUE) {
         if (dummy == EGL_SLOW_CONFIG)
             mFlags |= SLOW_CONFIG;
@@ -160,33 +198,29 @@
      * Create our main surface
      */
 
-    mDisplaySurface = new EGLDisplaySurface();
-
-    surface = eglCreateWindowSurface(display, config, mDisplaySurface.get(), NULL);
-    //checkEGLErrors("eglCreateDisplaySurfaceANDROID");
+    surface = eglCreateWindowSurface(display, config, mNativeWindow.get(), NULL);
+    checkEGLErrors("eglCreateWindowSurface");
 
     if (eglQuerySurface(display, surface, EGL_SWAP_BEHAVIOR, &dummy) == EGL_TRUE) {
         if (dummy == EGL_BUFFER_PRESERVED) {
             mFlags |= BUFFER_PRESERVED;
         }
     }
-    
-    GLint value = EGL_UNKNOWN;
-    eglQuerySurface(display, surface, EGL_HORIZONTAL_RESOLUTION, &value);
-    if (value == EGL_UNKNOWN) {
-        mDpiX = 160.0f;
-    } else {
-        mDpiX = 25.4f * float(value)/EGL_DISPLAY_SCALING;
+
+#ifdef EGL_ANDROID_swap_rectangle    
+    if (strstr(egl_extensions, "EGL_ANDROID_swap_rectangle")) {
+        mFlags |= SWAP_RECTANGLE;
     }
-    value = EGL_UNKNOWN;
-    eglQuerySurface(display, surface, EGL_VERTICAL_RESOLUTION, &value);
-    if (value == EGL_UNKNOWN) {
-        mDpiY = 160.0f;
-    } else {
-        mDpiY = 25.4f * float(value)/EGL_DISPLAY_SCALING;
-    }
-    mRefreshRate = 60.f;    // TODO: get the real refresh rate 
+    // when we have the choice between UPDATE_ON_DEMAND and SWAP_RECTANGLE
+    // choose UPDATE_ON_DEMAND, which is more efficient
+    if (mFlags & UPDATE_ON_DEMAND)
+        mFlags &= ~SWAP_RECTANGLE;
+#endif
     
+
+    mDpiX = mNativeWindow->xdpi;
+    mDpiY = mNativeWindow->ydpi;
+    mRefreshRate = fbDev->fps; 
     
     char property[PROPERTY_VALUE_MAX];
     /* Read density from build-specific ro.sf.lcd_density property
@@ -230,7 +264,10 @@
     if (strstr(gl_extensions, "GL_OES_draw_texture")) {
         mFlags |= DRAW_TEXTURE_EXTENSION;
     }
-    if (strstr(gl_extensions, "GL_ANDROID_direct_texture")) {
+    if (strstr( gl_extensions, "GL_OES_EGL_image") &&
+        (strstr(egl_extensions, "EGL_KHR_image_base") || 
+                strstr(egl_extensions, "EGL_KHR_image")) &&
+        strstr(egl_extensions, "EGL_ANDROID_image_native_buffer")) {
         mFlags |= DIRECT_TEXTURE;
     }
 
@@ -241,19 +278,8 @@
     mConfig  = config;
     mSurface = surface;
     mContext = context;
-    mFormat  = GGL_PIXEL_FORMAT_RGB_565;
-    
-    hw_module_t const* module;
-
-    mBlitEngine = NULL;
-    if (hw_get_module(COPYBIT_HARDWARE_MODULE_ID, &module) == 0) {
-        copybit_open(module, &mBlitEngine);
-    }
-
-    mOverlayEngine = NULL;
-    if (hw_get_module(OVERLAY_HARDWARE_MODULE_ID, &module) == 0) {
-        overlay_control_open(module, &mOverlayEngine);
-    }
+    mFormat  = fbDev->format;
+    mPageFlipCount = 0;
 }
 
 /*
@@ -267,7 +293,6 @@
 {
     eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
     eglTerminate(mDisplay);
-    copybit_close(mBlitEngine);
     overlay_control_close(mOverlayEngine);
 }
 
@@ -281,28 +306,8 @@
     DisplayHardwareBase::acquireScreen();
 }
 
-void DisplayHardware::getDisplaySurface(copybit_image_t* img) const
-{
-    img->w      = mDisplaySurface->stride;
-    img->h      = mDisplaySurface->height;
-    img->format = mDisplaySurface->format;
-    img->offset = mDisplaySurface->offset;
-    img->base   = (void*)mDisplaySurface->base;
-    img->fd     = mDisplaySurface->fd;
-}
-
-void DisplayHardware::getDisplaySurface(GGLSurface* fb) const
-{
-    fb->version= sizeof(GGLSurface);
-    fb->width  = mDisplaySurface->width;
-    fb->height = mDisplaySurface->height;
-    fb->stride = mDisplaySurface->stride;
-    fb->format = mDisplaySurface->format;
-    fb->data   = (GGLubyte*)mDisplaySurface->base + mDisplaySurface->offset;
-}
-
 uint32_t DisplayHardware::getPageFlipCount() const {
-    return mDisplaySurface->getPageFlipCount();
+    return mPageFlipCount;
 }
 
 /*
@@ -316,21 +321,20 @@
     EGLDisplay dpy = mDisplay;
     EGLSurface surface = mSurface;
 
-    Region newDirty(dirty);
-    newDirty.andSelf(Rect(mWidth, mHeight));
-
-    if (mFlags & BUFFER_PRESERVED) {
-        const Region copyback(mDirty.subtract(newDirty));
-        mDirty = newDirty;
-        mDisplaySurface->copyFrontToBack(copyback);
-    } 
-
-    if (mFlags & SWAP_RECTANGLE_EXTENSION) {
-        const Rect& b(newDirty.bounds());
-        mDisplaySurface->setSwapRectangle(
+#ifdef EGL_ANDROID_swap_rectangle    
+    if (mFlags & SWAP_RECTANGLE) {
+        const Region newDirty(dirty.intersect(bounds()));
+        const Rect b(newDirty.getBounds());
+        eglSetSwapRectangleANDROID(dpy, surface,
                 b.left, b.top, b.width(), b.height());
+    } 
+#endif
+    
+    if (mFlags & UPDATE_ON_DEMAND) {
+        mNativeWindow->setUpdateRectangle(dirty.getBounds());
     }
-
+    
+    mPageFlipCount++;
     eglSwapBuffers(dpy, surface);
     checkEGLErrors("eglSwapBuffers");
 
@@ -348,11 +352,3 @@
 {
     eglMakeCurrent(mDisplay, mSurface, mSurface, mContext);
 }
-
-void DisplayHardware::copyFrontToImage(const copybit_image_t& front) const {
-    mDisplaySurface->copyFrontToImage(front);
-}
-
-void DisplayHardware::copyBackToImage(const copybit_image_t& front) const {
-    mDisplaySurface->copyBackToImage(front);
-}
diff --git a/libs/surfaceflinger/DisplayHardware/DisplayHardware.h b/libs/surfaceflinger/DisplayHardware/DisplayHardware.h
index 550a4d1..8972d51 100644
--- a/libs/surfaceflinger/DisplayHardware/DisplayHardware.h
+++ b/libs/surfaceflinger/DisplayHardware/DisplayHardware.h
@@ -22,31 +22,35 @@
 #include <ui/PixelFormat.h>
 #include <ui/Region.h>
 
+#include <GLES/gl.h>
+#include <GLES/glext.h>
 #include <EGL/egl.h>
+#include <EGL/eglext.h>
+
+#include <pixelflinger/pixelflinger.h>
 
 #include "DisplayHardware/DisplayHardwareBase.h"
 
 struct overlay_control_device_t;
-struct copybit_device_t;
+struct framebuffer_device_t;
 struct copybit_image_t;
-struct copybit_t;
 
 namespace android {
 
-class EGLDisplaySurface;
+class FramebufferNativeWindow;
 
 class DisplayHardware : public DisplayHardwareBase
 {
 public:
     enum {
         DIRECT_TEXTURE          = 0x00000002,
-        SWAP_RECTANGLE_EXTENSION= 0x00000004,
         COPY_BITS_EXTENSION     = 0x00000008,
         NPOT_EXTENSION          = 0x00000100,
         DRAW_TEXTURE_EXTENSION  = 0x00000200,
         BUFFER_PRESERVED        = 0x00010000,
         UPDATE_ON_DEMAND        = 0x00020000,   // video driver feature
         SLOW_CONFIG             = 0x00040000,   // software
+        SWAP_RECTANGLE          = 0x00080000,
     };
 
     DisplayHardware(
@@ -73,15 +77,9 @@
     void        makeCurrent() const;
 
     uint32_t getPageFlipCount() const;
-    void getDisplaySurface(copybit_image_t* img) const;
-    void getDisplaySurface(GGLSurface* fb) const;
     EGLDisplay getEGLDisplay() const { return mDisplay; }
-    copybit_device_t* getBlitEngine() const { return mBlitEngine; }
     overlay_control_device_t* getOverlayEngine() const { return mOverlayEngine; }
     
-    void copyFrontToImage(const copybit_image_t& front) const;
-    void copyBackToImage(const copybit_image_t& front) const;
-       
     Rect bounds() const {
         return Rect(mWidth, mHeight);
     }
@@ -102,9 +100,9 @@
     int             mHeight;
     PixelFormat     mFormat;
     uint32_t        mFlags;
-    mutable Region  mDirty;
-    sp<EGLDisplaySurface> mDisplaySurface;
-    copybit_device_t*     mBlitEngine;
+    mutable uint32_t mPageFlipCount;
+    
+    sp<FramebufferNativeWindow> mNativeWindow;
     overlay_control_device_t* mOverlayEngine;
 };
 
diff --git a/libs/surfaceflinger/DisplayHardware/DisplayHardwareBase.cpp b/libs/surfaceflinger/DisplayHardware/DisplayHardwareBase.cpp
index f75e5c2..1d09f84 100644
--- a/libs/surfaceflinger/DisplayHardware/DisplayHardwareBase.cpp
+++ b/libs/surfaceflinger/DisplayHardware/DisplayHardwareBase.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <assert.h>
 #include <errno.h>
 #include <stdlib.h>
diff --git a/libs/surfaceflinger/Layer.cpp b/libs/surfaceflinger/Layer.cpp
index 96395a8..9916158 100644
--- a/libs/surfaceflinger/Layer.cpp
+++ b/libs/surfaceflinger/Layer.cpp
@@ -14,26 +14,24 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <stdlib.h>
 #include <stdint.h>
 #include <sys/types.h>
 
 #include <cutils/properties.h>
+#include <cutils/native_handle.h>
 
 #include <utils/Errors.h>
 #include <utils/Log.h>
 #include <utils/StopWatch.h>
 
 #include <ui/PixelFormat.h>
-#include <ui/EGLDisplaySurface.h>
+#include <ui/Surface.h>
 
 #include "clz.h"
 #include "Layer.h"
 #include "LayerBitmap.h"
 #include "SurfaceFlinger.h"
-#include "VRamHeap.h"
 #include "DisplayHardware/DisplayHardware.h"
 
 
@@ -49,13 +47,12 @@
 
 // ---------------------------------------------------------------------------
 
-Layer::Layer(SurfaceFlinger* flinger, DisplayID display, Client* c, int32_t i)
+Layer::Layer(SurfaceFlinger* flinger, DisplayID display, const sp<Client>& c, int32_t i)
     :   LayerBaseClient(flinger, display, c, i),
         mSecure(false),
         mFrontBufferIndex(1),
         mNeedsBlending(true),
-        mResizeTransactionDone(false),
-        mTextureName(-1U), mTextureWidth(0), mTextureHeight(0)
+        mResizeTransactionDone(false)
 {
     // no OpenGL operation is possible here, since we might not be
     // in the OpenGL thread.
@@ -63,12 +60,25 @@
 
 Layer::~Layer()
 {
-    client->free(clientIndex());
-    // this should always be called from the OpenGL thread
-    if (mTextureName != -1U) {
-        //glDeleteTextures(1, &mTextureName);
-        deletedTextures.add(mTextureName);
+    destroy();
+    // the actual buffers will be destroyed here
+}
+
+void Layer::destroy()
+{
+    for (int i=0 ; i<NUM_BUFFERS ; i++) {
+        if (mTextures[i].name != -1U) {
+            glDeleteTextures(1, &mTextures[i].name);
+            mTextures[i].name = -1U;
+        }
+        if (mTextures[i].image != EGL_NO_IMAGE_KHR) {
+            EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
+            eglDestroyImageKHR(dpy, mTextures[i].image);
+            mTextures[i].image = EGL_NO_IMAGE_KHR;
+        }
+        mBuffers[i].free();
     }
+    mSurface.clear();
 }
 
 void Layer::initStates(uint32_t w, uint32_t h, uint32_t flags)
@@ -79,148 +89,206 @@
         lcblk->flags |= eNoCopyBack;
 }
 
-sp<LayerBaseClient::Surface> Layer::getSurface() const
+sp<LayerBaseClient::Surface> Layer::createSurface() const
 {
     return mSurface;
 }
 
-status_t Layer::setBuffers( Client* client,
-                            uint32_t w, uint32_t h,
+status_t Layer::ditch()
+{
+    // the layer is not on screen anymore. free as much resources as possible
+    destroy();
+    return NO_ERROR;
+}
+
+status_t Layer::setBuffers( uint32_t w, uint32_t h,
                             PixelFormat format, uint32_t flags)
 {
     PixelFormatInfo info;
     status_t err = getPixelFormatInfo(format, &info);
     if (err) return err;
 
-    // TODO: if eHardware is explicitly requested, we should fail
-    // on systems where we can't allocate memory that can be used with
-    // DMA engines for instance.
-    
-    // FIXME: we always ask for hardware for now (this should come from copybit)
-    flags |= ISurfaceComposer::eHardware;
+    uint32_t bufferFlags = 0;
+    if (flags & ISurfaceComposer::eGPU)
+        bufferFlags |= Buffer::GPU;
 
-    const uint32_t memory_flags = flags & 
-            (ISurfaceComposer::eGPU | 
-             ISurfaceComposer::eHardware | 
-             ISurfaceComposer::eSecure);
-    
-    // pixel-alignment. the final alignment may be bigger because
-    // we always force a 4-byte aligned bpr.
-    uint32_t alignment = 1;
+    if (flags & ISurfaceComposer::eSecure)
+        bufferFlags |= Buffer::SECURE;
 
-    if ((flags & ISurfaceComposer::eGPU) && (mFlinger->getGPU() != 0)) {
-        // FIXME: this value should come from the h/w
-        alignment = 8; 
+    /* FIXME we need this code for msm7201A
+    if (bufferFlags & Buffer::GPU) {
         // FIXME: this is msm7201A specific, as its GPU only supports
         // BGRA_8888.
         if (format == PIXEL_FORMAT_RGBA_8888) {
             format = PIXEL_FORMAT_BGRA_8888;
         }
     }
+    */
 
-    mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
+    mSecure = (bufferFlags & Buffer::SECURE) ? true : false;
     mNeedsBlending = (info.h_alpha - info.l_alpha) > 0;
-    sp<MemoryDealer> allocators[2];
     for (int i=0 ; i<2 ; i++) {
-        allocators[i] = client->createAllocator(memory_flags);
-        if (allocators[i] == 0)
-            return NO_MEMORY;
-        mBuffers[i].init(allocators[i]);
-        int err = mBuffers[i].setBits(w, h, alignment, format, LayerBitmap::SECURE_BITS);
-        if (err != NO_ERROR)
+        err = mBuffers[i].init(lcblk->surface + i, w, h, format, bufferFlags);
+        if (err != NO_ERROR) {
             return err;
-        mBuffers[i].clear(); // clear the bits for security
-        mBuffers[i].getInfo(lcblk->surface + i);
+        }
     }
-
-    mSurface = new Surface(clientIndex(),
-            allocators[0]->getMemoryHeap(),
-            allocators[1]->getMemoryHeap(),
-            mIdentity);
-
+    mSurface = new SurfaceLayer(mFlinger, clientIndex(), this);
     return NO_ERROR;
 }
 
 void Layer::reloadTexture(const Region& dirty)
 {
-    if (UNLIKELY(mTextureName == -1U)) {
-        // create the texture name the first time
-        // can't do that in the ctor, because it runs in another thread.
-        mTextureName = createTexture();
+    const sp<Buffer>& buffer(frontBuffer().getBuffer());
+    if (LIKELY(mFlags & DisplayHardware::DIRECT_TEXTURE)) {
+        int index = mFrontBufferIndex;
+        if (LIKELY(!mTextures[index].dirty)) {
+            glBindTexture(GL_TEXTURE_2D, mTextures[index].name);
+        } else {
+            // we need to recreate the texture
+            EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
+            
+            // create the new texture name if needed
+            if (UNLIKELY(mTextures[index].name == -1U)) {
+                mTextures[index].name = createTexture();
+            } else {
+                glBindTexture(GL_TEXTURE_2D, mTextures[index].name);
+            }
+
+            // free the previous image
+            if (mTextures[index].image != EGL_NO_IMAGE_KHR) {
+                eglDestroyImageKHR(dpy, mTextures[index].image);
+                mTextures[index].image = EGL_NO_IMAGE_KHR;
+            }
+            
+            // construct an EGL_NATIVE_BUFFER_ANDROID
+            android_native_buffer_t* clientBuf = buffer->getNativeBuffer();
+            
+            // create the new EGLImageKHR
+            const EGLint attrs[] = { 
+                    EGL_IMAGE_PRESERVED_KHR,    EGL_TRUE, 
+                    EGL_NONE,                   EGL_NONE 
+            };
+            mTextures[index].image = eglCreateImageKHR(
+                    dpy, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
+                    (EGLClientBuffer)clientBuf, attrs);
+
+            LOGE_IF(mTextures[index].image == EGL_NO_IMAGE_KHR,
+                    "eglCreateImageKHR() failed. err=0x%4x",
+                    eglGetError());
+            
+            if (mTextures[index].image != EGL_NO_IMAGE_KHR) {
+                glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, 
+                        (GLeglImageOES)mTextures[index].image);
+                GLint error = glGetError();
+                if (UNLIKELY(error != GL_NO_ERROR)) {
+                    // this failed, for instance, because we don't support
+                    // NPOT.
+                    // FIXME: do something!
+                    mFlags &= ~DisplayHardware::DIRECT_TEXTURE;
+                } else {
+                    // Everything went okay!
+                    mTextures[index].dirty  = false;
+                    mTextures[index].width  = clientBuf->width;
+                    mTextures[index].height = clientBuf->height;
+                }
+            }                
+        }
+    } else {
+        GGLSurface t;
+        status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_RARELY);
+        LOGE_IF(res, "error %d (%s) locking buffer %p",
+                res, strerror(res), buffer.get());
+        if (res == NO_ERROR) {
+            if (UNLIKELY(mTextures[0].name == -1U)) {
+                mTextures[0].name = createTexture();
+            }
+            loadTexture(&mTextures[0], mTextures[0].name, dirty, t);
+            buffer->unlock();
+        }
     }
-    const GGLSurface& t(frontBuffer().surface());
-    loadTexture(dirty, mTextureName, t, mTextureWidth, mTextureHeight);
 }
 
 
 void Layer::onDraw(const Region& clip) const
 {
-    if (UNLIKELY(mTextureName == -1LU)) {
-        //LOGW("Layer %p doesn't have a texture", this);
+    const int index = (mFlags & DisplayHardware::DIRECT_TEXTURE) ? 
+            mFrontBufferIndex : 0;
+    GLuint textureName = mTextures[index].name;
+
+    if (UNLIKELY(textureName == -1LU)) {
+        LOGW("Layer %p doesn't have a texture", this);
         // the texture has not been created yet, this Layer has
         // in fact never been drawn into. this happens frequently with
         // SurfaceView.
         clearWithOpenGL(clip);
         return;
     }
-
-    const DisplayHardware& hw(graphicPlane(0).displayHardware());
-    const LayerBitmap& front(frontBuffer());
-    const GGLSurface& t(front.surface());
-
-    status_t err = NO_ERROR;
-    const int can_use_copybit = canUseCopybit();
-    if (can_use_copybit)  {
-        // StopWatch watch("copybit");
-        const State& s(drawingState());
-
-        copybit_image_t dst;
-        hw.getDisplaySurface(&dst);
-        const copybit_rect_t& drect
-            = reinterpret_cast<const copybit_rect_t&>(mTransformedBounds);
-
-        copybit_image_t src;
-        front.getBitmapSurface(&src);
-        copybit_rect_t srect = { 0, 0, t.width, t.height };
-
-        copybit_device_t* copybit = mFlinger->getBlitEngine();
-        copybit->set_parameter(copybit, COPYBIT_TRANSFORM, getOrientation());
-        copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, s.alpha);
-        copybit->set_parameter(copybit, COPYBIT_DITHER,
-                s.flags & ISurfaceComposer::eLayerDither ?
-                        COPYBIT_ENABLE : COPYBIT_DISABLE);
-
-        region_iterator it(clip);
-        err = copybit->stretch(copybit, &dst, &src, &drect, &srect, &it);
-    }
-
-    if (!can_use_copybit || err) {
-        drawWithOpenGL(clip, mTextureName, t);
-    }
+    drawWithOpenGL(clip, mTextures[index]);
 }
 
-status_t Layer::reallocateBuffer(int32_t index, uint32_t w, uint32_t h)
+sp<SurfaceBuffer> Layer::peekBuffer()
 {
-    LOGD_IF(DEBUG_RESIZE,
-                "reallocateBuffer (layer=%p), "
-                "requested (%dx%d), "
-                "index=%d, (%dx%d), (%dx%d)",
-                this,
-                int(w), int(h),
-                int(index),
-                int(mBuffers[0].width()), int(mBuffers[0].height()),
-                int(mBuffers[1].width()), int(mBuffers[1].height()));
+    /*
+     * This is called from the client's Surface::lock(), after it locked
+     * the surface successfully. We're therefore guaranteed that the
+     * back-buffer is not in use by ourselves.
+     * Of course, we need to validate all this, which is not trivial.
+     *
+     * FIXME: A resize could happen at any time here. What to do about this?
+     *  - resize() form post()
+     *  - resize() from doTransaction()
+     *  
+     *  We'll probably need an internal lock for this.
+     *     
+     * 
+     * TODO: We need to make sure that post() doesn't swap
+     *       the buffers under us.
+     */
 
-    status_t err = mBuffers[index].resize(w, h);
-    if (err == NO_ERROR) {
-        mBuffers[index].getInfo(lcblk->surface + index);
-    } else {
-        LOGE("resizing buffer %d to (%u,%u) failed [%08x] %s",
-            index, w, h, err, strerror(err));
-        // XXX: what to do, what to do? We could try to free some
-        // hidden surfaces, instead of killing this one?
+    // it's okay to read swapState for the purpose of figuring out the 
+    // backbuffer index, which cannot change (since the app has locked it).
+    const uint32_t state = lcblk->swapState;
+    const int32_t backBufferIndex = layer_cblk_t::backBuffer(state);
+    
+    // get rid of the EGL image, since we shouldn't need it anymore
+    // (note that we're in a different thread than where it is being used)
+    if (mTextures[backBufferIndex].image != EGL_NO_IMAGE_KHR) {
+        EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
+        eglDestroyImageKHR(dpy, mTextures[backBufferIndex].image);
+        mTextures[backBufferIndex].image = EGL_NO_IMAGE_KHR;
     }
-    return err;
+    
+    LayerBitmap& layerBitmap(mBuffers[backBufferIndex]);
+    sp<SurfaceBuffer> buffer = layerBitmap.allocate();
+    
+    LOGD_IF(DEBUG_RESIZE,
+            "Layer::getBuffer(this=%p), index=%d, (%d,%d), (%d,%d)",
+            this, backBufferIndex,
+            layerBitmap.getWidth(),
+            layerBitmap.getHeight(),
+            layerBitmap.getBuffer()->getWidth(),
+            layerBitmap.getBuffer()->getHeight());
+
+    if (UNLIKELY(buffer == 0)) {
+        // XXX: what to do, what to do?
+    } else {
+        // texture is now dirty...
+        mTextures[backBufferIndex].dirty = true;
+        // ... so it the visible region (because we consider the surface's
+        // buffer size for visibility calculations)
+        forceVisibilityTransaction();
+        mFlinger->setTransactionFlags(eTraversalNeeded);
+    }
+    return buffer;
+}
+
+void Layer::scheduleBroadcast()
+{
+    sp<Client> ourClient(client.promote());
+    if (ourClient != 0) {
+        mFlinger->scheduleBroadcast(ourClient);
+    }
 }
 
 uint32_t Layer::doTransaction(uint32_t flags)
@@ -232,7 +300,7 @@
     // that the size changed back to its previous value before the buffer
     // was resized (in the eLocked case below), in which case, we still
     // need to execute the code below so the clients have a chance to be
-    // release. resze() deals with the fact that the size can be the same.
+    // release. resize() deals with the fact that the size can be the same.
 
     /*
      *  Various states we could be in...
@@ -276,8 +344,8 @@
                 int(temp.w), int(temp.h),
                 int(drawingState().w), int(drawingState().h),
                 int(clientBackBufferIndex),
-                int(mBuffers[0].width()), int(mBuffers[0].height()),
-                int(mBuffers[1].width()), int(mBuffers[1].height()));
+                int(mBuffers[0].getWidth()), int(mBuffers[0].getHeight()),
+                int(mBuffers[1].getWidth()), int(mBuffers[1].getHeight()));
         // if we get there we're pretty screwed. the only reasonable
         // thing to do is to pretend we should do the resize since
         // backbufferChanged is set (this also will give a chance to
@@ -299,8 +367,8 @@
                     int(temp.w), int(temp.h),
                     int(drawingState().w), int(drawingState().h),
                     int(clientBackBufferIndex),
-                    int(mBuffers[0].width()), int(mBuffers[0].height()),
-                    int(mBuffers[1].width()), int(mBuffers[1].height()));
+                    int(mBuffers[0].getWidth()), int(mBuffers[0].getHeight()),
+                    int(mBuffers[1].getWidth()), int(mBuffers[1].getHeight()));
 
         if (state & eLocked) {
             // if the buffer is locked, we can't resize anything because
@@ -314,10 +382,11 @@
             status_t err =
                 resize(clientBackBufferIndex, temp.w, temp.h, "transaction");
             if (err == NO_ERROR) {
-                const uint32_t mask = clientBackBufferIndex ? eResizeBuffer1 : eResizeBuffer0;
+                const uint32_t mask = clientBackBufferIndex ?
+                        eResizeBuffer1 : eResizeBuffer0;
                 android_atomic_and(~mask, &(lcblk->swapState));
                 // since a buffer became available, we can let the client go...
-                mFlinger->scheduleBroadcast(client);
+                scheduleBroadcast();
                 mResizeTransactionDone = true;
 
                 // we're being resized and there is a freeze display request,
@@ -353,14 +422,15 @@
 {
     /*
      * handle resize (backbuffer and frontbuffer reallocation)
+     * this is called from post() or from doTransaction()
      */
 
     const LayerBitmap& clientBackBuffer(mBuffers[clientBackBufferIndex]);
 
     // if the new (transaction) size is != from the the backbuffer
     // then we need to reallocate the backbuffer
-    bool backbufferChanged = (clientBackBuffer.width()  != width) ||
-                             (clientBackBuffer.height() != height);
+    bool backbufferChanged = (clientBackBuffer.getWidth()  != width) ||
+                             (clientBackBuffer.getHeight() != height);
 
     LOGD_IF(!backbufferChanged,
             "(%s) eResizeRequested (layer=%p), but size not changed: "
@@ -372,18 +442,28 @@
             int(currentState().w), int(currentState().h),
             long(lcblk->swapState),
             int(clientBackBufferIndex),
-            int(mBuffers[0].width()), int(mBuffers[0].height()),
-            int(mBuffers[1].width()), int(mBuffers[1].height()));
+            int(mBuffers[0].getWidth()), int(mBuffers[0].getHeight()),
+            int(mBuffers[1].getWidth()), int(mBuffers[1].getHeight()));
 
     // this can happen when changing the size back and forth quickly
     status_t err = NO_ERROR;
     if (backbufferChanged) {
-        err = reallocateBuffer(clientBackBufferIndex, width, height);
-    }
-    if (UNLIKELY(err != NO_ERROR)) {
-        // couldn't reallocate the surface
-        android_atomic_write(eInvalidSurface, &lcblk->swapState);
-        memset(lcblk->surface+clientBackBufferIndex, 0, sizeof(surface_info_t));
+
+        LOGD_IF(DEBUG_RESIZE,
+                "resize (layer=%p), requested (%dx%d), "
+                "index=%d, (%dx%d), (%dx%d)",
+                this, int(width), int(height), int(clientBackBufferIndex),
+                int(mBuffers[0].getWidth()), int(mBuffers[0].getHeight()),
+                int(mBuffers[1].getWidth()), int(mBuffers[1].getHeight()));
+
+        err = mBuffers[clientBackBufferIndex].setSize(width, height);
+        if (UNLIKELY(err != NO_ERROR)) {
+            // This really should never happen
+            LOGE("resizing buffer %d to (%u,%u) failed [%08x] %s",
+                    clientBackBufferIndex, width, height, err, strerror(err));
+            // couldn't reallocate the surface
+            android_atomic_write(eInvalidSurface, &lcblk->swapState);
+        }
     }
     return err;
 }
@@ -415,7 +495,7 @@
     if (UNLIKELY(state & eInvalidSurface)) {
         // if eInvalidSurface is set, this means the surface
         // became invalid during a transaction (NO_MEMORY for instance)
-        mFlinger->scheduleBroadcast(client);
+        scheduleBroadcast();
         return;
     }
 
@@ -457,15 +537,21 @@
 
     } while(android_atomic_cmpxchg(oldValue, newValue, &(lcblk->swapState)));
     *previousSate = oldValue;
-
+    
     const int32_t index = (newValue & eIndex) ^ 1;
     mFrontBufferIndex = index;
 
+    /* NOTE: it's safe to set this flag here because this is only touched
+     * from LayerBitmap::allocate(), which by construction cannot happen
+     * while we're in post().
+     */
+    lcblk->surface[index].flags &= ~surface_info_t::eBufferDirty;
+
     // ... post the new front-buffer
     Region dirty(lcblk->region + index);
-    dirty.andSelf(frontBuffer().bounds());
+    dirty.andSelf(frontBuffer().getBounds());
 
-    //LOGI("Did post oldValue=%08lx, newValue=%08lx, mFrontBufferIndex=%u\n",
+    //LOGD("Did post oldValue=%08lx, newValue=%08lx, mFrontBufferIndex=%u\n",
     //    oldValue, newValue, mFrontBufferIndex);
     //dirty.dump("dirty");
 
@@ -476,8 +562,8 @@
                      "index=%d, (%dx%d), (%dx%d)",
                      this,  newValue,
                      int(1-index),
-                     int(mBuffers[0].width()), int(mBuffers[0].height()),
-                     int(mBuffers[1].width()), int(mBuffers[1].height()));
+                     int(mBuffers[0].getWidth()), int(mBuffers[0].getHeight()),
+                     int(mBuffers[1].getWidth()), int(mBuffers[1].getHeight()));
 
         // here, we just posted the surface and we have resolved
         // the front/back buffer indices. The client is blocked, so
@@ -522,8 +608,8 @@
 
 Point Layer::getPhysicalSize() const
 {
-    const LayerBitmap& front(frontBuffer());
-    return Point(front.width(), front.height());
+    sp<const Buffer> front(frontBuffer().getBuffer());
+    return Point(front->getWidth(), front->getHeight());
 }
 
 void Layer::unlockPageFlip(
@@ -547,7 +633,7 @@
 
         // client could be blocked, so signal them so they get a
         // chance to reevaluate their condition.
-        mFlinger->scheduleBroadcast(client);
+        scheduleBroadcast();
     }
 }
 
@@ -558,9 +644,30 @@
                 "layer %p wasn't locked!", this);
         android_atomic_and(~eBusy, &(lcblk->swapState));
     }
-    mFlinger->scheduleBroadcast(client);
+    scheduleBroadcast();
 }
 
+// ---------------------------------------------------------------------------
+
+Layer::SurfaceLayer::SurfaceLayer(const sp<SurfaceFlinger>& flinger,
+        SurfaceID id, const sp<Layer>& owner)
+    : Surface(flinger, id, owner->getIdentity(), owner)
+{
+}
+
+Layer::SurfaceLayer::~SurfaceLayer()
+{
+}
+
+sp<SurfaceBuffer> Layer::SurfaceLayer::getBuffer()
+{
+    sp<SurfaceBuffer> buffer = 0;
+    sp<Layer> owner(getOwner());
+    if (owner != 0) {
+        buffer = owner->peekBuffer();
+    }
+    return buffer;
+}
 
 // ---------------------------------------------------------------------------
 
diff --git a/libs/surfaceflinger/Layer.h b/libs/surfaceflinger/Layer.h
index 2867f2b..4c13d6e 100644
--- a/libs/surfaceflinger/Layer.h
+++ b/libs/surfaceflinger/Layer.h
@@ -27,6 +27,11 @@
 
 #include <pixelflinger/pixelflinger.h>
 
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
 #include "LayerBitmap.h"
 #include "LayerBase.h"
 #include "Transform.h"
@@ -37,11 +42,12 @@
 
 class Client;
 class LayerBitmap;
-class MemoryDealer;
 class FreezeLock;
 
 // ---------------------------------------------------------------------------
 
+const int NUM_BUFFERS = 2;
+
 class Layer : public LayerBaseClient
 {
 public:    
@@ -51,16 +57,15 @@
     virtual uint32_t getTypeInfo() const { return typeInfo; }
 
                  Layer(SurfaceFlinger* flinger, DisplayID display,
-                         Client* c, int32_t i);
+                         const sp<Client>& client, int32_t i);
 
         virtual ~Layer();
 
     inline PixelFormat pixelFormat() const {
-        return frontBuffer().pixelFormat();
+        return frontBuffer().getPixelFormat();
     }
 
-    status_t setBuffers(    Client* client,
-                            uint32_t w, uint32_t h,
+    status_t setBuffers(    uint32_t w, uint32_t h,
                             PixelFormat format, uint32_t flags=0);
 
     virtual void onDraw(const Region& clip) const;
@@ -73,8 +78,8 @@
     virtual void finishPageFlip();
     virtual bool needsBlending() const      { return mNeedsBlending; }
     virtual bool isSecure() const           { return mSecure; }
-    virtual GLuint getTextureName() const   { return mTextureName; }
-    virtual sp<Surface> getSurface() const;
+    virtual sp<Surface> createSurface() const;
+    virtual status_t ditch();
 
     const LayerBitmap& getBuffer(int i) const { return mBuffers[i]; }
           LayerBitmap& getBuffer(int i)       { return mBuffers[i]; }
@@ -96,21 +101,37 @@
 
     status_t resize(int32_t index, uint32_t w, uint32_t h, const char* what);
     Region post(uint32_t* oldState, bool& recomputeVisibleRegions);
-    status_t reallocateBuffer(int32_t index, uint32_t w, uint32_t h);
+    sp<SurfaceBuffer> peekBuffer();
+    void destroy();
+    void scheduleBroadcast();
 
+    
+    class SurfaceLayer : public LayerBaseClient::Surface
+    {
+    public:
+                SurfaceLayer(const sp<SurfaceFlinger>& flinger,
+                        SurfaceID id, const sp<Layer>& owner);
+                ~SurfaceLayer();
+
+    private:
+        virtual sp<SurfaceBuffer> getBuffer();
+
+        sp<Layer> getOwner() const {
+            return static_cast<Layer*>(Surface::getOwner().get());
+        }
+    };
+    friend class SurfaceLayer;
+    
     sp<Surface>             mSurface;
 
             bool            mSecure;
-            LayerBitmap     mBuffers[2];
+            LayerBitmap     mBuffers[NUM_BUFFERS];
+            Texture         mTextures[NUM_BUFFERS];
             int32_t         mFrontBufferIndex;
             bool            mNeedsBlending;
             bool            mResizeTransactionDone;
             Region          mPostedDirtyRegion;
             sp<FreezeLock>  mFreezeLock;
-            
-            GLuint          mTextureName;
-            GLuint          mTextureWidth;
-            GLuint          mTextureHeight;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/libs/surfaceflinger/LayerBase.cpp b/libs/surfaceflinger/LayerBase.cpp
index 0cf53f7..a841ab3 100644
--- a/libs/surfaceflinger/LayerBase.cpp
+++ b/libs/surfaceflinger/LayerBase.cpp
@@ -14,14 +14,14 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <stdlib.h>
 #include <stdint.h>
 #include <sys/types.h>
 
 #include <utils/Errors.h>
 #include <utils/Log.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
 
 #include <GLES/gl.h>
 #include <GLES/glext.h>
@@ -53,19 +53,13 @@
 
 // ---------------------------------------------------------------------------
 
-Vector<GLuint> LayerBase::deletedTextures; 
-
-int32_t LayerBase::sIdentity = 0;
-
 LayerBase::LayerBase(SurfaceFlinger* flinger, DisplayID display)
     : dpy(display), contentDirty(false),
       mFlinger(flinger),
       mTransformed(false),
       mOrientation(0),
-      mCanUseCopyBit(false),
       mTransactionFlags(0),
       mPremultipliedAlpha(true),
-      mIdentity(uint32_t(android_atomic_inc(&sIdentity))),
       mInvalidate(0)
 {
     const DisplayHardware& hw(flinger->graphicPlane(0).displayHardware());
@@ -265,43 +259,6 @@
     mTransformed = transformed;
     mLeft = tr.tx();
     mTop  = tr.ty();
-
-    // see if we can/should use 2D h/w with the new configuration
-    mCanUseCopyBit = false;
-    copybit_device_t* copybit = mFlinger->getBlitEngine();
-    if (copybit) { 
-        const int step = copybit->get(copybit, COPYBIT_ROTATION_STEP_DEG);
-        const int scaleBits = copybit->get(copybit, COPYBIT_SCALING_FRAC_BITS);
-        mCanUseCopyBit = true;
-        if ((mOrientation < 0) && (step > 1)) {
-            // arbitrary orientations not supported
-            mCanUseCopyBit = false;
-        } else if ((mOrientation > 0) && (step > 90)) {
-            // 90 deg rotations not supported
-            mCanUseCopyBit = false;
-        } else if ((tr.getType() & SkMatrix::kScale_Mask) && (scaleBits < 12)) { 
-            // arbitrary scaling not supported
-            mCanUseCopyBit = false;
-        }
-#if HONOR_PREMULTIPLIED_ALPHA 
-        else if (needsBlending() && mPremultipliedAlpha) {
-            // pre-multiplied alpha not supported
-            mCanUseCopyBit = false;
-        }
-#endif
-        else {
-            // here, we determined we can use copybit
-            if (tr.getType() & SkMatrix::kScale_Mask) {
-                // and we have scaling
-                if (!transparentRegionScreen.isRect()) {
-                    // we punt because blending is cheap (h/w) and the region is
-                    // complex, which may causes artifacts when copying
-                    // scaled content
-                    transparentRegionScreen.clear();
-                }
-            }
-        }
-    }
 }
 
 void LayerBase::lockPageFlip(bool& recomputeVisibleRegions)
@@ -329,8 +286,9 @@
 
 void LayerBase::drawRegion(const Region& reg) const
 {
-    Region::iterator iterator(reg);
-    if (iterator) {
+    Region::const_iterator it = reg.begin();
+    Region::const_iterator const end = reg.end();
+    if (it != end) {
         Rect r;
         const DisplayHardware& hw(graphicPlane(0).displayHardware());
         const int32_t fbWidth  = hw.getWidth();
@@ -338,7 +296,8 @@
         const GLshort vertices[][2] = { { 0, 0 }, { fbWidth, 0 }, 
                 { fbWidth, fbHeight }, { 0, fbHeight }  };
         glVertexPointer(2, GL_SHORT, 0, vertices);
-        while (iterator.iterate(&r)) {
+        while (it != end) {
+            const Rect& r = *it++;
             const GLint sy = fbHeight - (r.top + r.height());
             glScissor(r.left, sy, r.width(), r.height());
             glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 
@@ -403,12 +362,14 @@
     glDisable(GL_TEXTURE_2D);
     glDisable(GL_BLEND);
     glDisable(GL_DITHER);
-    Rect r;
-    Region::iterator iterator(clip);
-    if (iterator) {
+
+    Region::const_iterator it = clip.begin();
+    Region::const_iterator const end = clip.end();
+    if (it != end) {
         glEnable(GL_SCISSOR_TEST);
         glVertexPointer(2, GL_FIXED, 0, mVertices);
-        while (iterator.iterate(&r)) {
+        while (it != end) {
+            const Rect& r = *it++;
             const GLint sy = fbHeight - (r.top + r.height());
             glScissor(r.left, sy, r.width(), r.height());
             glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 
@@ -416,15 +377,17 @@
     }
 }
 
-void LayerBase::drawWithOpenGL(const Region& clip,
-        GLint textureName, const GGLSurface& t, int transform) const
+void LayerBase::drawWithOpenGL(const Region& clip, const Texture& texture) const
 {
     const DisplayHardware& hw(graphicPlane(0).displayHardware());
     const uint32_t fbHeight = hw.getHeight();
     const State& s(drawingState());
-
+    
     // bind our texture
-    validateTexture(textureName);
+    validateTexture(texture.name);
+    uint32_t width  = texture.width; 
+    uint32_t height = texture.height;
+    
     glEnable(GL_TEXTURE_2D);
 
     // Dithering...
@@ -472,8 +435,9 @@
             || !(mFlags & DisplayHardware::DRAW_TEXTURE_EXTENSION) )) 
     {
         //StopWatch watch("GL transformed");
-        Region::iterator iterator(clip);
-        if (iterator) {
+        Region::const_iterator it = clip.begin();
+        Region::const_iterator const end = clip.end();
+        if (it != end) {
             // always use high-quality filtering with fast configurations
             bool fast = !(mFlags & DisplayHardware::SLOW_CONFIG);
             if (!fast && s.flags & ISurfaceComposer::eLayerFilter) {
@@ -490,21 +454,23 @@
             glMatrixMode(GL_TEXTURE);
             glLoadIdentity();
             
-            if (transform == HAL_TRANSFORM_ROT_90) {
+            // the texture's source is rotated
+            if (texture.transform == HAL_TRANSFORM_ROT_90) {
+                // TODO: handle the other orientations
                 glTranslatef(0, 1, 0);
                 glRotatef(-90, 0, 0, 1);
             }
 
             if (!(mFlags & DisplayHardware::NPOT_EXTENSION)) {
                 // find the smallest power-of-two that will accommodate our surface
-                GLuint tw = 1 << (31 - clz(t.width));
-                GLuint th = 1 << (31 - clz(t.height));
-                if (tw < t.width)  tw <<= 1;
-                if (th < t.height) th <<= 1;
+                GLuint tw = 1 << (31 - clz(width));
+                GLuint th = 1 << (31 - clz(height));
+                if (tw < width)  tw <<= 1;
+                if (th < height) th <<= 1;
                 // this divide should be relatively fast because it's
                 // a power-of-two (optimized path in libgcc)
-                GLfloat ws = GLfloat(t.width) /tw;
-                GLfloat hs = GLfloat(t.height)/th;
+                GLfloat ws = GLfloat(width) /tw;
+                GLfloat hs = GLfloat(height)/th;
                 glScalef(ws, hs, 1.0f);
             }
 
@@ -512,8 +478,8 @@
             glVertexPointer(2, GL_FIXED, 0, mVertices);
             glTexCoordPointer(2, GL_FIXED, 0, texCoords);
 
-            Rect r;
-            while (iterator.iterate(&r)) {
+            while (it != end) {
+                const Rect& r = *it++;
                 const GLint sy = fbHeight - (r.top + r.height());
                 glScissor(r.left, sy, r.width(), r.height());
                 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 
@@ -526,18 +492,19 @@
             glDisableClientState(GL_TEXTURE_COORD_ARRAY);
         }
     } else {
-        Region::iterator iterator(clip);
-        if (iterator) {
-            Rect r;
-            GLint crop[4] = { 0, t.height, t.width, -t.height };
+        Region::const_iterator it = clip.begin();
+        Region::const_iterator const end = clip.end();
+        if (it != end) {
+            GLint crop[4] = { 0, height, width, -height };
             glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
             int x = tx();
             int y = ty();
-            y = fbHeight - (y + t.height);
-            while (iterator.iterate(&r)) {
+            y = fbHeight - (y + height);
+            while (it != end) {
+                const Rect& r = *it++;
                 const GLint sy = fbHeight - (r.top + r.height());
                 glScissor(r.left, sy, r.width(), r.height());
-                glDrawTexiOES(x, y, 0, t.width, t.height);
+                glDrawTexiOES(x, y, 0, width, height);
             }
         }
     }
@@ -550,13 +517,16 @@
     // this is currently done in loadTexture() below
 }
 
-void LayerBase::loadTexture(const Region& dirty,
-        GLint textureName, const GGLSurface& t,
-        GLuint& textureWidth, GLuint& textureHeight) const
+void LayerBase::loadTexture(Texture* texture, GLint textureName, 
+        const Region& dirty, const GGLSurface& t) const
 {
     // TODO: defer the actual texture reload until LayerBase::validateTexture
     // is called.
 
+    texture->name = textureName;
+    GLuint& textureWidth(texture->width);
+    GLuint& textureHeight(texture->height);
+    
     uint32_t flags = mFlags;
     glBindTexture(GL_TEXTURE_2D, textureName);
 
@@ -565,8 +535,7 @@
 
     /*
      * In OpenGL ES we can't specify a stride with glTexImage2D (however,
-     * GL_UNPACK_ALIGNMENT is 4, which in essence allows a limited form of
-     * stride).
+     * GL_UNPACK_ALIGNMENT is a limited form of stride).
      * So if the stride here isn't representable with GL_UNPACK_ALIGNMENT, we
      * need to do something reasonable (here creating a bigger texture).
      * 
@@ -579,9 +548,11 @@
      *
      * This should never be a problem with POT textures
      */
-
-    tw += (((t.stride - tw) * bytesPerPixel(t.format)) / 4);
-
+    
+    int unpack = __builtin_ctz(t.stride * bytesPerPixel(t.format));
+    unpack = 1 << ((unpack > 3) ? 3 : unpack);
+    glPixelStorei(GL_UNPACK_ALIGNMENT, unpack);
+    
     /*
      * round to POT if needed 
      */
@@ -594,119 +565,98 @@
         texture_h = 1 << (31 - clz(t.height));
         if (texture_w < t.width)  texture_w <<= 1;
         if (texture_h < t.height) texture_h <<= 1;
-        if (texture_w != tw || texture_h != th) {
-            // we can't use DIRECT_TEXTURE since we changed the size
-            // of the texture
-            flags &= ~DisplayHardware::DIRECT_TEXTURE;
-        }
     }
-
-    if (flags & DisplayHardware::DIRECT_TEXTURE) {
-        // here we're guaranteed that texture_{w|h} == t{w|h}
-        if (t.format == GGL_PIXEL_FORMAT_RGB_565) {
-            glTexImage2D(GL_DIRECT_TEXTURE_2D_QUALCOMM, 0,
-                    GL_RGB, tw, th, 0,
-                    GL_RGB, GL_UNSIGNED_SHORT_5_6_5, t.data);
-        } else if (t.format == GGL_PIXEL_FORMAT_RGBA_4444) {
-            glTexImage2D(GL_DIRECT_TEXTURE_2D_QUALCOMM, 0,
-                    GL_RGBA, tw, th, 0,
-                    GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, t.data);
-        } else if (t.format == GGL_PIXEL_FORMAT_RGBA_8888) {
-            glTexImage2D(GL_DIRECT_TEXTURE_2D_QUALCOMM, 0,
-                    GL_RGBA, tw, th, 0,
-                    GL_RGBA, GL_UNSIGNED_BYTE, t.data);
-        } else if (t.format == GGL_PIXEL_FORMAT_BGRA_8888) {
-            // TODO: add GL_BGRA extension
-        } else {
-            // oops, we don't handle this format, try the regular path
-            goto regular;
-        }
-        textureWidth = tw;
-        textureHeight = th;
-    } else {
+    
 regular:
-        Rect bounds(dirty.bounds());
-        GLvoid* data = 0;
-        if (texture_w!=textureWidth || texture_h!=textureHeight) {
-            // texture size changed, we need to create a new one
+    Rect bounds(dirty.bounds());
+    GLvoid* data = 0;
+    if (texture_w!=textureWidth || texture_h!=textureHeight) {
+        // texture size changed, we need to create a new one
 
-            if (!textureWidth || !textureHeight) {
-                // this is the first time, load the whole texture
-                if (texture_w==tw && texture_h==th) {
-                    // we can do it one pass
-                    data = t.data;
-                } else {
-                    // we have to create the texture first because it
-                    // doesn't match the size of the buffer
-                    bounds.set(Rect(tw, th));
-                }
-            }
-            
-            if (t.format == GGL_PIXEL_FORMAT_RGB_565) {
-                glTexImage2D(GL_TEXTURE_2D, 0,
-                        GL_RGB, texture_w, texture_h, 0,
-                        GL_RGB, GL_UNSIGNED_SHORT_5_6_5, data);
-            } else if (t.format == GGL_PIXEL_FORMAT_RGBA_4444) {
-                glTexImage2D(GL_TEXTURE_2D, 0,
-                        GL_RGBA, texture_w, texture_h, 0,
-                        GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, data);
-            } else if (t.format == GGL_PIXEL_FORMAT_RGBA_8888) {
-                glTexImage2D(GL_TEXTURE_2D, 0,
-                        GL_RGBA, texture_w, texture_h, 0,
-                        GL_RGBA, GL_UNSIGNED_BYTE, data);
-            } else if ( t.format == GGL_PIXEL_FORMAT_YCbCr_422_SP ||
-                        t.format == GGL_PIXEL_FORMAT_YCbCr_420_SP) {
-                // just show the Y plane of YUV buffers
+        if (!textureWidth || !textureHeight) {
+            // this is the first time, load the whole texture
+            if (texture_w==tw && texture_h==th) {
+                // we can do it one pass
                 data = t.data;
-                glTexImage2D(GL_TEXTURE_2D, 0,
-                        GL_LUMINANCE, texture_w, texture_h, 0,
-                        GL_LUMINANCE, GL_UNSIGNED_BYTE, data);
             } else {
-                // oops, we don't handle this format!
-                LOGE("layer %p, texture=%d, using format %d, which is not "
-                     "supported by the GL", this, textureName, t.format);
-                textureName = -1;
+                // we have to create the texture first because it
+                // doesn't match the size of the buffer
+                bounds.set(Rect(tw, th));
             }
-            textureWidth = texture_w;
-            textureHeight = texture_h;
         }
-        if (!data && textureName>=0) {
-            if (t.format == GGL_PIXEL_FORMAT_RGB_565) {
-                glTexSubImage2D(GL_TEXTURE_2D, 0,
-                        0, bounds.top, t.width, bounds.height(),
-                        GL_RGB, GL_UNSIGNED_SHORT_5_6_5,
-                        t.data + bounds.top*t.width*2);
-            } else if (t.format == GGL_PIXEL_FORMAT_RGBA_4444) {
-                glTexSubImage2D(GL_TEXTURE_2D, 0,
-                        0, bounds.top, t.width, bounds.height(),
-                        GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4,
-                        t.data + bounds.top*t.width*2);
-            } else if (t.format == GGL_PIXEL_FORMAT_RGBA_8888) {
-                glTexSubImage2D(GL_TEXTURE_2D, 0,
-                        0, bounds.top, t.width, bounds.height(),
-                        GL_RGBA, GL_UNSIGNED_BYTE,
-                        t.data + bounds.top*t.width*4);
-            }
+        
+        if (t.format == GGL_PIXEL_FORMAT_RGB_565) {
+            glTexImage2D(GL_TEXTURE_2D, 0,
+                    GL_RGB, texture_w, texture_h, 0,
+                    GL_RGB, GL_UNSIGNED_SHORT_5_6_5, data);
+        } else if (t.format == GGL_PIXEL_FORMAT_RGBA_4444) {
+            glTexImage2D(GL_TEXTURE_2D, 0,
+                    GL_RGBA, texture_w, texture_h, 0,
+                    GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, data);
+        } else if (t.format == GGL_PIXEL_FORMAT_RGBA_8888) {
+            glTexImage2D(GL_TEXTURE_2D, 0,
+                    GL_RGBA, texture_w, texture_h, 0,
+                    GL_RGBA, GL_UNSIGNED_BYTE, data);
+        } else if ( t.format == GGL_PIXEL_FORMAT_YCbCr_422_SP ||
+                    t.format == GGL_PIXEL_FORMAT_YCbCr_420_SP) {
+            // just show the Y plane of YUV buffers
+            glTexImage2D(GL_TEXTURE_2D, 0,
+                    GL_LUMINANCE, texture_w, texture_h, 0,
+                    GL_LUMINANCE, GL_UNSIGNED_BYTE, data);
+        } else {
+            // oops, we don't handle this format!
+            LOGE("layer %p, texture=%d, using format %d, which is not "
+                 "supported by the GL", this, textureName, t.format);
+            textureName = -1;
+        }
+        textureWidth = texture_w;
+        textureHeight = texture_h;
+    }
+    if (!data && textureName>=0) {
+        if (t.format == GGL_PIXEL_FORMAT_RGB_565) {
+            glTexSubImage2D(GL_TEXTURE_2D, 0,
+                    0, bounds.top, t.width, bounds.height(),
+                    GL_RGB, GL_UNSIGNED_SHORT_5_6_5,
+                    t.data + bounds.top*t.stride*2);
+        } else if (t.format == GGL_PIXEL_FORMAT_RGBA_4444) {
+            glTexSubImage2D(GL_TEXTURE_2D, 0,
+                    0, bounds.top, t.width, bounds.height(),
+                    GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4,
+                    t.data + bounds.top*t.stride*2);
+        } else if (t.format == GGL_PIXEL_FORMAT_RGBA_8888) {
+            glTexSubImage2D(GL_TEXTURE_2D, 0,
+                    0, bounds.top, t.width, bounds.height(),
+                    GL_RGBA, GL_UNSIGNED_BYTE,
+                    t.data + bounds.top*t.stride*4);
+        } else if ( t.format == GGL_PIXEL_FORMAT_YCbCr_422_SP ||
+                    t.format == GGL_PIXEL_FORMAT_YCbCr_420_SP) {
+            // just show the Y plane of YUV buffers
+            glTexSubImage2D(GL_TEXTURE_2D, 0,
+                    0, bounds.top, t.width, bounds.height(),
+                    GL_LUMINANCE, GL_UNSIGNED_BYTE,
+                    t.data + bounds.top*t.stride);
         }
     }
 }
 
-bool LayerBase::canUseCopybit() const
-{
-    return mCanUseCopyBit;
-}
-
 // ---------------------------------------------------------------------------
 
-LayerBaseClient::LayerBaseClient(SurfaceFlinger* flinger, DisplayID display,
-        Client* c, int32_t i)
-    : LayerBase(flinger, display), client(c),
-      lcblk( c ? &(c->ctrlblk->layers[i]) : 0 ),
-      mIndex(i)
-{
-    if (client) {
-        client->bindLayer(this, i);
+int32_t LayerBaseClient::sIdentity = 0;
 
+LayerBaseClient::LayerBaseClient(SurfaceFlinger* flinger, DisplayID display,
+        const sp<Client>& client, int32_t i)
+    : LayerBase(flinger, display), client(client),
+      lcblk( client!=0 ? &(client->ctrlblk->layers[i]) : 0 ),
+      mIndex(i),
+      mIdentity(uint32_t(android_atomic_inc(&sIdentity)))
+{
+}
+
+void LayerBaseClient::onFirstRef()
+{    
+    sp<Client> client(this->client.promote());
+    if (client != 0) {
+        client->bindLayer(this, mIndex);
         // Initialize this layer's control block
         memset(this->lcblk, 0, sizeof(layer_cblk_t));
         this->lcblk->identity = mIdentity;
@@ -717,23 +667,121 @@
 
 LayerBaseClient::~LayerBaseClient()
 {
-    if (client) {
+    sp<Client> client(this->client.promote());
+    if (client != 0) {
         client->free(mIndex);
     }
 }
 
-int32_t LayerBaseClient::serverIndex() const {
-    if (client) {
+int32_t LayerBaseClient::serverIndex() const 
+{
+    sp<Client> client(this->client.promote());
+    if (client != 0) {
         return (client->cid<<16)|mIndex;
     }
     return 0xFFFF0000 | mIndex;
 }
 
-sp<LayerBaseClient::Surface> LayerBaseClient::getSurface() const
+sp<LayerBaseClient::Surface> LayerBaseClient::getSurface()
 {
-    return new Surface(clientIndex(), mIdentity);
+    sp<Surface> s;
+    Mutex::Autolock _l(mLock);
+    s = mClientSurface.promote();
+    if (s == 0) {
+        s = createSurface();
+        mClientSurface = s;
+    }
+    return s;
 }
 
+sp<LayerBaseClient::Surface> LayerBaseClient::createSurface() const
+{
+    return new Surface(mFlinger, clientIndex(), mIdentity,
+            const_cast<LayerBaseClient *>(this));
+}
+
+// ---------------------------------------------------------------------------
+
+LayerBaseClient::Surface::Surface(
+        const sp<SurfaceFlinger>& flinger,
+        SurfaceID id, int identity, 
+        const sp<LayerBaseClient>& owner) 
+    : mFlinger(flinger), mToken(id), mIdentity(identity), mOwner(owner)
+{
+}
+
+
+LayerBaseClient::Surface::~Surface() 
+{
+    /*
+     * This is a good place to clean-up all client resources 
+     */
+
+    // destroy client resources
+    sp<LayerBaseClient> layer = getOwner();
+    if (layer != 0) {
+        mFlinger->destroySurface(layer);
+    }
+}
+
+sp<LayerBaseClient> LayerBaseClient::Surface::getOwner() const {
+    sp<LayerBaseClient> owner(mOwner.promote());
+    return owner;
+}
+
+
+void LayerBaseClient::Surface::getSurfaceData(
+        ISurfaceFlingerClient::surface_data_t* params) const 
+{
+    params->token = mToken;
+    params->identity = mIdentity;
+}
+
+status_t LayerBaseClient::Surface::onTransact(
+        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
+{
+    switch (code) {
+        case REGISTER_BUFFERS:
+        case UNREGISTER_BUFFERS:
+        case CREATE_OVERLAY:
+        {
+            if (!mFlinger->mAccessSurfaceFlinger.checkCalling()) {
+                IPCThreadState* ipc = IPCThreadState::self();
+                const int pid = ipc->getCallingPid();
+                const int uid = ipc->getCallingUid();
+                LOGE("Permission Denial: "
+                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
+                return PERMISSION_DENIED;
+            }
+        }
+    }
+    return BnSurface::onTransact(code, data, reply, flags);
+}
+
+sp<SurfaceBuffer> LayerBaseClient::Surface::getBuffer() 
+{
+    return NULL; 
+}
+
+status_t LayerBaseClient::Surface::registerBuffers(
+        const ISurface::BufferHeap& buffers) 
+{ 
+    return INVALID_OPERATION; 
+}
+
+void LayerBaseClient::Surface::postBuffer(ssize_t offset) 
+{
+}
+
+void LayerBaseClient::Surface::unregisterBuffers() 
+{
+}
+
+sp<OverlayRef> LayerBaseClient::Surface::createOverlay(
+        uint32_t w, uint32_t h, int32_t format) 
+{
+    return NULL;
+};
 
 // ---------------------------------------------------------------------------
 
diff --git a/libs/surfaceflinger/LayerBase.h b/libs/surfaceflinger/LayerBase.h
index a020f44..6fb1d1c 100644
--- a/libs/surfaceflinger/LayerBase.h
+++ b/libs/surfaceflinger/LayerBase.h
@@ -20,8 +20,13 @@
 #include <stdint.h>
 #include <sys/types.h>
 
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+
 #include <private/ui/LayerState.h>
 
+#include <utils/RefBase.h>
+
 #include <ui/Region.h>
 #include <ui/Overlay.h>
 
@@ -37,10 +42,12 @@
 class DisplayHardware;
 class GraphicPlane;
 class Client;
+class SurfaceBuffer;
+class Buffer;
 
 // ---------------------------------------------------------------------------
 
-class LayerBase
+class LayerBase : public RefBase
 {
     // poor man's dynamic_cast below
     template<typename T>
@@ -69,10 +76,7 @@
     }
 
     
-    static Vector<GLuint> deletedTextures; 
-
     LayerBase(SurfaceFlinger* flinger, DisplayID display);
-    virtual ~LayerBase();
     
     DisplayID           dpy;
     mutable bool        contentDirty;
@@ -201,21 +205,29 @@
 
     /**
      * isSecure - true if this surface is secure, that is if it prevents
-     * screenshots or vns servers.
+     * screenshots or VNC servers.
      */
     virtual bool isSecure() const       { return false; }
 
-            enum { // flags for doTransaction()
-                eVisibleRegion      = 0x00000002,
-                eRestartTransaction = 0x00000008
-            };
+    /** signal this layer that it's not needed any longer. called from the 
+     * main thread */
+    virtual status_t ditch() { return NO_ERROR; }
+
+    
+    
+    enum { // flags for doTransaction()
+        eVisibleRegion      = 0x00000002,
+        eRestartTransaction = 0x00000008
+    };
 
 
     inline  const State&    drawingState() const    { return mDrawingState; }
     inline  const State&    currentState() const    { return mCurrentState; }
     inline  State&          currentState()          { return mCurrentState; }
 
-    static int compareCurrentStateZ(LayerBase*const* layerA, LayerBase*const* layerB) {
+    static int compareCurrentStateZ(
+            sp<LayerBase> const * layerA,
+            sp<LayerBase> const * layerB) {
         return layerA[0]->currentState().z - layerB[0]->currentState().z;
     }
 
@@ -229,20 +241,24 @@
 
           GLuint createTexture() const;
     
-          void drawWithOpenGL(const Region& clip,
-                  GLint textureName,
-                  const GGLSurface& surface,
-                  int transform = 0) const;
-
-          void clearWithOpenGL(const Region& clip) const;
-
-          void loadTexture(const Region& dirty,
-                  GLint textureName, const GGLSurface& t,
-                  GLuint& textureWidth, GLuint& textureHeight) const;
-
-          bool canUseCopybit() const;
+          struct Texture {
+              Texture() : name(-1U), width(0), height(0),
+                  image(EGL_NO_IMAGE_KHR), transform(0), dirty(true) { }
+              GLuint        name;
+              GLuint        width;
+              GLuint        height;
+              EGLImageKHR   image;
+              uint32_t      transform;
+              bool          dirty;
+          };
           
-                SurfaceFlinger* mFlinger;
+          void clearWithOpenGL(const Region& clip) const;
+          void drawWithOpenGL(const Region& clip, const Texture& texture) const;
+          void loadTexture(Texture* texture, GLint textureName, 
+                  const Region& dirty, const GGLSurface& t) const;
+
+          
+                sp<SurfaceFlinger> mFlinger;
                 uint32_t        mFlags;
 
                 // cached during validateVisibility()
@@ -250,7 +266,6 @@
                 int32_t         mOrientation;
                 GLfixed         mVertices[4][2];
                 Rect            mTransformedBounds;
-                bool            mCanUseCopyBit;
                 int             mLeft;
                 int             mTop;
             
@@ -262,16 +277,16 @@
                 // don't change, don't need a lock
                 bool            mPremultipliedAlpha;
 
-                // only read
-    const       uint32_t        mIdentity;
-     
                 // atomic
     volatile    int32_t         mInvalidate;
                 
 
+protected:
+    virtual ~LayerBase();
+
 private:
-                void validateTexture(GLint textureName) const;
-    static      int32_t         sIdentity;
+    LayerBase(const LayerBase& rhs);
+    void validateTexture(GLint textureName) const;
 };
 
 
@@ -287,66 +302,63 @@
     virtual uint32_t getTypeInfo() const { return typeInfo; }
 
     LayerBaseClient(SurfaceFlinger* flinger, DisplayID display, 
-            Client* client, int32_t i);
+            const sp<Client>& client, int32_t i);
     virtual ~LayerBaseClient();
+    virtual void onFirstRef();
 
-
-    Client*             const client;
+    wp<Client>          client;
     layer_cblk_t*       const lcblk;
 
+    inline  uint32_t    getIdentity() const { return mIdentity; }
     inline  int32_t     clientIndex() const { return mIndex; }
             int32_t     serverIndex() const;
 
-    virtual sp<Surface> getSurface() const;
    
-            uint32_t    getIdentity() const { return mIdentity; }
+            sp<Surface> getSurface();
+    virtual sp<Surface> createSurface() const;
+    
 
     class Surface : public BnSurface 
     {
     public:
-        Surface(SurfaceID id, int identity) { 
-            mParams.token = id;
-            mParams.identity = identity;
-        }
-        Surface(SurfaceID id, 
-                const sp<IMemoryHeap>& heap0,
-                const sp<IMemoryHeap>& heap1,
-                int identity)
-        {
-            mParams.token = id;
-            mParams.identity = identity;
-            mParams.heap[0] = heap0;
-            mParams.heap[1] = heap1;
-        }
-        virtual ~Surface() {
-            // TODO: We now have a point here were we can clean-up the
-            // client's mess.
-            // This is also where surface id should be recycled.
-            //LOGD("Surface %d, heaps={%p, %p} destroyed",
-            //        mId, mHeap[0].get(), mHeap[1].get());
-        }
-
+        
         virtual void getSurfaceData(
-                ISurfaceFlingerClient::surface_data_t* params) const {
-            *params = mParams;
-        }
+                ISurfaceFlingerClient::surface_data_t* params) const;
 
-        virtual status_t registerBuffers(const ISurface::BufferHeap& buffers) 
-                { return INVALID_OPERATION; }
-        virtual void postBuffer(ssize_t offset) { }
-        virtual void unregisterBuffers() { };
-        virtual sp<OverlayRef> createOverlay(
-                uint32_t w, uint32_t h, int32_t format) {
-            return NULL;
-        };
+    protected:
+        Surface(const sp<SurfaceFlinger>& flinger, 
+                SurfaceID id, int identity, 
+                const sp<LayerBaseClient>& owner);
+        virtual ~Surface();
+        virtual status_t onTransact(uint32_t code, const Parcel& data,
+                Parcel* reply, uint32_t flags);
+        sp<LayerBaseClient> getOwner() const;
 
     private:
-        ISurfaceFlingerClient::surface_data_t mParams;
+        virtual sp<SurfaceBuffer> getBuffer();
+        virtual status_t registerBuffers(const ISurface::BufferHeap& buffers); 
+        virtual void postBuffer(ssize_t offset);
+        virtual void unregisterBuffers();
+        virtual sp<OverlayRef> createOverlay(uint32_t w, uint32_t h,
+                int32_t format);
+
+    protected:
+        friend class LayerBaseClient;
+        sp<SurfaceFlinger>  mFlinger;
+        int32_t             mToken;
+        int32_t             mIdentity;
+        wp<LayerBaseClient> mOwner;
     };
 
-private:
-    int32_t mIndex;
+    friend class Surface;
 
+private:
+                int32_t         mIndex;
+    mutable     Mutex           mLock;
+    mutable     wp<Surface>     mClientSurface;
+    // only read
+    const       uint32_t        mIdentity;
+    static      int32_t         sIdentity;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/libs/surfaceflinger/LayerBitmap.cpp b/libs/surfaceflinger/LayerBitmap.cpp
index 397ddc8..9fffbbf 100644
--- a/libs/surfaceflinger/LayerBitmap.cpp
+++ b/libs/surfaceflinger/LayerBitmap.cpp
@@ -14,173 +14,196 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <stdlib.h>
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <cutils/memory.h>
 #include <utils/Errors.h>
 #include <utils/Log.h>
-#include <utils/MemoryDealer.h>
-#include <utils/IMemory.h>
+#include <binder/MemoryBase.h>
+#include <binder/IMemory.h>
+
 #include <ui/PixelFormat.h>
+#include <ui/Surface.h>
 #include <pixelflinger/pixelflinger.h>
 
+#include "BufferAllocator.h"
 #include "LayerBitmap.h"
 #include "SurfaceFlinger.h"
-#include "VRamHeap.h"
 
 
 namespace android {
 
-// ---------------------------------------------------------------------------
+// ===========================================================================
+// Buffer and implementation of android_native_buffer_t
+// ===========================================================================
+
+Buffer::Buffer(uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
+    : SurfaceBuffer(), mInitCheck(NO_INIT), mFlags(flags), 
+    mVStride(0)
+{
+    this->format = format;
+    if (w>0 && h>0) {
+        mInitCheck = initSize(w, h);
+    }
+}
+
+Buffer::~Buffer()
+{
+    if (handle) {
+        BufferAllocator& allocator(BufferAllocator::get());
+        allocator.free(handle);
+    }
+}
+
+status_t Buffer::initCheck() const {
+    return mInitCheck;
+}
+
+android_native_buffer_t* Buffer::getNativeBuffer() const
+{
+    return static_cast<android_native_buffer_t*>(const_cast<Buffer*>(this));
+}
+
+status_t Buffer::initSize(uint32_t w, uint32_t h)
+{
+    status_t err = NO_ERROR;
+
+    BufferAllocator& allocator = BufferAllocator::get();
+        
+    /*
+     *  buffers used for software rendering, but h/w composition
+     *  are allocated with SW_READ_OFTEN | SW_WRITE_OFTEN | HW_TEXTURE
+     *  
+     *  buffers used for h/w rendering and h/w composition
+     *  are allocated with  HW_RENDER | HW_TEXTURE
+     *  
+     *  buffers used with h/w rendering and either NPOT or no egl_image_ext
+     *  are allocated with SW_READ_RARELY | HW_RENDER 
+     *  
+     */
+    
+    if (mFlags & Buffer::SECURE) {
+        // secure buffer, don't store it into the GPU
+        usage = BufferAllocator::USAGE_SW_READ_OFTEN | 
+                BufferAllocator::USAGE_SW_WRITE_OFTEN;
+    } else {
+        if (mFlags & Buffer::GPU) {
+            // the client wants to do GL rendering
+            usage = BufferAllocator::USAGE_HW_RENDER |
+                    BufferAllocator::USAGE_HW_TEXTURE;
+        } else {
+            // software rendering-client, h/w composition
+            usage = BufferAllocator::USAGE_SW_READ_OFTEN | 
+                    BufferAllocator::USAGE_SW_WRITE_OFTEN |
+                    BufferAllocator::USAGE_HW_TEXTURE;
+        }
+    }
+
+    err = allocator.alloc(w, h, format, usage, &handle, &stride);
+    
+    if (err == NO_ERROR) {
+        if (err == NO_ERROR) {
+            width  = w;
+            height = h;
+            mVStride = 0;
+        }
+    }
+
+    return err;
+}
+
+status_t Buffer::lock(GGLSurface* sur, uint32_t usage) 
+{
+    void* vaddr;
+    status_t res = SurfaceBuffer::lock(usage, &vaddr);
+    if (res == NO_ERROR && sur) {
+        sur->version = sizeof(GGLSurface);
+        sur->width = width;
+        sur->height = height;
+        sur->stride = stride;
+        sur->format = format;
+        sur->vstride = mVStride;
+        sur->data = static_cast<GGLubyte*>(vaddr);
+    }
+    return res;
+}
+
+// ===========================================================================
+// LayerBitmap
+// ===========================================================================
 
 LayerBitmap::LayerBitmap()
-    : mAllocFlags(0), mOffset(0), mSize(-1U), mAlignment(2)
+    : mInfo(0), mWidth(0), mHeight(0)
 {
-    memset(&mSurface, 0, sizeof(mSurface));
 }
 
 LayerBitmap::~LayerBitmap()
 {
-    mSurface.data = 0;
 }
 
-status_t LayerBitmap::init(const sp<MemoryDealer>& allocator)
+status_t LayerBitmap::init(surface_info_t* info,
+        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
 {
-    if (mAllocator != NULL)
+    if (info == NULL)
         return BAD_VALUE;
-    mAllocator = allocator;
+    
+    mFormat = format;
+    mFlags = flags;
+    mWidth = w;
+    mHeight = h;
+
+    mInfo = info;
+    memset(info, 0, sizeof(surface_info_t));
+    info->flags = surface_info_t::eNeedNewBuffer;
+    
+    // init the buffer, but don't trigger an allocation
+    mBuffer = new Buffer(0, 0, format, flags);
     return NO_ERROR;
 }
 
-status_t LayerBitmap::setBits(uint32_t w, uint32_t h, uint32_t alignment, 
-        PixelFormat format, uint32_t flags)
+status_t LayerBitmap::setSize(uint32_t w, uint32_t h)
 {
-    const sp<MemoryDealer>& allocator(mAllocator);
-    if (allocator == NULL)
-        return NO_INIT;
-
-    if (UNLIKELY(w == mSurface.width && h == mSurface.height &&
-            format == mSurface.format))
-    { // same format and size, do nothing.
-        return NO_ERROR;
-    }
-
-    PixelFormatInfo info;
-    getPixelFormatInfo(format, &info);
-
-    uint32_t allocFlags = MemoryDealer::PAGE_ALIGNED;
-    const uint32_t align = 4; // must match GL_UNPACK_ALIGNMENT
-    const uint32_t Bpp = info.bytesPerPixel;
-    uint32_t stride = (w + (alignment-1)) & ~(alignment-1);
-    stride = ((stride * Bpp + (align-1)) & ~(align-1)) / Bpp;
-    size_t size = info.getScanlineSize(stride) * h;
-    if (allocFlags & MemoryDealer::PAGE_ALIGNED) {
-        size_t pagesize = getpagesize();
-        size = (size + (pagesize-1)) & ~(pagesize-1);
-    }
-
-    /* FIXME: we should be able to have a h/v stride because the user of the
-     * surface might have stride limitation (for instance h/w codecs often do)
-     */
-    int32_t vstride = 0;
-
-    mAlignment = alignment;
-    mAllocFlags = allocFlags;
-    mOffset = 0;
-    if (mSize != size) {
-        // would be nice to have a reallocate() api
-        mBitsMemory.clear(); // free-memory
-        mBitsMemory = allocator->allocate(size, allocFlags);
-        mSize = size;
-    } else {
-        // don't erase memory if we didn't have to reallocate
-        flags &= ~SECURE_BITS;
-    }
-    if (mBitsMemory != 0) {
-        mOffset = mBitsMemory->offset();
-        mSurface.data = static_cast<GGLubyte*>(mBitsMemory->pointer());
-        mSurface.version = sizeof(GGLSurface);
-        mSurface.width  = w;
-        mSurface.height = h;
-        mSurface.stride = stride;
-        mSurface.vstride = vstride;
-        mSurface.format = format;
-        if (flags & SECURE_BITS)
-            clear();
-    }
-
-    if (mBitsMemory==0 || mSurface.data==0) {
-        LOGE("not enough memory for layer bitmap "
-             "size=%u (w=%d, h=%d, stride=%d, format=%d)",
-             size, int(w), int(h), int(stride), int(format));
-        allocator->dump("LayerBitmap");
-        mSurface.data = 0;
-        mSize = -1U;
-        return NO_MEMORY;
+    Mutex::Autolock _l(mLock);
+    if ((w != mWidth) || (h != mHeight)) {
+        mWidth  = w;
+        mHeight = h;
+        // this will signal the client that it needs to asks us for a new buffer
+        mInfo->flags = surface_info_t::eNeedNewBuffer;
     }
     return NO_ERROR;
 }
 
-void LayerBitmap::clear()
+sp<Buffer> LayerBitmap::allocate()
 {
-    // NOTE: this memset should not be necessary, at least for
-    // opaque surface. However, for security reasons it's better to keep it
-    // (in the case of pmem, it's possible that the memory contains old
-    // data)
-    if (mSurface.data) {
-        memset(mSurface.data, 0, mSize);
-        //if (bytesPerPixel(mSurface.format) == 4) {
-        //    android_memset32((uint32_t*)mSurface.data, 0xFF0000FF, mSize);
-        //} else  {
-        //    android_memset16((uint16_t*)mSurface.data, 0xF800, mSize);
-        //}
+    Mutex::Autolock _l(mLock);
+    sp<Buffer> buffer(mBuffer);
+    const uint32_t w = mWidth; 
+    const uint32_t h = mHeight;
+    if (buffer!=0 && (w != buffer->getWidth() || h != buffer->getHeight())) {
+        surface_info_t* info = mInfo;
+        buffer = new Buffer(w, h, mFormat, mFlags);
+        status_t err = buffer->initCheck();
+        if (LIKELY(err == NO_ERROR)) {
+            info->flags  = surface_info_t::eBufferDirty;
+            info->status = NO_ERROR;
+        } else {
+            memset(info, 0, sizeof(surface_info_t));
+            info->status = NO_MEMORY;
+        }
+        mBuffer = buffer;
     }
+    return buffer;
 }
 
-status_t LayerBitmap::getInfo(surface_info_t* info) const
+status_t LayerBitmap::free()
 {
-    if (mSurface.data == 0) {
-        memset(info, 0, sizeof(surface_info_t));
-        info->bits_offset = NO_MEMORY;
-        return NO_MEMORY;
-    }
-    info->w     = uint16_t(width());
-    info->h     = uint16_t(height());
-    info->stride= uint16_t(stride());
-    info->bpr   = uint16_t(stride() * bytesPerPixel(pixelFormat()));
-    info->format= uint8_t(pixelFormat());
-    info->flags = surface_info_t::eBufferDirty;
-    info->bits_offset = ssize_t(mOffset);
+    mBuffer.clear();
+    mWidth = 0;
+    mHeight = 0;
     return NO_ERROR;
 }
 
-status_t LayerBitmap::resize(uint32_t w, uint32_t h)
-{
-    int err = setBits(w, h, mAlignment, pixelFormat(), SECURE_BITS);
-    return err;
-}
-
-size_t LayerBitmap::size() const
-{
-    return mSize;
-}
-
-void LayerBitmap::getBitmapSurface(copybit_image_t* img) const
-{
-    const sp<IMemoryHeap>& mh(getAllocator()->getMemoryHeap());
-    void* sbase = mh->base();
-    const GGLSurface& t(surface());
-    img->w = t.stride  ?: t.width;
-    img->h = t.vstride ?: t.height;
-    img->format = t.format;
-    img->offset = intptr_t(t.data) - intptr_t(sbase);
-    img->base = sbase;
-    img->fd = mh->heapID();
-}
 
 // ---------------------------------------------------------------------------
 
diff --git a/libs/surfaceflinger/LayerBitmap.h b/libs/surfaceflinger/LayerBitmap.h
index 9ad64c4..22525ce 100644
--- a/libs/surfaceflinger/LayerBitmap.h
+++ b/libs/surfaceflinger/LayerBitmap.h
@@ -20,63 +20,114 @@
 #include <stdint.h>
 #include <sys/types.h>
 
+#include <hardware/gralloc.h>
+
 #include <utils/Atomic.h>
+
 #include <ui/PixelFormat.h>
 #include <ui/Rect.h>
-#include <private/ui/SharedState.h>
+#include <ui/Surface.h>
+
 #include <pixelflinger/pixelflinger.h>
 
+#include <private/ui/SharedState.h>
+#include <private/ui/SurfaceBuffer.h>
+
 class copybit_image_t;
+struct android_native_buffer_t;
 
 namespace android {
 
 // ---------------------------------------------------------------------------
-
 class IMemory;
-class MemoryDealer;
 class LayerBitmap;
 
-// ---------------------------------------------------------------------------
+// ===========================================================================
+// Buffer
+// ===========================================================================
+
+class NativeBuffer;
+
+class Buffer : public SurfaceBuffer
+{
+public:
+    enum {
+        DONT_CLEAR  = 0x00000001,
+        GPU         = 0x00000002,
+        SECURE      = 0x00000004
+    };
+
+    // creates w * h buffer
+    Buffer(uint32_t w, uint32_t h, PixelFormat format, uint32_t flags = 0);
+
+    // return status
+    status_t initCheck() const;
+
+    uint32_t getWidth() const           { return width; }
+    uint32_t getHeight() const          { return height; }
+    uint32_t getStride() const          { return stride; }
+    uint32_t getUsage() const           { return usage; }
+    PixelFormat getPixelFormat() const  { return format; }
+    Rect getBounds() const              { return Rect(width, height); }
+    
+    status_t lock(GGLSurface* surface, uint32_t usage);
+    
+    android_native_buffer_t* getNativeBuffer() const;
+    
+private:
+    friend class LightRefBase<Buffer>;
+    Buffer(const Buffer& rhs);
+    virtual ~Buffer();
+    Buffer& operator = (const Buffer& rhs);
+    const Buffer& operator = (const Buffer& rhs) const;
+
+    status_t initSize(uint32_t w, uint32_t h);
+
+    ssize_t                 mInitCheck;
+    uint32_t                mFlags;
+    uint32_t                mVStride;
+};
+
+// ===========================================================================
+// LayerBitmap
+// ===========================================================================
 
 class LayerBitmap
 {
 public:
-
     enum {
-        // erase memory to ensure security when necessary
-        SECURE_BITS = 0x00000001
+        DONT_CLEAR  = Buffer::DONT_CLEAR,
+        GPU         = Buffer::GPU,
+        SECURE      = Buffer::SECURE
     };
+    LayerBitmap();
+    ~LayerBitmap();
 
-                LayerBitmap();
-                ~LayerBitmap();
-    status_t    init(const sp<MemoryDealer>& allocator);
+    status_t init(surface_info_t* info,
+            uint32_t w, uint32_t h, PixelFormat format, uint32_t flags = 0);
 
-    status_t    setBits(uint32_t w, uint32_t h, uint32_t alignment,
-                        PixelFormat format, uint32_t flags = 0);
-    void        clear();
+    status_t setSize(uint32_t w, uint32_t h);
 
-    status_t    getInfo(surface_info_t* info) const;
-    status_t    resize(uint32_t w, uint32_t h);
-
-    const GGLSurface& surface() const   { return mSurface; }
-    Rect bounds() const                 { return Rect(width(), height()); }
-    uint32_t width() const              { return surface().width; }
-    uint32_t height() const             { return surface().height; }
-    uint32_t stride() const             { return surface().stride; }
-    PixelFormat pixelFormat() const     { return surface().format; }
-    void* serverBits() const            { return surface().data; }
-    size_t size() const;
-    const sp<MemoryDealer>& getAllocator() const { return mAllocator; }
-    void getBitmapSurface(copybit_image_t* img) const;
-
+    sp<Buffer> allocate();
+    status_t free();
+    
+    sp<const Buffer>  getBuffer() const { return mBuffer; }
+    sp<Buffer>        getBuffer()       { return mBuffer; }
+    
+    uint32_t getWidth() const           { return mWidth; }
+    uint32_t getHeight() const          { return mHeight; }
+    PixelFormat getPixelFormat() const  { return mBuffer->getPixelFormat(); }
+    Rect getBounds() const              { return mBuffer->getBounds(); }
+    
 private:
-    sp<MemoryDealer>        mAllocator;
-    sp<IMemory>             mBitsMemory;
-    uint32_t                mAllocFlags;
-    ssize_t                 mOffset;
-    GGLSurface              mSurface;
-    size_t                  mSize;
-    uint32_t                mAlignment;
+    surface_info_t* mInfo;
+    sp<Buffer>      mBuffer;
+    uint32_t        mWidth;
+    uint32_t        mHeight;
+    PixelFormat     mFormat;
+    uint32_t        mFlags;
+    // protects setSize() and allocate()
+    mutable Mutex   mLock;
 };
 
 }; // namespace android
diff --git a/libs/surfaceflinger/LayerBlur.cpp b/libs/surfaceflinger/LayerBlur.cpp
index d3e456f..00abd5a 100644
--- a/libs/surfaceflinger/LayerBlur.cpp
+++ b/libs/surfaceflinger/LayerBlur.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <stdlib.h>
 #include <stdint.h>
 #include <sys/types.h>
@@ -40,7 +38,7 @@
 // ---------------------------------------------------------------------------
 
 LayerBlur::LayerBlur(SurfaceFlinger* flinger, DisplayID display,
-        Client* client, int32_t i)
+        const sp<Client>& client, int32_t i)
      : LayerBaseClient(flinger, display, client, i), mCacheDirty(true),
      mRefreshCache(true), mCacheAge(0), mTextureName(-1U)
 {
@@ -49,8 +47,7 @@
 LayerBlur::~LayerBlur()
 {
     if (mTextureName != -1U) {
-        //glDeleteTextures(1, &mTextureName);
-        deletedTextures.add(mTextureName);
+        glDeleteTextures(1, &mTextureName);
     }
 }
 
@@ -139,8 +136,9 @@
         glGenTextures(1, &mTextureName);
     }
 
-    Region::iterator iterator(clip);
-    if (iterator) {
+    Region::const_iterator it = clip.begin();
+    Region::const_iterator const end = clip.end();
+    if (it != end) {
         glEnable(GL_TEXTURE_2D);
         glBindTexture(GL_TEXTURE_2D, mTextureName);
     
@@ -201,27 +199,25 @@
             glEnableClientState(GL_TEXTURE_COORD_ARRAY);
             glVertexPointer(2, GL_FIXED, 0, mVertices);
             glTexCoordPointer(2, GL_FIXED, 0, mVertices);
-            Rect r;
-            while (iterator.iterate(&r)) {
+            while (it != end) {
+                const Rect& r = *it++;
                 const GLint sy = fbHeight - (r.top + r.height());
                 glScissor(r.left, sy, r.width(), r.height());
                 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 
             }       
         } else {
-            Region::iterator iterator(clip);
-            if (iterator) {
-                // NOTE: this is marginally faster with the software gl, because
-                // glReadPixels() reads the fb bottom-to-top, however we'll
-                // skip all the jaccobian computations.
-                Rect r;
-                GLint crop[4] = { 0, 0, w, h };
-                glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
-                y = fbHeight - (y + h);
-                while (iterator.iterate(&r)) {
-                    const GLint sy = fbHeight - (r.top + r.height());
-                    glScissor(r.left, sy, r.width(), r.height());
-                    glDrawTexiOES(x, y, 0, w, h);
-                }
+            // NOTE: this is marginally faster with the software gl, because
+            // glReadPixels() reads the fb bottom-to-top, however we'll
+            // skip all the jaccobian computations.
+            Rect r;
+            GLint crop[4] = { 0, 0, w, h };
+            glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
+            y = fbHeight - (y + h);
+            while (it != end) {
+                const Rect& r = *it++;
+                const GLint sy = fbHeight - (r.top + r.height());
+                glScissor(r.left, sy, r.width(), r.height());
+                glDrawTexiOES(x, y, 0, w, h);
             }
         }
     }
diff --git a/libs/surfaceflinger/LayerBlur.h b/libs/surfaceflinger/LayerBlur.h
index 24b1156..0c3e6eb 100644
--- a/libs/surfaceflinger/LayerBlur.h
+++ b/libs/surfaceflinger/LayerBlur.h
@@ -39,7 +39,7 @@
     virtual uint32_t getTypeInfo() const { return typeInfo; }
     
                 LayerBlur(SurfaceFlinger* flinger, DisplayID display,
-                        Client* client, int32_t i);
+                        const sp<Client>& client, int32_t i);
         virtual ~LayerBlur();
 
     virtual void onDraw(const Region& clip) const;
diff --git a/libs/surfaceflinger/LayerBuffer.cpp b/libs/surfaceflinger/LayerBuffer.cpp
index 00fab70..90e7f50 100644
--- a/libs/surfaceflinger/LayerBuffer.cpp
+++ b/libs/surfaceflinger/LayerBuffer.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <stdlib.h>
 #include <stdint.h>
 #include <math.h>
@@ -25,17 +23,16 @@
 #include <utils/Log.h>
 #include <utils/StopWatch.h>
 
-#include <utils/IPCThreadState.h>
-#include <utils/IServiceManager.h>
-
 #include <ui/PixelFormat.h>
-#include <ui/EGLDisplaySurface.h>
+#include <ui/FramebufferNativeWindow.h>
+
+#include <hardware/copybit.h>
 
 #include "LayerBuffer.h"
 #include "SurfaceFlinger.h"
-#include "VRamHeap.h"
 #include "DisplayHardware/DisplayHardware.h"
 
+#include "gralloc_priv.h"   // needed for msm / copybit
 
 namespace android {
 
@@ -47,7 +44,7 @@
 // ---------------------------------------------------------------------------
 
 LayerBuffer::LayerBuffer(SurfaceFlinger* flinger, DisplayID display,
-        Client* client, int32_t i)
+        const sp<Client>& client, int32_t i)
     : LayerBaseClient(flinger, display, client, i),
       mNeedsBlending(false)
 {
@@ -55,30 +52,24 @@
 
 LayerBuffer::~LayerBuffer()
 {
-    sp<SurfaceBuffer> s(getClientSurface());
-    if (s != 0) {
-        s->disown();
-        mClientSurface.clear();
-    }
 }
 
-sp<LayerBuffer::SurfaceBuffer> LayerBuffer::getClientSurface() const
+void LayerBuffer::onFirstRef()
 {
-    Mutex::Autolock _l(mLock);
-    return mClientSurface.promote();
+    LayerBaseClient::onFirstRef();
+    mSurface = new SurfaceBuffer(mFlinger, clientIndex(),
+            const_cast<LayerBuffer *>(this));
 }
 
-sp<LayerBaseClient::Surface> LayerBuffer::getSurface() const
+sp<LayerBaseClient::Surface> LayerBuffer::createSurface() const
 {
-    sp<SurfaceBuffer> s;
-    Mutex::Autolock _l(mLock);
-    s = mClientSurface.promote();
-    if (s == 0) {
-        s = new SurfaceBuffer(clientIndex(),
-                const_cast<LayerBuffer *>(this));
-        mClientSurface = s;
-    }
-    return s;
+    return mSurface;
+}
+
+status_t LayerBuffer::ditch()
+{
+    mSurface.clear();
+    return NO_ERROR;
 }
 
 bool LayerBuffer::needsBlending() const {
@@ -192,82 +183,49 @@
 // LayerBuffer::SurfaceBuffer
 // ============================================================================
 
-LayerBuffer::SurfaceBuffer::SurfaceBuffer(SurfaceID id, LayerBuffer* owner)
-: LayerBaseClient::Surface(id, owner->getIdentity()), mOwner(owner)
+LayerBuffer::SurfaceBuffer::SurfaceBuffer(const sp<SurfaceFlinger>& flinger,
+        SurfaceID id, const sp<LayerBuffer>& owner)
+    : LayerBaseClient::Surface(flinger, id, owner->getIdentity(), owner)
 {
 }
 
 LayerBuffer::SurfaceBuffer::~SurfaceBuffer()
 {
     unregisterBuffers();
-    mOwner = 0;
 }
 
-status_t LayerBuffer::SurfaceBuffer::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
+status_t LayerBuffer::SurfaceBuffer::registerBuffers(
+        const ISurface::BufferHeap& buffers)
 {
-    switch (code) {
-        case REGISTER_BUFFERS:
-        case UNREGISTER_BUFFERS:
-        case CREATE_OVERLAY:
-        {
-            // codes that require permission check
-            IPCThreadState* ipc = IPCThreadState::self();
-            const int pid = ipc->getCallingPid();
-            const int self_pid = getpid();
-            if (LIKELY(pid != self_pid)) {
-                // we're called from a different process, do the real check
-                if (!checkCallingPermission(
-                        String16("android.permission.ACCESS_SURFACE_FLINGER")))
-                {
-                    const int uid = ipc->getCallingUid();
-                    LOGE("Permission Denial: "
-                            "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
-                    return PERMISSION_DENIED;
-                }
-            }
-        }
-    }
-    return LayerBaseClient::Surface::onTransact(code, data, reply, flags);
-}
-
-status_t LayerBuffer::SurfaceBuffer::registerBuffers(const ISurface::BufferHeap& buffers)
-{
-    LayerBuffer* owner(getOwner());
-    if (owner)
+    sp<LayerBuffer> owner(getOwner());
+    if (owner != 0)
         return owner->registerBuffers(buffers);
     return NO_INIT;
 }
 
 void LayerBuffer::SurfaceBuffer::postBuffer(ssize_t offset)
 {
-    LayerBuffer* owner(getOwner());
-    if (owner)
+    sp<LayerBuffer> owner(getOwner());
+    if (owner != 0)
         owner->postBuffer(offset);
 }
 
 void LayerBuffer::SurfaceBuffer::unregisterBuffers()
 {
-    LayerBuffer* owner(getOwner());
-    if (owner)
+    sp<LayerBuffer> owner(getOwner());
+    if (owner != 0)
         owner->unregisterBuffers();
 }
 
 sp<OverlayRef> LayerBuffer::SurfaceBuffer::createOverlay(
         uint32_t w, uint32_t h, int32_t format) {
     sp<OverlayRef> result;
-    LayerBuffer* owner(getOwner());
-    if (owner)
+    sp<LayerBuffer> owner(getOwner());
+    if (owner != 0)
         result = owner->createOverlay(w, h, format);
     return result;
 }
 
-void LayerBuffer::SurfaceBuffer::disown()
-{
-    Mutex::Autolock _l(mLock);
-    mOwner = 0;
-}
-
 // ============================================================================
 // LayerBuffer::Buffer
 // ============================================================================
@@ -276,20 +234,30 @@
     : mBufferHeap(buffers)
 {
     NativeBuffer& src(mNativeBuffer);
+    
     src.crop.l = 0;
     src.crop.t = 0;
     src.crop.r = buffers.w;
     src.crop.b = buffers.h;
-    src.img.w = buffers.hor_stride ?: buffers.w;
-    src.img.h = buffers.ver_stride ?: buffers.h;
-    src.img.format = buffers.format;
-    src.img.offset = offset;
-    src.img.base   = buffers.heap->base();
-    src.img.fd     = buffers.heap->heapID();
+    
+    src.img.w       = buffers.hor_stride ?: buffers.w;
+    src.img.h       = buffers.ver_stride ?: buffers.h;
+    src.img.format  = buffers.format;
+    src.img.base    = (void*)(intptr_t(buffers.heap->base()) + offset);
+
+    // FIXME: gross hack, we should never access private_handle_t from here,
+    // but this is needed by msm drivers
+    private_handle_t* hnd = new private_handle_t(
+            buffers.heap->heapID(), buffers.heap->getSize(), 0);
+    hnd->offset = offset;
+    src.img.handle = hnd;
 }
 
 LayerBuffer::Buffer::~Buffer()
 {
+    NativeBuffer& src(mNativeBuffer);
+    if (src.img.handle)
+        delete (private_handle_t*)src.img.handle;
 }
 
 // ============================================================================
@@ -323,8 +291,7 @@
 
 LayerBuffer::BufferSource::BufferSource(LayerBuffer& layer,
         const ISurface::BufferHeap& buffers)
-    : Source(layer), mStatus(NO_ERROR), 
-      mBufferSize(0), mTextureName(-1U)
+    : Source(layer), mStatus(NO_ERROR), mBufferSize(0)
 {
     if (buffers.heap == NULL) {
         // this is allowed, but in this case, it is illegal to receive
@@ -363,13 +330,21 @@
     mLayer.setNeedsBlending((info.h_alpha - info.l_alpha) > 0);    
     mBufferSize = info.getScanlineSize(buffers.hor_stride)*buffers.ver_stride;
     mLayer.forceVisibilityTransaction();
-    
+
+    hw_module_t const* module;
+    mBlitEngine = NULL;
+    if (hw_get_module(COPYBIT_HARDWARE_MODULE_ID, &module) == 0) {
+        copybit_open(module, &mBlitEngine);
+    }
 }
 
 LayerBuffer::BufferSource::~BufferSource()
 {    
-    if (mTextureName != -1U) {
-        LayerBase::deletedTextures.add(mTextureName);
+    if (mTexture.name != -1U) {
+        glDeleteTextures(1, &mTexture.name);
+    }
+    if (mBlitEngine) {
+        copybit_close(mBlitEngine);
     }
 }
 
@@ -427,19 +402,19 @@
 
 void LayerBuffer::BufferSource::onDraw(const Region& clip) const 
 {
-    sp<Buffer> buffer(getBuffer());
-    if (UNLIKELY(buffer == 0))  {
+    sp<Buffer> ourBuffer(getBuffer());
+    if (UNLIKELY(ourBuffer == 0))  {
         // nothing to do, we don't have a buffer
         mLayer.clearWithOpenGL(clip);
         return;
     }
 
     status_t err = NO_ERROR;
-    NativeBuffer src(buffer->getBuffer());
+    NativeBuffer src(ourBuffer->getBuffer());
     const Rect& transformedBounds = mLayer.getTransformedBounds();
-    const int can_use_copybit = mLayer.canUseCopybit();
+    copybit_device_t* copybit = mBlitEngine;
 
-    if (can_use_copybit)  {
+    if (copybit)  {
         const int src_width  = src.crop.r - src.crop.l;
         const int src_height = src.crop.b - src.crop.t;
         int W = transformedBounds.width();
@@ -448,89 +423,108 @@
             int t(W); W=H; H=t;
         }
 
-        /* With LayerBuffer, it is likely that we'll have to rescale the
-         * surface, because this is often used for video playback or
-         * camera-preview. Since we want these operation as fast as possible
-         * we make sure we can use the 2D H/W even if it doesn't support
-         * the requested scale factor, in which case we perform the scaling
-         * in several passes. */
+#ifdef EGL_ANDROID_get_render_buffer
+        EGLDisplay dpy = eglGetCurrentDisplay();
+        EGLSurface draw = eglGetCurrentSurface(EGL_DRAW); 
+        EGLClientBuffer clientBuf = eglGetRenderBufferANDROID(dpy, draw);
+        android_native_buffer_t* nb = (android_native_buffer_t*)clientBuf;
+        if (nb == 0) {
+            err = BAD_VALUE;
+        } else {
+            copybit_image_t dst;
+            dst.w       = nb->width;
+            dst.h       = nb->height;
+            dst.format  = nb->format;
+            dst.base    = NULL; // unused by copybit on msm7k
+            dst.handle  = (native_handle_t *)nb->handle;
 
-        copybit_device_t* copybit = mLayer.mFlinger->getBlitEngine();
-        const float min = copybit->get(copybit, COPYBIT_MINIFICATION_LIMIT);
-        const float mag = copybit->get(copybit, COPYBIT_MAGNIFICATION_LIMIT);
+            /* With LayerBuffer, it is likely that we'll have to rescale the
+             * surface, because this is often used for video playback or
+             * camera-preview. Since we want these operation as fast as possible
+             * we make sure we can use the 2D H/W even if it doesn't support
+             * the requested scale factor, in which case we perform the scaling
+             * in several passes. */
 
-        float xscale = 1.0f;
-        if (src_width > W*min)          xscale = 1.0f / min;
-        else if (src_width*mag < W)     xscale = mag;
+            const float min = copybit->get(copybit, COPYBIT_MINIFICATION_LIMIT);
+            const float mag = copybit->get(copybit, COPYBIT_MAGNIFICATION_LIMIT);
 
-        float yscale = 1.0f;
-        if (src_height > H*min)         yscale = 1.0f / min;
-        else if (src_height*mag < H)    yscale = mag;
+            float xscale = 1.0f;
+            if (src_width > W*min)          xscale = 1.0f / min;
+            else if (src_width*mag < W)     xscale = mag;
 
-        if (UNLIKELY(xscale!=1.0f || yscale!=1.0f)) {
-            if (UNLIKELY(mTemporaryDealer == 0)) {
-                // allocate a memory-dealer for this the first time
-                mTemporaryDealer = mLayer.mFlinger->getSurfaceHeapManager()
-                    ->createHeap(ISurfaceComposer::eHardware);
-                mTempBitmap.init(mTemporaryDealer);
+            float yscale = 1.0f;
+            if (src_height > H*min)         yscale = 1.0f / min;
+            else if (src_height*mag < H)    yscale = mag;
+
+            if (UNLIKELY(xscale!=1.0f || yscale!=1.0f)) {
+                const int tmp_w = floorf(src_width  * xscale);
+                const int tmp_h = floorf(src_height * yscale);
+                
+                if (mTempBitmap==0 || 
+                        mTempBitmap->getWidth() < tmp_w || 
+                        mTempBitmap->getHeight() < tmp_h) {
+                    mTempBitmap.clear();
+                    mTempBitmap = new android::Buffer(tmp_w, tmp_h, src.img.format);
+                    err = mTempBitmap->initCheck();
+                }
+
+                if (LIKELY(err == NO_ERROR)) {
+                    NativeBuffer tmp;
+                    tmp.img.w = tmp_w;
+                    tmp.img.h = tmp_h;
+                    tmp.img.format = src.img.format;
+                    tmp.img.handle = (native_handle_t*)mTempBitmap->getNativeBuffer()->handle;
+                    tmp.crop.l = 0;
+                    tmp.crop.t = 0;
+                    tmp.crop.r = tmp.img.w;
+                    tmp.crop.b = tmp.img.h;
+
+                    region_iterator tmp_it(Region(Rect(tmp.crop.r, tmp.crop.b)));
+                    copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0);
+                    copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 0xFF);
+                    copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_DISABLE);
+                    err = copybit->stretch(copybit,
+                            &tmp.img, &src.img, &tmp.crop, &src.crop, &tmp_it);
+                    src = tmp;
+                }
             }
 
-            const int tmp_w = floorf(src_width  * xscale);
-            const int tmp_h = floorf(src_height * yscale);
-            err = mTempBitmap.setBits(tmp_w, tmp_h, 1, src.img.format);
+            const Rect& transformedBounds = mLayer.getTransformedBounds();
+            const copybit_rect_t& drect =
+                reinterpret_cast<const copybit_rect_t&>(transformedBounds);
+            const State& s(mLayer.drawingState());
+            region_iterator it(clip);
 
-            if (LIKELY(err == NO_ERROR)) {
-                NativeBuffer tmp;
-                mTempBitmap.getBitmapSurface(&tmp.img);
-                tmp.crop.l = 0;
-                tmp.crop.t = 0;
-                tmp.crop.r = tmp.img.w;
-                tmp.crop.b = tmp.img.h;
-
-                region_iterator tmp_it(Region(Rect(tmp.crop.r, tmp.crop.b)));
-                copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0);
-                copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 0xFF);
-                copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_DISABLE);
-                err = copybit->stretch(copybit,
-                        &tmp.img, &src.img, &tmp.crop, &src.crop, &tmp_it);
-                src = tmp;
+            // pick the right orientation for this buffer
+            int orientation = mLayer.getOrientation();
+            if (UNLIKELY(mBufferHeap.transform)) {
+                Transform rot90;
+                GraphicPlane::orientationToTransfrom(
+                        ISurfaceComposer::eOrientation90, 0, 0, &rot90);
+                const Transform& planeTransform(mLayer.graphicPlane(0).transform());
+                const Layer::State& s(mLayer.drawingState());
+                Transform tr(planeTransform * s.transform * rot90);
+                orientation = tr.getOrientation();
             }
-        }
 
-        const DisplayHardware& hw(mLayer.graphicPlane(0).displayHardware());
-        copybit_image_t dst;
-        hw.getDisplaySurface(&dst);
-        const copybit_rect_t& drect
-            = reinterpret_cast<const copybit_rect_t&>(transformedBounds);
-        const State& s(mLayer.drawingState());
-        region_iterator it(clip);
-        
-        // pick the right orientation for this buffer
-        int orientation = mLayer.getOrientation();
-        if (UNLIKELY(mBufferHeap.transform)) {
-            Transform rot90;
-            GraphicPlane::orientationToTransfrom(
-                    ISurfaceComposer::eOrientation90, 0, 0, &rot90);
-            const Transform& planeTransform(mLayer.graphicPlane(0).transform());
-            const Layer::State& s(mLayer.drawingState());
-            Transform tr(planeTransform * s.transform * rot90);
-            orientation = tr.getOrientation();
-        }
-        
-        copybit->set_parameter(copybit, COPYBIT_TRANSFORM, orientation);
-        copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, s.alpha);
-        copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_ENABLE);
+            copybit->set_parameter(copybit, COPYBIT_TRANSFORM, orientation);
+            copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, s.alpha);
+            copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_ENABLE);
 
-        err = copybit->stretch(copybit,
-                &dst, &src.img, &drect, &src.crop, &it);
-        if (err != NO_ERROR) {
-            LOGE("copybit failed (%s)", strerror(err));
+            err = copybit->stretch(copybit,
+                    &dst, &src.img, &drect, &src.crop, &it);
+            if (err != NO_ERROR) {
+                LOGE("copybit failed (%s)", strerror(err));
+            }
         }
     }
-
-    if (!can_use_copybit || err) {
-        if (UNLIKELY(mTextureName == -1LU)) {
-            mTextureName = mLayer.createTexture();
+#endif
+    
+    if (!copybit || err) 
+    {
+        // OpenGL fall-back
+        if (UNLIKELY(mTexture.name == -1LU)) {
+            mTexture.name = mLayer.createTexture();
         }
         GLuint w = 0;
         GLuint h = 0;
@@ -541,10 +535,11 @@
         t.stride = src.img.w;
         t.vstride= src.img.h;
         t.format = src.img.format;
-        t.data = (GGLubyte*)(intptr_t(src.img.base) + src.img.offset);
+        t.data = (GGLubyte*)src.img.base;
         const Region dirty(Rect(t.width, t.height));
-        mLayer.loadTexture(dirty, mTextureName, t, w, h);
-        mLayer.drawWithOpenGL(clip, mTextureName, t, mBufferHeap.transform);
+        mLayer.loadTexture(&mTexture, mTexture.name, dirty, t);
+        mTexture.transform = mBufferHeap.transform;
+        mLayer.drawWithOpenGL(clip, mTexture);
     }
 }
 
@@ -580,6 +575,7 @@
     mFormat = overlay->format; 
     mWidthStride = overlay->w_stride;
     mHeightStride = overlay->h_stride;
+    mInitialized = false;
 
     mOverlayHandle = overlay->getHandleRef(overlay);
     
@@ -599,6 +595,11 @@
     }
 }
 
+void LayerBuffer::OverlaySource::onDraw(const Region& clip) const
+{
+    mLayer.clearWithOpenGL(clip);
+}
+
 void LayerBuffer::OverlaySource::onTransaction(uint32_t flags)
 {
     const Layer::State& front(mLayer.drawingState());
@@ -614,8 +615,9 @@
     // this code-path must be as tight as possible, it's called each time
     // the screen is composited.
     if (UNLIKELY(mOverlay != 0)) {
-        if (mVisibilityChanged) {
+        if (mVisibilityChanged || !mInitialized) {
             mVisibilityChanged = false;
+            mInitialized = true;
             const Rect& bounds = mLayer.getTransformedBounds();
             int x = bounds.left;
             int y = bounds.top;
@@ -627,8 +629,9 @@
             if (mOverlay) {
                 overlay_control_device_t* overlay_dev = mOverlayDevice;
                 overlay_dev->setPosition(overlay_dev, mOverlay, x,y,w,h);
-                overlay_dev->setParameter(overlay_dev, mOverlay, 
+                overlay_dev->setParameter(overlay_dev, mOverlay,
                         OVERLAY_TRANSFORM, mLayer.getOrientation());
+                overlay_dev->commit(overlay_dev, mOverlay);
             }
         }
     }
diff --git a/libs/surfaceflinger/LayerBuffer.h b/libs/surfaceflinger/LayerBuffer.h
index 2dc77f1..8057219 100644
--- a/libs/surfaceflinger/LayerBuffer.h
+++ b/libs/surfaceflinger/LayerBuffer.h
@@ -20,18 +20,18 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 #include <private/ui/LayerState.h>
-#include <EGL/eglnatives.h>
 
 #include "LayerBase.h"
 #include "LayerBitmap.h"
 
+struct copybit_device_t;
+
 namespace android {
 
 // ---------------------------------------------------------------------------
 
-class MemoryDealer;
 class Region;
 class OverlayRef;
 
@@ -51,7 +51,6 @@
         LayerBuffer& mLayer;
     };
 
-
 public:
     static const uint32_t typeInfo;
     static const char* const typeID;
@@ -59,12 +58,14 @@
     virtual uint32_t getTypeInfo() const { return typeInfo; }
 
             LayerBuffer(SurfaceFlinger* flinger, DisplayID display,
-                        Client* client, int32_t i);
+                    const sp<Client>& client, int32_t i);
         virtual ~LayerBuffer();
 
+    virtual void onFirstRef();
     virtual bool needsBlending() const;
 
-    virtual sp<LayerBaseClient::Surface> getSurface() const;
+    virtual sp<LayerBaseClient::Surface> createSurface() const;
+    virtual status_t ditch();
     virtual void onDraw(const Region& clip) const;
     virtual uint32_t doTransaction(uint32_t flags);
     virtual void unlockPageFlip(const Transform& planeTransform, Region& outDirtyRegion);
@@ -121,14 +122,14 @@
         virtual void unregisterBuffers();
         virtual bool transformed() const;
     private:
-        mutable Mutex   mLock;
-        sp<Buffer>      mBuffer;
-        status_t        mStatus;
-        ISurface::BufferHeap mBufferHeap;
-        size_t          mBufferSize;
-        mutable sp<MemoryDealer> mTemporaryDealer;
-        mutable LayerBitmap mTempBitmap;
-        mutable GLuint  mTextureName;
+        mutable Mutex                   mLock;
+        sp<Buffer>                      mBuffer;
+        status_t                        mStatus;
+        ISurface::BufferHeap            mBufferHeap;
+        size_t                          mBufferSize;
+        mutable sp<android::Buffer>     mTempBitmap;
+        mutable LayerBase::Texture      mTexture;
+        copybit_device_t*               mBlitEngine;
     };
     
     class OverlaySource : public Source {
@@ -137,6 +138,7 @@
                 sp<OverlayRef>* overlayRef, 
                 uint32_t w, uint32_t h, int32_t format);
         virtual ~OverlaySource();
+        virtual void onDraw(const Region& clip) const;
         virtual void onTransaction(uint32_t flags);
         virtual void onVisibilityResolved(const Transform& planeTransform);
     private:
@@ -173,40 +175,34 @@
         int32_t mWidthStride;
         int32_t mHeightStride;
         mutable Mutex mLock;
+        bool mInitialized;
     };
 
 
     class SurfaceBuffer : public LayerBaseClient::Surface
     {
     public:
-                SurfaceBuffer(SurfaceID id, LayerBuffer* owner);
+                SurfaceBuffer(const sp<SurfaceFlinger>& flinger,
+                        SurfaceID id, const sp<LayerBuffer>& owner);
         virtual ~SurfaceBuffer();
-        virtual status_t onTransact(
-            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
+
         virtual status_t registerBuffers(const ISurface::BufferHeap& buffers);
         virtual void postBuffer(ssize_t offset);
         virtual void unregisterBuffers();
+        
         virtual sp<OverlayRef> createOverlay(
                 uint32_t w, uint32_t h, int32_t format);
-       void disown();
     private:
-        LayerBuffer* getOwner() const {
-            Mutex::Autolock _l(mLock);
-            return mOwner;
+        sp<LayerBuffer> getOwner() const {
+            return static_cast<LayerBuffer*>(Surface::getOwner().get());
         }
-        mutable Mutex   mLock;
-        LayerBuffer*    mOwner;
     };
-
-    friend class SurfaceFlinger;
-    sp<SurfaceBuffer>   getClientSurface() const;
-
+    
     mutable Mutex   mLock;
     sp<Source>      mSource;
-
+    sp<Surface>     mSurface;
     bool            mInvalidate;
     bool            mNeedsBlending;
-    mutable wp<SurfaceBuffer> mClientSurface;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/libs/surfaceflinger/LayerDim.cpp b/libs/surfaceflinger/LayerDim.cpp
index 0c347cc..8e9df9c 100644
--- a/libs/surfaceflinger/LayerDim.cpp
+++ b/libs/surfaceflinger/LayerDim.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <stdlib.h>
 #include <stdint.h>
 #include <sys/types.h>
@@ -25,7 +23,6 @@
 
 #include "LayerDim.h"
 #include "SurfaceFlinger.h"
-#include "VRamHeap.h"
 #include "DisplayHardware/DisplayHardware.h"
 
 namespace android {
@@ -33,27 +30,74 @@
 
 const uint32_t LayerDim::typeInfo = LayerBaseClient::typeInfo | 0x10;
 const char* const LayerDim::typeID = "LayerDim";
-sp<MemoryDealer> LayerDim::mDimmerDealer;
-LayerBitmap LayerDim::mDimmerBitmap;
+
+bool LayerDim::sUseTexture;
+GLuint LayerDim::sTexId;
+EGLImageKHR LayerDim::sImage;
+int32_t LayerDim::sWidth;
+int32_t LayerDim::sHeight;
 
 // ---------------------------------------------------------------------------
 
 LayerDim::LayerDim(SurfaceFlinger* flinger, DisplayID display,
-        Client* client, int32_t i)
-     : LayerBaseClient(flinger, display, client, i)
+        const sp<Client>& client, int32_t i)
+    : LayerBaseClient(flinger, display, client, i)
 {
 }
 
 void LayerDim::initDimmer(SurfaceFlinger* flinger, uint32_t w, uint32_t h)
 {
-    // must only be called once.
-    mDimmerDealer = flinger->getSurfaceHeapManager()
-            ->createHeap(ISurfaceComposer::eHardware);
-    if (mDimmerDealer != 0) {
-        mDimmerBitmap.init(mDimmerDealer);
-        mDimmerBitmap.setBits(w, h, 1, PIXEL_FORMAT_RGB_565);
-        mDimmerBitmap.clear();
+    sTexId = -1;
+    sImage = EGL_NO_IMAGE_KHR;
+    sWidth = w;
+    sHeight = h;
+    sUseTexture = false;
+    
+#ifdef DIM_WITH_TEXTURE
+    
+#warning "using a texture to implement LayerDim"
+    
+    /* On some h/w like msm7K, it is faster to use a texture because the
+     * software renderer will defer to copybit, for this to work we need to
+     * use an EGLImage texture so copybit can actually make use of it.
+     * This burns a full-screen worth of graphic memory.
+     */
+
+    const DisplayHardware& hw(flinger->graphicPlane(0).displayHardware());
+    uint32_t flags = hw.getFlags();
+
+    if (LIKELY(flags & DisplayHardware::DIRECT_TEXTURE)) {
+        // TODO: api to pass the usage flags
+        sp<Buffer> buffer = new Buffer(w, h, PIXEL_FORMAT_RGB_565);
+        android_native_buffer_t* clientBuf = buffer->getNativeBuffer();
+
+        glGenTextures(1, &sTexId);
+        glBindTexture(GL_TEXTURE_2D, sTexId);
+
+        EGLDisplay dpy = eglGetCurrentDisplay();
+        sImage = eglCreateImageKHR(dpy, EGL_NO_CONTEXT, 
+                EGL_NATIVE_BUFFER_ANDROID, (EGLClientBuffer)clientBuf, 0);
+        if (sImage == EGL_NO_IMAGE_KHR) {
+            LOGE("eglCreateImageKHR() failed. err=0x%4x", eglGetError());
+            return;
+        }
+
+        glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (GLeglImageOES)sImage);
+        GLint error = glGetError();
+        if (error != GL_NO_ERROR) {
+            eglDestroyImageKHR(dpy, sImage);
+            LOGE("glEGLImageTargetTexture2DOES() failed. err=0x%4x", error);
+            return;
+        }
+
+        // initialize the texture with zeros
+        GGLSurface t;
+        buffer->lock(&t, GRALLOC_USAGE_SW_READ_NEVER | GRALLOC_USAGE_SW_WRITE_OFTEN);
+        memset(t.data, 0, t.stride * t.height * 2);
+        buffer->unlock();
+        sUseTexture = true;
     }
+#endif
 }
 
 LayerDim::~LayerDim()
@@ -63,49 +107,56 @@
 void LayerDim::onDraw(const Region& clip) const
 {
     const State& s(drawingState());
-
-    Region::iterator iterator(clip);
-    if (s.alpha>0 && iterator) {
+    Region::const_iterator it = clip.begin();
+    Region::const_iterator const end = clip.end();
+    if (s.alpha>0 && (it != end)) {
         const DisplayHardware& hw(graphicPlane(0).displayHardware());
-
-        status_t err = NO_ERROR;
-        const int can_use_copybit = canUseCopybit();
-        if (can_use_copybit)  {
-            // StopWatch watch("copybit");
-            copybit_image_t dst;
-            hw.getDisplaySurface(&dst);
-            const copybit_rect_t& drect
-                = reinterpret_cast<const copybit_rect_t&>(mTransformedBounds);
-
-            copybit_image_t src;
-            mDimmerBitmap.getBitmapSurface(&src);
-            const copybit_rect_t& srect(drect);
-
-            copybit_device_t* copybit = mFlinger->getBlitEngine();
-            copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0);
-            copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, s.alpha);
-            copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_ENABLE);
-            region_iterator it(clip);
-            err = copybit->stretch(copybit, &dst, &src, &drect, &srect, &it);
+        const GGLfixed alpha = (s.alpha << 16)/255;
+        const uint32_t fbHeight = hw.getHeight();
+        glDisable(GL_DITHER);
+        glEnable(GL_BLEND);
+        glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+        glColor4x(0, 0, 0, alpha);
+        
+#ifdef DIM_WITH_TEXTURE
+        if (sUseTexture) {
+            glBindTexture(GL_TEXTURE_2D, sTexId);
+            glEnable(GL_TEXTURE_2D);
+            glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+            const GLshort texCoords[4][2] = {
+                    { 0,  0 },
+                    { 0,  1 },
+                    { 1,  1 },
+                    { 1,  0 }
+            };
+            glMatrixMode(GL_TEXTURE);
+            glLoadIdentity();
+            glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+            glTexCoordPointer(2, GL_SHORT, 0, texCoords);
+        } else
+#endif
+        {
+            glDisable(GL_TEXTURE_2D);
         }
 
-        if (!can_use_copybit || err) {
-            const GGLfixed alpha = (s.alpha << 16)/255;
-            const uint32_t fbHeight = hw.getHeight();
-            glDisable(GL_TEXTURE_2D);
-            glDisable(GL_DITHER);
-            glEnable(GL_BLEND);
-            glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
-            glColor4x(0, 0, 0, alpha);
-            glVertexPointer(2, GL_FIXED, 0, mVertices);
-            Rect r;
-            while (iterator.iterate(&r)) {
-                const GLint sy = fbHeight - (r.top + r.height());
-                glScissor(r.left, sy, r.width(), r.height());
-                glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 
-            }
+        GLshort w = sWidth;
+        GLshort h = sHeight;
+        const GLshort vertices[4][2] = {
+                { 0, 0 },
+                { 0, h },
+                { w, h },
+                { w, 0 }
+        };
+        glVertexPointer(2, GL_SHORT, 0, vertices);
+
+        while (it != end) {
+            const Rect& r = *it++;
+            const GLint sy = fbHeight - (r.top + r.height());
+            glScissor(r.left, sy, r.width(), r.height());
+            glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 
         }
     }
+    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
 }
 
 // ---------------------------------------------------------------------------
diff --git a/libs/surfaceflinger/LayerDim.h b/libs/surfaceflinger/LayerDim.h
index 3e37a47..33bd49d 100644
--- a/libs/surfaceflinger/LayerDim.h
+++ b/libs/surfaceflinger/LayerDim.h
@@ -20,6 +20,9 @@
 #include <stdint.h>
 #include <sys/types.h>
 
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+
 #include "LayerBase.h"
 #include "LayerBitmap.h"
 
@@ -29,6 +32,11 @@
 
 class LayerDim : public LayerBaseClient
 {
+    static bool sUseTexture;
+    static GLuint sTexId;
+    static EGLImageKHR sImage;
+    static int32_t sWidth;
+    static int32_t sHeight;
 public:    
     static const uint32_t typeInfo;
     static const char* const typeID;
@@ -36,7 +44,7 @@
     virtual uint32_t getTypeInfo() const { return typeInfo; }
     
                 LayerDim(SurfaceFlinger* flinger, DisplayID display,
-                        Client* client, int32_t i);
+                        const sp<Client>& client, int32_t i);
         virtual ~LayerDim();
 
     virtual void onDraw(const Region& clip) const;
@@ -44,10 +52,6 @@
     virtual bool isSecure() const       { return false; }
 
     static void initDimmer(SurfaceFlinger* flinger, uint32_t w, uint32_t h);
-
-private:
-    static sp<MemoryDealer> mDimmerDealer;
-    static LayerBitmap mDimmerBitmap;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/libs/surfaceflinger/LayerOrientationAnim.cpp b/libs/surfaceflinger/LayerOrientationAnim.cpp
deleted file mode 100644
index 79e5328..0000000
--- a/libs/surfaceflinger/LayerOrientationAnim.cpp
+++ /dev/null
@@ -1,206 +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.
- */
-
-#define LOG_TAG "SurfaceFlinger"
-
-#include <stdlib.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Errors.h>
-#include <utils/Log.h>
-#include <utils/StopWatch.h>
-
-#include <core/SkBitmap.h>
-
-#include <ui/EGLDisplaySurface.h>
-
-#include "BlurFilter.h"
-#include "LayerBase.h"
-#include "LayerOrientationAnim.h"
-#include "SurfaceFlinger.h"
-#include "DisplayHardware/DisplayHardware.h"
-#include "OrientationAnimation.h"
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-const uint32_t LayerOrientationAnim::typeInfo = LayerBase::typeInfo | 0x80;
-const char* const LayerOrientationAnim::typeID = "LayerOrientationAnim";
-
-// ---------------------------------------------------------------------------
-
-// Animation...
-const float DURATION = ms2ns(200);
-const float BOUNCES_PER_SECOND = 0.5f;
-const float DIM_TARGET = 0.40f;
-#define INTERPOLATED_TIME(_t)   (_t)
-
-// ---------------------------------------------------------------------------
-
-LayerOrientationAnim::LayerOrientationAnim(
-        SurfaceFlinger* flinger, DisplayID display, 
-        OrientationAnimation* anim, 
-        const LayerBitmap& bitmapIn,
-        const LayerBitmap& bitmapOut)
-    : LayerOrientationAnimBase(flinger, display), mAnim(anim), 
-      mBitmapIn(bitmapIn), mBitmapOut(bitmapOut), 
-      mTextureName(-1), mTextureNameIn(-1)
-{
-    // blur that texture. 
-    mOrientationCompleted = false;
-    mNeedsBlending = false;
-}
-
-LayerOrientationAnim::~LayerOrientationAnim()
-{
-    if (mTextureName != -1U) {
-        LayerBase::deletedTextures.add(mTextureName);
-    }
-    if (mTextureNameIn != -1U) {
-        LayerBase::deletedTextures.add(mTextureNameIn);
-    }
-}
-
-bool LayerOrientationAnim::needsBlending() const 
-{
-    return mNeedsBlending; 
-}
-
-Point LayerOrientationAnim::getPhysicalSize() const
-{
-    const GraphicPlane& plane(graphicPlane(0));
-    const DisplayHardware& hw(plane.displayHardware());
-    return Point(hw.getWidth(), hw.getHeight());
-}
-
-void LayerOrientationAnim::validateVisibility(const Transform&)
-{
-    const Layer::State& s(drawingState());
-    const Transform tr(s.transform);
-    const Point size(getPhysicalSize());
-    uint32_t w = size.x;
-    uint32_t h = size.y;
-    mTransformedBounds = tr.makeBounds(w, h);
-    mLeft = tr.tx();
-    mTop  = tr.ty();
-    transparentRegionScreen.clear();
-    mTransformed = true;
-    mCanUseCopyBit = false;
-    copybit_device_t* copybit = mFlinger->getBlitEngine();
-    if (copybit) { 
-        mCanUseCopyBit = true;
-    }
-}
-
-void LayerOrientationAnim::onOrientationCompleted()
-{
-    mAnim->onAnimationFinished();
-}
-
-void LayerOrientationAnim::onDraw(const Region& clip) const
-{
-    float alphaIn =  DIM_TARGET;
-    
-    // clear screen
-    // TODO: with update on demand, we may be able 
-    // to not erase the screen at all during the animation 
-    if (!mOrientationCompleted) {
-        glDisable(GL_BLEND);
-        glDisable(GL_DITHER);
-        glDisable(GL_SCISSOR_TEST);
-        glClearColor(0,0,0,0);
-        glClear(GL_COLOR_BUFFER_BIT);
-    }
-    
-    copybit_image_t dst;
-    const GraphicPlane& plane(graphicPlane(0));
-    const DisplayHardware& hw(plane.displayHardware());
-    hw.getDisplaySurface(&dst);
-
-    copybit_image_t src;
-    mBitmapIn.getBitmapSurface(&src);
-
-    copybit_image_t srcOut;
-    mBitmapOut.getBitmapSurface(&srcOut);
-
-    const int w = dst.w; 
-    const int h = dst.h; 
-    const int xc = uint32_t(dst.w-w)/2;
-    const int yc = uint32_t(dst.h-h)/2;
-    const copybit_rect_t drect = { xc, yc, xc+w, yc+h }; 
-    const copybit_rect_t srect = { 0, 0, src.w, src.h };
-    const Region reg(Rect( drect.l, drect.t, drect.r, drect.b ));
-
-    int err = NO_ERROR;
-    const int can_use_copybit = canUseCopybit();
-    if (can_use_copybit)  {
-        copybit_device_t* copybit = mFlinger->getBlitEngine();
-        copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0);
-        copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_ENABLE);
-        
-        if (alphaIn > 0) {
-            region_iterator it(reg);
-            copybit->set_parameter(copybit, COPYBIT_BLUR, COPYBIT_ENABLE);
-            copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, int(alphaIn*255));
-            err = copybit->stretch(copybit, &dst, &src, &drect, &srect, &it);
-            copybit->set_parameter(copybit, COPYBIT_BLUR, COPYBIT_DISABLE);
-        }
-        LOGE_IF(err != NO_ERROR, "copybit failed (%s)", strerror(err));
-    }
-    if (!can_use_copybit || err) {   
-        GGLSurface t;
-        t.version = sizeof(GGLSurface);
-        t.width  = src.w;
-        t.height = src.h;
-        t.stride = src.w;
-        t.vstride= src.h;
-        t.format = src.format;
-        t.data = (GGLubyte*)(intptr_t(src.base) + src.offset);
-
-        Transform tr;
-        tr.set(xc, yc);
-        
-        // FIXME: we should not access mVertices and mDrawingState like that,
-        // but since we control the animation, we know it's going to work okay.
-        // eventually we'd need a more formal way of doing things like this.
-        LayerOrientationAnim& self(const_cast<LayerOrientationAnim&>(*this));
-        tr.transform(self.mVertices[0], 0, 0);
-        tr.transform(self.mVertices[1], 0, src.h);
-        tr.transform(self.mVertices[2], src.w, src.h);
-        tr.transform(self.mVertices[3], src.w, 0);
-        if (!(mFlags & DisplayHardware::SLOW_CONFIG)) {
-            // Too slow to do this in software
-            self.mDrawingState.flags |= ISurfaceComposer::eLayerFilter;
-        }
-
-        if (alphaIn > 0.0f) {
-            t.data = (GGLubyte*)(intptr_t(src.base) + src.offset);
-            if (UNLIKELY(mTextureNameIn == -1LU)) {
-                mTextureNameIn = createTexture();
-                GLuint w=0, h=0;
-                const Region dirty(Rect(t.width, t.height));
-                loadTexture(dirty, mTextureNameIn, t, w, h);
-            }
-            self.mDrawingState.alpha = int(alphaIn*255);
-            drawWithOpenGL(reg, mTextureNameIn, t);
-        }
-    }
-}
-
-// ---------------------------------------------------------------------------
-
-}; // namespace android
diff --git a/libs/surfaceflinger/MessageQueue.cpp b/libs/surfaceflinger/MessageQueue.cpp
new file mode 100644
index 0000000..b43d801
--- /dev/null
+++ b/libs/surfaceflinger/MessageQueue.cpp
@@ -0,0 +1,192 @@
+/*
+ * 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.
+ */
+
+#include <stdint.h>
+#include <errno.h>
+#include <sys/types.h>
+
+#include <utils/threads.h>
+#include <utils/Timers.h>
+#include <utils/Log.h>
+#include <binder/IPCThreadState.h>
+
+#include "MessageQueue.h"
+
+namespace android {
+
+// ---------------------------------------------------------------------------
+
+void MessageList::insert(const sp<MessageBase>& node) 
+{
+    LIST::iterator cur(mList.begin());
+    LIST::iterator end(mList.end());
+    while (cur != end) {
+        if (*node < **cur) {
+            mList.insert(cur, node);
+            return;
+        }
+        ++cur;
+    }
+    mList.insert(++end, node);
+}
+
+void MessageList::remove(MessageList::LIST::iterator pos) 
+{
+    mList.erase(pos);
+}
+
+// ---------------------------------------------------------------------------
+
+MessageQueue::MessageQueue()
+    : mInvalidate(false)
+{
+    mInvalidateMessage = new MessageBase(INVALIDATE);
+}
+
+MessageQueue::~MessageQueue()
+{
+}
+
+MessageList::value_type MessageQueue::waitMessage(nsecs_t timeout)
+{
+    MessageList::value_type result;
+
+    bool again;
+    do {
+        const nsecs_t timeoutTime = systemTime() + timeout;
+        while (true) {
+            Mutex::Autolock _l(mLock);
+            nsecs_t now = systemTime();
+            nsecs_t nextEventTime = -1;
+
+            // invalidate messages are always handled first
+            if (mInvalidate) {
+                mInvalidate = false;
+                mInvalidateMessage->when = now;
+                result = mInvalidateMessage;
+                break;
+            }
+
+            LIST::iterator cur(mMessages.begin());
+            if (cur != mMessages.end()) {
+                result = *cur;
+            }
+            
+            if (result != 0) {
+                if (result->when <= now) {
+                    // there is a message to deliver
+                    mMessages.remove(cur);
+                    break;
+                }
+                if (timeout>=0 && timeoutTime < now) {
+                    // we timed-out, return a NULL message
+                    result = 0;
+                    break;
+                }
+                nextEventTime = result->when;
+                result = 0;
+            }
+
+            if (timeout >= 0 && nextEventTime > 0) {
+                if (nextEventTime > timeoutTime) {
+                    nextEventTime = timeoutTime;
+                }
+            }
+
+            if (nextEventTime >= 0) {
+                //LOGD("nextEventTime = %lld ms", nextEventTime);
+                if (nextEventTime > 0) {
+                    // we're about to wait, flush the binder command buffer
+                    IPCThreadState::self()->flushCommands();
+                    const nsecs_t reltime = nextEventTime - systemTime();
+                    if (reltime > 0) {
+                        mCondition.waitRelative(mLock, reltime);
+                    }
+                }
+            } else {
+                //LOGD("going to wait");
+                // we're about to wait, flush the binder command buffer
+                IPCThreadState::self()->flushCommands();
+                mCondition.wait(mLock);
+            }
+        } 
+        // here we're not holding the lock anymore
+
+        if (result == 0)
+            break;
+
+        again = result->handler();
+        if (again) {
+            // the message has been processed. release our reference to it
+            // without holding the lock.
+            result = 0;
+        }
+        
+    } while (again);
+
+    return result;
+}
+
+status_t MessageQueue::postMessage(
+        const MessageList::value_type& message, nsecs_t relTime, uint32_t flags)
+{
+    return queueMessage(message, relTime, flags);
+}
+
+status_t MessageQueue::invalidate() {
+    Mutex::Autolock _l(mLock);
+    mInvalidate = true;
+    mCondition.signal();
+    return NO_ERROR;
+}
+
+status_t MessageQueue::queueMessage(
+        const MessageList::value_type& message, nsecs_t relTime, uint32_t flags)
+{
+    Mutex::Autolock _l(mLock);
+    message->when = systemTime() + relTime;
+    mMessages.insert(message);
+    
+    //LOGD("MessageQueue::queueMessage time = %lld ms", message->when);
+    //dumpLocked(message);
+
+    mCondition.signal();
+    return NO_ERROR;
+}
+
+void MessageQueue::dump(const MessageList::value_type& message)
+{
+    Mutex::Autolock _l(mLock);
+    dumpLocked(message);
+}
+
+void MessageQueue::dumpLocked(const MessageList::value_type& message)
+{
+    LIST::const_iterator cur(mMessages.begin());
+    LIST::const_iterator end(mMessages.end());
+    int c = 0;
+    while (cur != end) {
+        const char tick = (*cur == message) ? '>' : ' ';
+        LOGD("%c %d: msg{.what=%08x, when=%lld}",
+                tick, c, (*cur)->what, (*cur)->when);
+        ++cur;
+        c++;
+    }
+}
+
+// ---------------------------------------------------------------------------
+
+}; // namespace android
diff --git a/libs/surfaceflinger/MessageQueue.h b/libs/surfaceflinger/MessageQueue.h
new file mode 100644
index 0000000..dc8138d
--- /dev/null
+++ b/libs/surfaceflinger/MessageQueue.h
@@ -0,0 +1,127 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_MESSAGE_QUEUE_H
+#define ANDROID_MESSAGE_QUEUE_H
+
+#include <stdint.h>
+#include <errno.h>
+#include <sys/types.h>
+
+#include <utils/threads.h>
+#include <utils/Timers.h>
+#include <utils/List.h>
+
+
+namespace android {
+
+// ---------------------------------------------------------------------------
+
+class MessageBase;
+
+class MessageList 
+{
+    List< sp<MessageBase> > mList;
+    typedef List< sp<MessageBase> > LIST;
+public:
+    typedef sp<MessageBase> value_type;
+    inline LIST::iterator begin()                { return mList.begin(); }
+    inline LIST::const_iterator begin() const    { return mList.begin(); }
+    inline LIST::iterator end()                  { return mList.end(); }
+    inline LIST::const_iterator end() const      { return mList.end(); }
+    inline bool isEmpty() const { return mList.empty(); }
+    void insert(const sp<MessageBase>& node);
+    void remove(LIST::iterator pos);
+};
+
+// ============================================================================
+
+class MessageBase : 
+    public LightRefBase<MessageBase>
+{
+public:
+    nsecs_t     when;
+    uint32_t    what;
+    int32_t     arg0;    
+
+    MessageBase() : when(0), what(0), arg0(0) { }
+    MessageBase(uint32_t what, int32_t arg0=0)
+        : when(0), what(what), arg0(arg0) { }
+    
+    // return true if message has a handler
+    virtual bool handler() { return false; }
+    
+protected:
+    virtual ~MessageBase() { }
+
+private:
+    friend class LightRefBase<MessageBase>;
+};
+
+inline bool operator < (const MessageBase& lhs, const MessageBase& rhs) {
+    return lhs.when < rhs.when;
+}
+
+// ---------------------------------------------------------------------------
+
+class MessageQueue
+{
+    typedef List< sp<MessageBase> > LIST;
+public:
+
+    // this is a work-around the multichar constant warning. A macro would
+    // work too, but would pollute the namespace.
+    template <int a, int b, int c, int d>
+    struct WHAT {
+        static const uint32_t Value = 
+            (uint32_t(a&0xff)<<24)|(uint32_t(b&0xff)<<16)|
+            (uint32_t(c&0xff)<<8)|uint32_t(d&0xff);
+    };
+    
+    MessageQueue();
+    ~MessageQueue();
+
+    // pre-defined messages
+    enum {
+        INVALIDATE = WHAT<'_','p','d','t'>::Value
+    };
+
+    MessageList::value_type waitMessage(nsecs_t timeout = -1);
+    
+    status_t postMessage(const MessageList::value_type& message, 
+            nsecs_t reltime=0, uint32_t flags = 0);
+        
+    status_t invalidate();
+    
+    void dump(const MessageList::value_type& message);
+
+private:
+    status_t queueMessage(const MessageList::value_type& message,
+            nsecs_t reltime, uint32_t flags);
+    void dumpLocked(const MessageList::value_type& message);
+    
+    Mutex           mLock;
+    Condition       mCondition;
+    MessageList     mMessages;
+    bool            mInvalidate;
+    MessageList::value_type mInvalidateMessage;
+};
+
+// ---------------------------------------------------------------------------
+
+}; // namespace android
+
+#endif /* ANDROID_MESSAGE_QUEUE_H */
diff --git a/libs/surfaceflinger/SurfaceFlinger.cpp b/libs/surfaceflinger/SurfaceFlinger.cpp
index fb25663..7a7574f 100644
--- a/libs/surfaceflinger/SurfaceFlinger.cpp
+++ b/libs/surfaceflinger/SurfaceFlinger.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <stdlib.h>
 #include <stdio.h>
 #include <stdint.h>
@@ -23,6 +21,7 @@
 #include <fcntl.h>
 #include <errno.h>
 #include <math.h>
+#include <limits.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <sys/ioctl.h>
@@ -30,36 +29,30 @@
 #include <cutils/log.h>
 #include <cutils/properties.h>
 
-#include <utils/IPCThreadState.h>
-#include <utils/IServiceManager.h>
-#include <utils/MemoryDealer.h>
-#include <utils/MemoryBase.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/MemoryHeapBase.h>
+
 #include <utils/String8.h>
 #include <utils/String16.h>
 #include <utils/StopWatch.h>
 
 #include <ui/PixelFormat.h>
 #include <ui/DisplayInfo.h>
-#include <ui/EGLDisplaySurface.h>
 
 #include <pixelflinger/pixelflinger.h>
 #include <GLES/gl.h>
 
 #include "clz.h"
-#include "CPUGauge.h"
+#include "BufferAllocator.h"
 #include "Layer.h"
 #include "LayerBlur.h"
 #include "LayerBuffer.h"
 #include "LayerDim.h"
 #include "LayerBitmap.h"
-#include "LayerOrientationAnim.h"
-#include "OrientationAnimation.h"
 #include "SurfaceFlinger.h"
-#include "VRamHeap.h"
 
 #include "DisplayHardware/DisplayHardware.h"
-#include "GPUHardware/GPUHardware.h"
-
 
 /* ideally AID_GRAPHICS would be in a semi-public header
  * or there would be a way to map a user/group name to its id
@@ -93,30 +86,30 @@
 }
 
 ssize_t SurfaceFlinger::LayerVector::indexOf(
-        LayerBase* key, size_t guess) const
+        const sp<LayerBase>& key, size_t guess) const
 {
     if (guess<size() && lookup.keyAt(guess) == key)
         return guess;
     const ssize_t i = lookup.indexOfKey(key);
     if (i>=0) {
         const size_t idx = lookup.valueAt(i);
-        LOG_ASSERT(layers[idx]==key,
+        LOGE_IF(layers[idx]!=key,
             "LayerVector[%p]: layers[%d]=%p, key=%p",
-            this, int(idx), layers[idx], key);
+            this, int(idx), layers[idx].get(), key.get());
         return idx;
     }
     return i;
 }
 
 ssize_t SurfaceFlinger::LayerVector::add(
-        LayerBase* layer,
-        Vector<LayerBase*>::compar_t cmp)
+        const sp<LayerBase>& layer,
+        Vector< sp<LayerBase> >::compar_t cmp)
 {
     size_t count = layers.size();
     ssize_t l = 0;
     ssize_t h = count-1;
     ssize_t mid;
-    LayerBase* const* a = layers.array();
+    sp<LayerBase> const* a = layers.array();
     while (l <= h) {
         mid = l + (h - l)/2;
         const int c = cmp(a+mid, &layer);
@@ -139,14 +132,14 @@
     return order;
 }
 
-ssize_t SurfaceFlinger::LayerVector::remove(LayerBase* layer)
+ssize_t SurfaceFlinger::LayerVector::remove(const sp<LayerBase>& layer)
 {
     const ssize_t keyIndex = lookup.indexOfKey(layer);
     if (keyIndex >= 0) {
         const size_t index = lookup.valueAt(keyIndex);
-        LOG_ASSERT(layers[index]==layer,
+        LOGE_IF(layers[index]!=layer,
                 "LayerVector[%p]: layers[%u]=%p, layer=%p",
-                this, int(index), layers[index], layer);
+                this, int(index), layers[index].get(), layer.get());
         layers.removeItemsAt(index);
         lookup.removeItemsAt(keyIndex);
         const size_t count = lookup.size();
@@ -161,8 +154,8 @@
 }
 
 ssize_t SurfaceFlinger::LayerVector::reorder(
-        LayerBase* layer,
-        Vector<LayerBase*>::compar_t cmp)
+        const sp<LayerBase>& layer,
+        Vector< sp<LayerBase> >::compar_t cmp)
 {
     // XXX: it's a little lame. but oh well...
     ssize_t err = remove(layer);
@@ -180,7 +173,11 @@
     :   BnSurfaceComposer(), Thread(false),
         mTransactionFlags(0),
         mTransactionCount(0),
+        mLayersRemoved(false),
         mBootTime(systemTime()),
+        mHardwareTest("android.permission.HARDWARE_TEST"),
+        mAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"),
+        mDump("android.permission.DUMP"),
         mLastScheduledBroadcast(NULL),
         mVisibleRegionsDirty(false),
         mDeferReleaseConsole(false),
@@ -188,11 +185,7 @@
         mFreezeCount(0),
         mFreezeDisplayTime(0),
         mDebugRegion(0),
-        mDebugCpu(0),
-        mDebugFps(0),
         mDebugBackground(0),
-        mSyncObject(),
-        mDeplayedTransactionPending(0),
         mConsoleSignals(0),
         mSecureFrameBuffer(0)
 {
@@ -207,28 +200,16 @@
     char value[PROPERTY_VALUE_MAX];
     property_get("debug.sf.showupdates", value, "0");
     mDebugRegion = atoi(value);
-    property_get("debug.sf.showcpu", value, "0");
-    mDebugCpu = atoi(value);
     property_get("debug.sf.showbackground", value, "0");
     mDebugBackground = atoi(value);
-    property_get("debug.sf.showfps", value, "0");
-    mDebugFps = atoi(value);
 
     LOGI_IF(mDebugRegion,           "showupdates enabled");
-    LOGI_IF(mDebugCpu,              "showcpu enabled");
     LOGI_IF(mDebugBackground,       "showbackground enabled");
-    LOGI_IF(mDebugFps,              "showfps enabled");
 }
 
 SurfaceFlinger::~SurfaceFlinger()
 {
     glDeleteTextures(1, &mWormholeTexName);
-    delete mOrientationAnimation;
-}
-
-copybit_device_t* SurfaceFlinger::getBlitEngine() const
-{
-    return graphicPlane(0).displayHardware().getBlitEngine();
 }
 
 overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
@@ -236,29 +217,9 @@
     return graphicPlane(0).displayHardware().getOverlayEngine();
 }
 
-sp<IMemory> SurfaceFlinger::getCblk() const
+sp<IMemoryHeap> SurfaceFlinger::getCblk() const
 {
-    return mServerCblkMemory;
-}
-
-status_t SurfaceFlinger::requestGPU(const sp<IGPUCallback>& callback,
-        gpu_info_t* gpu)
-{
-    if (mGPU == 0)
-        return INVALID_OPERATION;
-
-    IPCThreadState* ipc = IPCThreadState::self();
-    const int pid = ipc->getCallingPid();
-    status_t err = mGPU->request(pid, callback, gpu);
-    return err;
-}
-
-status_t SurfaceFlinger::revokeGPU()
-{
-    if (mGPU == 0)
-        return INVALID_OPERATION;
-
-    return mGPU->friendlyRevoke();
+    return mServerHeap;
 }
 
 sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
@@ -266,33 +227,34 @@
     Mutex::Autolock _l(mStateLock);
     uint32_t token = mTokens.acquire();
 
-    Client* client = new Client(token, this);
-    if ((client == 0) || (client->ctrlblk == 0)) {
+    sp<Client> client = new Client(token, this);
+    if (client->ctrlblk == 0) {
         mTokens.release(token);
         return 0;
     }
     status_t err = mClientsMap.add(token, client);
     if (err < 0) {
-        delete client;
         mTokens.release(token);
         return 0;
     }
     sp<BClient> bclient =
-        new BClient(this, token, client->controlBlockMemory());
+        new BClient(this, token, client->getControlBlockMemory());
     return bclient;
 }
 
 void SurfaceFlinger::destroyConnection(ClientID cid)
 {
     Mutex::Autolock _l(mStateLock);
-    Client* const client = mClientsMap.valueFor(cid);
-    if (client) {
+    sp<Client> client = mClientsMap.valueFor(cid);
+    if (client != 0) {
         // free all the layers this client owns
-        const Vector<LayerBaseClient*>& layers = client->getLayers();
+        Vector< wp<LayerBaseClient> > layers(client->getLayers());
         const size_t count = layers.size();
         for (size_t i=0 ; i<count ; i++) {
-            LayerBaseClient* const layer = layers[i];
-            removeLayer_l(layer);
+            sp<LayerBaseClient> layer(layers[i].promote());
+            if (layer != 0) {
+                purgatorizeLayer_l(layer);
+            }
         }
 
         // the resources associated with this client will be freed
@@ -339,41 +301,15 @@
     mReadyToRunBarrier.wait();
 }
 
-
 static inline uint16_t pack565(int r, int g, int b) {
     return (r<<11)|(g<<5)|b;
 }
 
-// this is defined in libGLES_CM.so
-extern ISurfaceComposer* GLES_localSurfaceManager;
-
 status_t SurfaceFlinger::readyToRun()
 {
     LOGI(   "SurfaceFlinger's main thread ready to run. "
             "Initializing graphics H/W...");
 
-    // create the shared control-block
-    mServerHeap = new MemoryDealer(4096, MemoryDealer::READ_ONLY);
-    LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
-
-    mServerCblkMemory = mServerHeap->allocate(4096);
-    LOGE_IF(mServerCblkMemory==0, "can't create shared control block");
-
-    mServerCblk = static_cast<surface_flinger_cblk_t *>(mServerCblkMemory->pointer());
-    LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
-    new(mServerCblk) surface_flinger_cblk_t;
-
-    // get a reference to the GPU if we have one
-    mGPU = GPUFactory::getGPU();
-
-    // create the surface Heap manager, which manages the heaps
-    // (be it in RAM or VRAM) where surfaces are allocated
-    // We give 8 MB per client.
-    mSurfaceHeapManager = new SurfaceHeapManager(this, 8 << 20);
-
-    
-    GLES_localSurfaceManager = static_cast<ISurfaceComposer*>(this);
-
     // we only support one display currently
     int dpy = 0;
 
@@ -384,6 +320,16 @@
         plane.setDisplayHardware(hw);
     }
 
+    // create the shared control-block
+    mServerHeap = new MemoryHeapBase(4096,
+            MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap");
+    LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
+    
+    mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase());
+    LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
+    
+    new(mServerCblk) surface_flinger_cblk_t;
+
     // initialize primary screen
     // (other display should be initialized in the same manner, but
     // asynchronously, as they could come and go. None of this is supported
@@ -450,13 +396,6 @@
      *  We're now ready to accept clients...
      */
 
-    mOrientationAnimation = new OrientationAnimation(this);
-    
-    // start CPU gauge display
-    if (mDebugCpu)
-        mCpuGauge = new CPUGauge(this, ms2ns(500));
-
-    
     // start boot animation
     property_set("ctl.start", "bootanim");
     
@@ -471,45 +410,53 @@
 
 void SurfaceFlinger::waitForEvent()
 {
-    // wait for something to do
-    if (UNLIKELY(isFrozen())) {
-        // wait 5 seconds
-        const nsecs_t freezeDisplayTimeout = ms2ns(5000);
-        const nsecs_t now = systemTime();
-        if (mFreezeDisplayTime == 0) {
-            mFreezeDisplayTime = now;
+    while (true) {
+        nsecs_t timeout = -1;
+        if (UNLIKELY(isFrozen())) {
+            // wait 5 seconds
+            const nsecs_t freezeDisplayTimeout = ms2ns(5000);
+            const nsecs_t now = systemTime();
+            if (mFreezeDisplayTime == 0) {
+                mFreezeDisplayTime = now;
+            }
+            nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
+            timeout = waitTime>0 ? waitTime : 0;
         }
-        nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
-        int err = (waitTime > 0) ? mSyncObject.wait(waitTime) : TIMED_OUT;
-        if (err != NO_ERROR) {
+
+        MessageList::value_type msg = mEventQueue.waitMessage(timeout);
+        if (msg != 0) {
+            mFreezeDisplayTime = 0;
+            switch (msg->what) {
+                case MessageQueue::INVALIDATE:
+                    // invalidate message, just return to the main loop
+                    return;
+            }
+        } else {
+            // we timed out
             if (isFrozen()) {
                 // we timed out and are still frozen
                 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
                         mFreezeDisplay, mFreezeCount);
                 mFreezeCount = 0;
                 mFreezeDisplay = false;
+                return;
             }
         }
-    } else {
-        mFreezeDisplayTime = 0;
-        mSyncObject.wait();
     }
 }
 
 void SurfaceFlinger::signalEvent() {
-    mSyncObject.open();
+    mEventQueue.invalidate();
 }
 
 void SurfaceFlinger::signal() const {
-    mSyncObject.open();
+    // this is the IPC call
+    const_cast<SurfaceFlinger*>(this)->signalEvent();
 }
 
 void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
 {
-    if (android_atomic_or(1, &mDeplayedTransactionPending) == 0) {
-        sp<DelayedTransaction> delayedEvent(new DelayedTransaction(this, delay));
-        delayedEvent->run("DelayedeEvent", PRIORITY_URGENT_DISPLAY);
-    }
+    mEventQueue.postMessage( new MessageBase(MessageQueue::INVALIDATE), delay);
 }
 
 // ----------------------------------------------------------------------------
@@ -548,11 +495,6 @@
         unlockClients();
         executeScheduledBroadcasts();
 
-        // sample the cpu gauge
-        if (UNLIKELY(mDebugCpu)) {
-            handleDebugCpu();
-        }
-
         postFramebuffer();
     } else {
         // pretend we did the post
@@ -565,28 +507,18 @@
 
 void SurfaceFlinger::postFramebuffer()
 {
-    const bool skip = mOrientationAnimation->run();
-    if (UNLIKELY(skip)) {
+    if (isFrozen()) {
+        // we are not allowed to draw, but pause a bit to make sure
+        // apps don't end up using the whole CPU, if they depend on
+        // surfaceflinger for synchronization.
+        usleep(8333); // 8.3ms ~ 120fps
         return;
     }
 
     if (!mInvalidRegion.isEmpty()) {
         const DisplayHardware& hw(graphicPlane(0).displayHardware());
-
-        if (UNLIKELY(mDebugFps)) {
-            debugShowFPS();
-        }
-
         hw.flip(mInvalidRegion);
-
         mInvalidRegion.clear();
-
-        if (Layer::deletedTextures.size()) {
-            glDeleteTextures(
-                    Layer::deletedTextures.size(),
-                    Layer::deletedTextures.array());
-            Layer::deletedTextures.clear();
-        }
     }
 }
 
@@ -601,15 +533,13 @@
     }
 
     if (mDeferReleaseConsole && hw.canDraw()) {
-        // We got the release signal before the aquire signal
+        // We got the release signal before the acquire signal
         mDeferReleaseConsole = false;
-        revokeGPU();
         hw.releaseScreen();
     }
 
     if (what & eConsoleReleased) {
         if (hw.canDraw()) {
-            revokeGPU();
             hw.releaseScreen();
         } else {
             mDeferReleaseConsole = true;
@@ -621,9 +551,25 @@
 
 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
 {
-    Mutex::Autolock _l(mStateLock);
+    Vector< sp<LayerBase> > ditchedLayers;
 
-    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
+    { // scope for the lock
+        Mutex::Autolock _l(mStateLock);
+        handleTransactionLocked(transactionFlags, ditchedLayers);
+    }
+
+    // do this without lock held
+    const size_t count = ditchedLayers.size();
+    for (size_t i=0 ; i<count ; i++) {
+        //LOGD("ditching layer %p", ditchedLayers[i].get());
+        ditchedLayers[i]->ditch();
+    }
+}
+
+void SurfaceFlinger::handleTransactionLocked(
+        uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers)
+{
+    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
     const size_t count = currentLayers.size();
 
     /*
@@ -634,7 +580,7 @@
     const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
     if (layersNeedTransaction) {
         for (size_t i=0 ; i<count ; i++) {
-            LayerBase* const layer = currentLayers[i];
+            const sp<LayerBase>& layer = currentLayers[i];
             uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
             if (!trFlags) continue;
 
@@ -681,7 +627,6 @@
             mVisibleRegionsDirty = true;
             mDirtyRegion.set(hw.bounds());
             mFreezeDisplayTime = 0;
-            mOrientationAnimation->onOrientationChanged(type);
         }
 
         if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
@@ -689,19 +634,26 @@
             mFreezeDisplay = mCurrentState.freezeDisplay;
         }
 
-        // some layers might have been removed, so
-        // we need to update the regions they're exposing.
-        size_t c = mRemovedLayers.size();
-        if (c) {
-            mVisibleRegionsDirty = true;
-        }
-
-        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
         if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
             // layers have been added
             mVisibleRegionsDirty = true;
         }
 
+        // some layers might have been removed, so
+        // we need to update the regions they're exposing.
+        if (mLayersRemoved) {
+            mVisibleRegionsDirty = true;
+            const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
+            const size_t count = previousLayers.size();
+            for (size_t i=0 ; i<count ; i++) {
+                const sp<LayerBase>& layer(previousLayers[i]);
+                if (currentLayers.indexOf( layer ) < 0) {
+                    // this layer is not visible anymore
+                    ditchedLayers.add(layer);
+                }
+            }
+        }
+
         // get rid of all resources we don't need anymore
         // (layers and clients)
         free_resources_l();
@@ -729,7 +681,7 @@
 
     size_t i = currentLayers.size();
     while (i--) {
-        LayerBase* const layer = currentLayers[i];
+        const sp<LayerBase>& layer = currentLayers[i];
         layer->validateVisibility(planeTransform);
 
         // start with the whole surface at its current location
@@ -782,7 +734,7 @@
         // accumulate to the screen dirty region
         dirtyRegion.orSelf(dirty);
 
-        // updade aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
+        // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
         aboveOpaqueLayers.orSelf(opaqueRegion);
         aboveCoveredLayers.orSelf(visibleRegion);
         
@@ -790,7 +742,7 @@
         layer->setVisibleRegion(visibleRegion);
         layer->setCoveredRegion(coveredRegion);
 
-        // If a secure layer is partially visible, lockdown the screen!
+        // If a secure layer is partially visible, lock down the screen!
         if (layer->isSecure() && !visibleRegion.isEmpty()) {
             secureFrameBuffer = true;
         }
@@ -830,9 +782,9 @@
 {
     bool recomputeVisibleRegions = false;
     size_t count = currentLayers.size();
-    LayerBase* const* layers = currentLayers.array();
+    sp<LayerBase> const* layers = currentLayers.array();
     for (size_t i=0 ; i<count ; i++) {
-        LayerBase* const layer = layers[i];
+        const sp<LayerBase>& layer = layers[i];
         layer->lockPageFlip(recomputeVisibleRegions);
     }
     return recomputeVisibleRegions;
@@ -843,37 +795,58 @@
     const GraphicPlane& plane(graphicPlane(0));
     const Transform& planeTransform(plane.transform());
     size_t count = currentLayers.size();
-    LayerBase* const* layers = currentLayers.array();
+    sp<LayerBase> const* layers = currentLayers.array();
     for (size_t i=0 ; i<count ; i++) {
-        LayerBase* const layer = layers[i];
+        const sp<LayerBase>& layer = layers[i];
         layer->unlockPageFlip(planeTransform, mDirtyRegion);
     }
 }
 
+
 void SurfaceFlinger::handleRepaint()
 {
-    // set the frame buffer
-    const DisplayHardware& hw(graphicPlane(0).displayHardware());
-    glMatrixMode(GL_MODELVIEW);
-    glLoadIdentity();
+    // compute the invalid region
+    mInvalidRegion.orSelf(mDirtyRegion);
+    if (mInvalidRegion.isEmpty()) {
+        // nothing to do
+        return;
+    }
 
     if (UNLIKELY(mDebugRegion)) {
         debugFlashRegions();
     }
 
-    // compute the invalid region
-    mInvalidRegion.orSelf(mDirtyRegion);
+    // set the frame buffer
+    const DisplayHardware& hw(graphicPlane(0).displayHardware());
+    glMatrixMode(GL_MODELVIEW);
+    glLoadIdentity();
 
     uint32_t flags = hw.getFlags();
-    if (flags & DisplayHardware::BUFFER_PRESERVED) {
-        // here we assume DisplayHardware::flip()'s  implementation
-        // performs the copy-back optimization.
-    } else {
-        if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
-            // we need to fully redraw the part that will be updated
+    if ((flags & DisplayHardware::SWAP_RECTANGLE) || 
+        (flags & DisplayHardware::BUFFER_PRESERVED)) 
+    {
+        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
+        // takes a rectangle, we must make sure to update that whole
+        // rectangle in that case
+        if (flags & DisplayHardware::SWAP_RECTANGLE) {
+            // FIXME: we really should be able to pass a region to
+            // SWAP_RECTANGLE so that we don't have to redraw all this.
             mDirtyRegion.set(mInvalidRegion.bounds());
         } else {
-            // we need to redraw everything
+            // in the BUFFER_PRESERVED case, obviously, we can update only
+            // what's needed and nothing more.
+            // NOTE: this is NOT a common case, as preserving the backbuffer
+            // is costly and usually involves copying the whole update back.
+        }
+    } else {
+        if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
+            // We need to redraw the rectangle that will be updated
+            // (pushed to the framebuffer).
+            // This is needed because UPDATE_ON_DEMAND only takes one
+            // rectangle instead of a region (see DisplayHardware::flip())
+            mDirtyRegion.set(mInvalidRegion.bounds());
+        } else {
+            // we need to redraw everything (the whole screen)
             mDirtyRegion.set(hw.bounds());
             mInvalidRegion = mDirtyRegion;
         }
@@ -896,9 +869,9 @@
     const SurfaceFlinger& flinger(*this);
     const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
     const size_t count = drawingLayers.size();
-    LayerBase const* const* const layers = drawingLayers.array();
+    sp<LayerBase> const* const layers = drawingLayers.array();
     for (size_t i=0 ; i<count ; ++i) {
-        LayerBase const * const layer = layers[i];
+        const sp<LayerBase>& layer = layers[i];
         const Region& visibleRegion(layer->visibleRegionScreen);
         if (!visibleRegion.isEmpty())  {
             const Region clip(dirty.intersect(visibleRegion));
@@ -913,14 +886,14 @@
 {
     const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
     const size_t count = drawingLayers.size();
-    LayerBase* const* const layers = drawingLayers.array();
+    sp<LayerBase> const* const layers = drawingLayers.array();
     for (size_t i=0 ; i<count ; ++i) {
-        LayerBase* const layer = layers[i];
+        const sp<LayerBase>& layer = layers[i];
         layer->finishPageFlip();
     }
 }
 
-void SurfaceFlinger::scheduleBroadcast(Client* client)
+void SurfaceFlinger::scheduleBroadcast(const sp<Client>& client)
 {
     if (mLastScheduledBroadcast != client) {
         mLastScheduledBroadcast = client;
@@ -930,50 +903,56 @@
 
 void SurfaceFlinger::executeScheduledBroadcasts()
 {
-    SortedVector<Client*>& list = mScheduledBroadcasts;
+    SortedVector< wp<Client> >& list(mScheduledBroadcasts);
     size_t count = list.size();
     while (count--) {
-        per_client_cblk_t* const cblk = list[count]->ctrlblk;
-        if (cblk->lock.tryLock() == NO_ERROR) {
-            cblk->cv.broadcast();
-            list.removeAt(count);
-            cblk->lock.unlock();
-        } else {
-            // schedule another round
-            LOGW("executeScheduledBroadcasts() skipped, "
-                "contention on the client. We'll try again later...");
-            signalDelayedEvent(ms2ns(4));
+        sp<Client> client = list[count].promote();
+        if (client != 0) {
+            per_client_cblk_t* const cblk = client->ctrlblk;
+            if (cblk->lock.tryLock() == NO_ERROR) {
+                cblk->cv.broadcast();
+                list.removeAt(count);
+                cblk->lock.unlock();
+            } else {
+                // schedule another round
+                LOGW("executeScheduledBroadcasts() skipped, "
+                        "contention on the client. We'll try again later...");
+                signalDelayedEvent(ms2ns(4));
+            }
         }
     }
     mLastScheduledBroadcast = 0;
 }
 
-void SurfaceFlinger::handleDebugCpu()
-{
-    Mutex::Autolock _l(mDebugLock);
-    if (mCpuGauge != 0)
-        mCpuGauge->sample();
-}
-
 void SurfaceFlinger::debugFlashRegions()
 {
-    if (UNLIKELY(!mDirtyRegion.isRect())) {
-        // TODO: do this only if we don't have preserving
-        // swapBuffer. If we don't have update-on-demand,
-        // redraw everything.
-        composeSurfaces(Region(mDirtyRegion.bounds()));
-    }
+     const DisplayHardware& hw(graphicPlane(0).displayHardware());
+     const uint32_t flags = hw.getFlags();
 
+     if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
+             (flags & DisplayHardware::BUFFER_PRESERVED))) {
+         const Region repaint((flags & DisplayHardware::UPDATE_ON_DEMAND) ?
+                 mDirtyRegion.bounds() : hw.bounds());
+         composeSurfaces(repaint);
+     }
+    
     glDisable(GL_TEXTURE_2D);
     glDisable(GL_BLEND);
     glDisable(GL_DITHER);
     glDisable(GL_SCISSOR_TEST);
 
-    glColor4x(0x10000, 0, 0x10000, 0x10000);
+    static int toggle = 0;
+    toggle = 1 - toggle;
+    if (toggle) {
+        glColor4x(0x10000, 0, 0x10000, 0x10000);
+    } else {
+        glColor4x(0x10000, 0x10000, 0, 0x10000);
+    }
 
-    Rect r;
-    Region::iterator iterator(mDirtyRegion);
-    while (iterator.iterate(&r)) {
+    Region::const_iterator it = mDirtyRegion.begin();
+    Region::const_iterator const end = mDirtyRegion.end();
+    while (it != end) {
+        const Rect& r = *it++;
         GLfloat vertices[][2] = {
                 { r.left,  r.top },
                 { r.left,  r.bottom },
@@ -983,10 +962,12 @@
         glVertexPointer(2, GL_FLOAT, 0, vertices);
         glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
     }
-
-    const DisplayHardware& hw(graphicPlane(0).displayHardware());
-    hw.flip(mDirtyRegion.merge(mInvalidRegion));
-    mInvalidRegion.clear();
+    
+    if (mInvalidRegion.isEmpty()) {
+        mDirtyRegion.dump("mDirtyRegion");
+        mInvalidRegion.dump("mInvalidRegion");
+    }
+    hw.flip(mInvalidRegion);
 
     if (mDebugRegion > 1)
        usleep(mDebugRegion * 1000);
@@ -1010,9 +991,10 @@
 
     if (LIKELY(!mDebugBackground)) {
         glClearColorx(0,0,0,0);
-        Rect r;
-        Region::iterator iterator(region);
-        while (iterator.iterate(&r)) {
+        Region::const_iterator it = region.begin();
+        Region::const_iterator const end = region.end();
+        while (it != end) {
+            const Rect& r = *it++;
             const GLint sy = height - (r.top + r.height());
             glScissor(r.left, sy, r.width(), r.height());
             glClear(GL_COLOR_BUFFER_BIT);
@@ -1030,9 +1012,10 @@
         glMatrixMode(GL_TEXTURE);
         glLoadIdentity();
         glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
-        Rect r;
-        Region::iterator iterator(region);
-        while (iterator.iterate(&r)) {
+        Region::const_iterator it = region.begin();
+        Region::const_iterator const end = region.end();
+        while (it != end) {
+            const Rect& r = *it++;
             const GLint sy = height - (r.top + r.height());
             glScissor(r.left, sy, r.width(), r.height());
             glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
@@ -1058,7 +1041,7 @@
     // XXX: mFPS has the value we want
  }
 
-status_t SurfaceFlinger::addLayer(LayerBase* layer)
+status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
 {
     Mutex::Autolock _l(mStateLock);
     addLayer_l(layer);
@@ -1066,62 +1049,72 @@
     return NO_ERROR;
 }
 
-status_t SurfaceFlinger::removeLayer(LayerBase* layer)
+status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
 {
     Mutex::Autolock _l(mStateLock);
-    removeLayer_l(layer);
-    setTransactionFlags(eTransactionNeeded);
-    return NO_ERROR;
+    status_t err = purgatorizeLayer_l(layer);
+    if (err == NO_ERROR)
+        setTransactionFlags(eTransactionNeeded);
+    return err;
 }
 
-status_t SurfaceFlinger::invalidateLayerVisibility(LayerBase* layer)
+status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
 {
     layer->forceVisibilityTransaction();
     setTransactionFlags(eTraversalNeeded);
     return NO_ERROR;
 }
 
-status_t SurfaceFlinger::addLayer_l(LayerBase* layer)
+status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
 {
     ssize_t i = mCurrentState.layersSortedByZ.add(
                 layer, &LayerBase::compareCurrentStateZ);
-    LayerBaseClient* lbc = LayerBase::dynamicCast<LayerBaseClient*>(layer);
-    if (lbc) {
+    sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
+    if (lbc != 0) {
         mLayerMap.add(lbc->serverIndex(), lbc);
     }
-    mRemovedLayers.remove(layer);
     return NO_ERROR;
 }
 
-status_t SurfaceFlinger::removeLayer_l(LayerBase* layerBase)
+status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
 {
     ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
     if (index >= 0) {
-        mRemovedLayers.add(layerBase);
-        LayerBaseClient* layer = LayerBase::dynamicCast<LayerBaseClient*>(layerBase);
-        if (layer) {
+        mLayersRemoved = true;
+        sp<LayerBaseClient> layer =
+            LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
+        if (layer != 0) {
             mLayerMap.removeItem(layer->serverIndex());
         }
         return NO_ERROR;
     }
+    return status_t(index);
+}
+
+status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
+{
+    // remove the layer from the main list (through a transaction).
+    ssize_t err = removeLayer_l(layerBase);
+
     // it's possible that we don't find a layer, because it might
     // have been destroyed already -- this is not technically an error
-    // from the user because there is a race between destroySurface,
-    // destroyclient and destroySurface-from-a-transaction.
-    return (index == NAME_NOT_FOUND) ? status_t(NO_ERROR) : index;
+    // from the user because there is a race between BClient::destroySurface(),
+    // ~BClient() and ~ISurface().
+    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
 }
 
+
 void SurfaceFlinger::free_resources_l()
 {
     // Destroy layers that were removed
-    destroy_all_removed_layers_l();
-
+    mLayersRemoved = false;
+    
     // free resources associated with disconnected clients
-    SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
-    Vector<Client*>& disconnectedClients(mDisconnectedClients);
+    SortedVector< wp<Client> >& scheduledBroadcasts(mScheduledBroadcasts);
+    Vector< sp<Client> >& disconnectedClients(mDisconnectedClients);
     const size_t count = disconnectedClients.size();
     for (size_t i=0 ; i<count ; i++) {
-        Client* client = disconnectedClients[i];
+        sp<Client> client = disconnectedClients[i];
         // if this client is the scheduled broadcast list,
         // remove it from there (and we don't need to signal it
         // since it is dead).
@@ -1130,27 +1123,10 @@
             scheduledBroadcasts.removeItemsAt(index);
         }
         mTokens.release(client->cid);
-        delete client;
     }
     disconnectedClients.clear();
 }
 
-void SurfaceFlinger::destroy_all_removed_layers_l()
-{
-    size_t c = mRemovedLayers.size();
-    while (c--) {
-        LayerBase* const removed_layer = mRemovedLayers[c];
-
-        LOGE_IF(mCurrentState.layersSortedByZ.indexOf(removed_layer) >= 0,
-            "layer %p removed but still in the current state list",
-            removed_layer);
-
-        delete removed_layer;
-    }
-    mRemovedLayers.clear();
-}
-
-
 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
 {
     return android_atomic_and(~flags, &mTransactionFlags) & flags;
@@ -1191,7 +1167,7 @@
     setTransactionFlags(eTransactionNeeded);
 
     // flags is intended to communicate some sort of animation behavior
-    // (for instance fadding)
+    // (for instance fading)
     return NO_ERROR;
 }
 
@@ -1205,7 +1181,7 @@
     setTransactionFlags(eTransactionNeeded);
 
     // flags is intended to communicate some sort of animation behavior
-    // (for instance fadding)
+    // (for instance fading)
     return NO_ERROR;
 }
 
@@ -1234,7 +1210,7 @@
         DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
         uint32_t flags)
 {
-    LayerBaseClient* layer = 0;
+    sp<LayerBaseClient> layer;
     sp<LayerBaseClient::Surface> surfaceHandle;
 
     if (int32_t(w|h) < 0) {
@@ -1244,14 +1220,14 @@
     }
     
     Mutex::Autolock _l(mStateLock);
-    Client* const c = mClientsMap.valueFor(clientId);
-    if (UNLIKELY(!c)) {
+    sp<Client> client = mClientsMap.valueFor(clientId);
+    if (UNLIKELY(client == 0)) {
         LOGE("createSurface() failed, client not found (id=%d)", clientId);
         return surfaceHandle;
     }
 
     //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
-    int32_t id = c->generateId(pid);
+    int32_t id = client->generateId(pid);
     if (uint32_t(id) >= NUM_LAYERS_MAX) {
         LOGE("createSurface() failed, generateId = %d", id);
         return surfaceHandle;
@@ -1260,20 +1236,20 @@
     switch (flags & eFXSurfaceMask) {
         case eFXSurfaceNormal:
             if (UNLIKELY(flags & ePushBuffers)) {
-                layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
+                layer = createPushBuffersSurfaceLocked(client, d, id, w, h, flags);
             } else {
-                layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
+                layer = createNormalSurfaceLocked(client, d, id, w, h, format, flags);
             }
             break;
         case eFXSurfaceBlur:
-            layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
+            layer = createBlurSurfaceLocked(client, d, id, w, h, flags);
             break;
         case eFXSurfaceDim:
-            layer = createDimSurfaceLocked(c, d, id, w, h, flags);
+            layer = createDimSurfaceLocked(client, d, id, w, h, flags);
             break;
     }
 
-    if (layer) {
+    if (layer != 0) {
         setTransactionFlags(eTransactionNeeded);
         surfaceHandle = layer->getSurface();
         if (surfaceHandle != 0)
@@ -1283,8 +1259,8 @@
     return surfaceHandle;
 }
 
-LayerBaseClient* SurfaceFlinger::createNormalSurfaceLocked(
-        Client* client, DisplayID display,
+sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
+        const sp<Client>& client, DisplayID display,
         int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
 {
     // initialize the surfaces
@@ -1298,57 +1274,99 @@
         break;
     }
 
-    Layer* layer = new Layer(this, display, client, id);
-    status_t err = layer->setBuffers(client, w, h, format, flags);
+    sp<Layer> layer = new Layer(this, display, client, id);
+    status_t err = layer->setBuffers(w, h, format, flags);
     if (LIKELY(err == NO_ERROR)) {
         layer->initStates(w, h, flags);
         addLayer_l(layer);
     } else {
         LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
-        delete layer;
-        return 0;
+        layer.clear();
     }
     return layer;
 }
 
-LayerBaseClient* SurfaceFlinger::createBlurSurfaceLocked(
-        Client* client, DisplayID display,
+sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
+        const sp<Client>& client, DisplayID display,
         int32_t id, uint32_t w, uint32_t h, uint32_t flags)
 {
-    LayerBlur* layer = new LayerBlur(this, display, client, id);
+    sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
     layer->initStates(w, h, flags);
     addLayer_l(layer);
     return layer;
 }
 
-LayerBaseClient* SurfaceFlinger::createDimSurfaceLocked(
-        Client* client, DisplayID display,
+sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
+        const sp<Client>& client, DisplayID display,
         int32_t id, uint32_t w, uint32_t h, uint32_t flags)
 {
-    LayerDim* layer = new LayerDim(this, display, client, id);
+    sp<LayerDim> layer = new LayerDim(this, display, client, id);
     layer->initStates(w, h, flags);
     addLayer_l(layer);
     return layer;
 }
 
-LayerBaseClient* SurfaceFlinger::createPushBuffersSurfaceLocked(
-        Client* client, DisplayID display,
+sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
+        const sp<Client>& client, DisplayID display,
         int32_t id, uint32_t w, uint32_t h, uint32_t flags)
 {
-    LayerBuffer* layer = new LayerBuffer(this, display, client, id);
+    sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
     layer->initStates(w, h, flags);
     addLayer_l(layer);
     return layer;
 }
 
-status_t SurfaceFlinger::destroySurface(SurfaceID index)
+status_t SurfaceFlinger::removeSurface(SurfaceID index)
 {
+    /*
+     * called by the window manager, when a surface should be marked for
+     * destruction.
+     * 
+     * The surface is removed from the current and drawing lists, but placed
+     * in the purgatory queue, so it's not destroyed right-away (we need
+     * to wait for all client's references to go away first).
+     */
+
     Mutex::Autolock _l(mStateLock);
-    LayerBaseClient* const layer = getLayerUser_l(index);
-    status_t err = removeLayer_l(layer);
-    if (err < 0)
-        return err;
-    setTransactionFlags(eTransactionNeeded);
+    sp<LayerBaseClient> layer = getLayerUser_l(index);
+    status_t err = purgatorizeLayer_l(layer);
+    if (err == NO_ERROR) {
+        setTransactionFlags(eTransactionNeeded);
+    }
+    return err;
+}
+
+status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
+{
+    // called by ~ISurface() when all references are gone
+    
+    class MessageDestroySurface : public MessageBase {
+        SurfaceFlinger* flinger;
+        sp<LayerBaseClient> layer;
+    public:
+        MessageDestroySurface(
+                SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
+            : flinger(flinger), layer(layer) { }
+        virtual bool handler() {
+            sp<LayerBaseClient> l(layer);
+            layer.clear(); // clear it outside of the lock;
+            Mutex::Autolock _l(flinger->mStateLock);
+            /*
+             * remove the layer from the current list -- chances are that it's 
+             * not in the list anyway, because it should have been removed 
+             * already upon request of the client (eg: window manager). 
+             * However, a buggy client could have not done that.
+             * Since we know we don't have any more clients, we don't need
+             * to use the purgatory.
+             */
+            status_t err = flinger->removeLayer_l(l);
+            LOGE_IF(err<0 && err != NAME_NOT_FOUND,
+                    "error removing layer=%p (%s)", l.get(), strerror(-err));
+            return true;
+        }
+    };
+
+    mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
     return NO_ERROR;
 }
 
@@ -1362,18 +1380,9 @@
     cid <<= 16;
     for (int i=0 ; i<count ; i++) {
         const layer_state_t& s = states[i];
-        LayerBaseClient* layer = getLayerUser_l(s.surface | cid);
-        if (layer) {
+        sp<LayerBaseClient> layer(getLayerUser_l(s.surface | cid));
+        if (layer != 0) {
             const uint32_t what = s.what;
-            // check if it has been destroyed first
-            if (what & eDestroyed) {
-                if (removeLayer_l(layer) == NO_ERROR) {
-                    flags |= eTransactionNeeded;
-                    // we skip everything else... well, no, not really
-                    // we skip ONLY that transaction.
-                    continue;
-                }
-            }
             if (what & ePositionChanged) {
                 if (layer->setPosition(s.x, s.y))
                     flags |= eTraversalNeeded;
@@ -1415,9 +1424,10 @@
     return NO_ERROR;
 }
 
-LayerBaseClient* SurfaceFlinger::getLayerUser_l(SurfaceID s) const
+sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
 {
-    return mLayerMap.valueFor(s);
+    sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
+    return layer;
 }
 
 void SurfaceFlinger::screenReleased(int dpy)
@@ -1439,9 +1449,7 @@
     const size_t SIZE = 1024;
     char buffer[SIZE];
     String8 result;
-    if (checkCallingPermission(
-            String16("android.permission.DUMP")) == false)
-    { // not allowed
+    if (!mDump.checkCalling()) {
         snprintf(buffer, SIZE, "Permission Denial: "
                 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
                 IPCThreadState::self()->getCallingPid(),
@@ -1452,7 +1460,7 @@
         size_t s = mClientsMap.size();
         char name[64];
         for (size_t i=0 ; i<s ; i++) {
-            Client* client = mClientsMap.valueAt(i);
+            sp<Client> client = mClientsMap.valueAt(i);
             sprintf(name, "  Client (id=0x%08x)", client->cid);
             client->dump(name);
         }
@@ -1460,7 +1468,7 @@
         const size_t count = currentLayers.size();
         for (size_t i=0 ; i<count ; i++) {
             /*** LayerBase ***/
-            LayerBase const * const layer = currentLayers[i];
+            const sp<LayerBase>& layer = currentLayers[i];
             const Layer::State& s = layer->drawingState();
             snprintf(buffer, SIZE,
                     "+ %s %p\n"
@@ -1468,7 +1476,7 @@
                     "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
                     "needsBlending=%1d, invalidate=%1d, "
                     "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
-                    layer->getTypeID(), layer,
+                    layer->getTypeID(), layer.get(),
                     s.z, layer->tx(), layer->ty(), s.w, s.h,
                     layer->needsBlending(), layer->contentDirty,
                     s.alpha, s.flags,
@@ -1477,30 +1485,33 @@
             result.append(buffer);
             buffer[0] = 0;
             /*** LayerBaseClient ***/
-            LayerBaseClient* const lbc =
-                LayerBase::dynamicCast<LayerBaseClient*>((LayerBase*)layer);
-            if (lbc) {
+            sp<LayerBaseClient> lbc =
+                LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
+            if (lbc != 0) {
+                sp<Client> client(lbc->client.promote());
                 snprintf(buffer, SIZE,
                         "      "
                         "id=0x%08x, client=0x%08x, identity=%u\n",
-                        lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
+                        lbc->clientIndex(), client.get() ? client->cid : 0,
                         lbc->getIdentity());
             }
             result.append(buffer);
             buffer[0] = 0;
             /*** Layer ***/
-            Layer* const l = LayerBase::dynamicCast<Layer*>((LayerBase*)layer);
-            if (l) {
+            sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
+            if (l != 0) {
                 const LayerBitmap& buf0(l->getBuffer(0));
                 const LayerBitmap& buf1(l->getBuffer(1));
                 snprintf(buffer, SIZE,
                         "      "
-                        "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u], mTextureName=%d,"
+                        "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
                         " freezeLock=%p, swapState=0x%08x\n",
                         l->pixelFormat(),
-                        buf0.width(), buf0.height(), buf0.stride(),
-                        buf1.width(), buf1.height(), buf1.stride(),
-                        l->getTextureName(), l->getFreezeLock().get(),
+                        buf0.getWidth(), buf0.getHeight(), 
+                        buf0.getBuffer()->getStride(),
+                        buf1.getWidth(), buf1.getHeight(), 
+                        buf1.getBuffer()->getStride(),
+                        l->getFreezeLock().get(),
                         l->lcblk->swapState);
             }
             result.append(buffer);
@@ -1516,20 +1527,10 @@
                 mFreezeDisplay?"yes":"no", mFreezeCount,
                 mCurrentState.orientation, hw.canDraw());
         result.append(buffer);
-
-        sp<AllocatorInterface> allocator;
-        if (mGPU != 0) {
-            snprintf(buffer, SIZE, "  GPU owner: %d\n", mGPU->getOwner());
-            result.append(buffer);
-            allocator = mGPU->getAllocator();
-            if (allocator != 0) {
-                allocator->dump(result, "GPU Allocator");
-            }
-        }
-        allocator = mSurfaceHeapManager->getAllocator(NATIVE_MEMORY_TYPE_PMEM);
-        if (allocator != 0) {
-            allocator->dump(result, "PMEM Allocator");
-        }
+        snprintf(buffer, SIZE, "  client count: %d\n", mClientsMap.size());
+        result.append(buffer);
+        const BufferAllocator& alloc(BufferAllocator::get());
+        alloc.dump(result);
     }
     write(fd, result.string(), result.size());
     return NO_ERROR;
@@ -1546,57 +1547,34 @@
         case FREEZE_DISPLAY:
         case UNFREEZE_DISPLAY:
         case BOOT_FINISHED:
-        case REVOKE_GPU:
         {
             // codes that require permission check
             IPCThreadState* ipc = IPCThreadState::self();
             const int pid = ipc->getCallingPid();
             const int uid = ipc->getCallingUid();
-            const int self_pid = getpid();
-            if (UNLIKELY(pid != self_pid && uid != AID_GRAPHICS)) {
-                // we're called from a different process, do the real check
-                if (!checkCallingPermission(
-                        String16("android.permission.ACCESS_SURFACE_FLINGER")))
-                {
-                    LOGE("Permission Denial: "
-                            "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
-                    return PERMISSION_DENIED;
-                }
+            if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) {
+                LOGE("Permission Denial: "
+                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
+                return PERMISSION_DENIED;
             }
         }
     }
-
     status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
     if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
-        // HARDWARE_TEST stuff...
-        if (UNLIKELY(checkCallingPermission(
-                String16("android.permission.HARDWARE_TEST")) == false))
-        { // not allowed
-            LOGE("Permission Denial: pid=%d, uid=%d\n",
-                    IPCThreadState::self()->getCallingPid(),
-                    IPCThreadState::self()->getCallingUid());
+        CHECK_INTERFACE(ISurfaceComposer, data, reply);
+        if (UNLIKELY(!mHardwareTest.checkCalling())) {
+            IPCThreadState* ipc = IPCThreadState::self();
+            const int pid = ipc->getCallingPid();
+            const int uid = ipc->getCallingUid();
+            LOGE("Permission Denial: "
+                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
             return PERMISSION_DENIED;
         }
         int n;
         switch (code) {
-            case 1000: // SHOW_CPU
-                n = data.readInt32();
-                mDebugCpu = n ? 1 : 0;
-                if (mDebugCpu) {
-                    if (mCpuGauge == 0) {
-                        mCpuGauge = new CPUGauge(this, ms2ns(500));
-                    }
-                } else {
-                    if (mCpuGauge != 0) {
-                        mCpuGauge->requestExitAndWait();
-                        Mutex::Autolock _l(mDebugLock);
-                        mCpuGauge.clear();
-                    }
-                }
+            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
                 return NO_ERROR;
-            case 1001:  // SHOW_FPS
-                n = data.readInt32();
-                mDebugFps = n ? 1 : 0;
+            case 1001:  // SHOW_FPS, NOT SUPPORTED ANYMORE
                 return NO_ERROR;
             case 1002:  // SHOW_UPDATES
                 n = data.readInt32();
@@ -1613,21 +1591,11 @@
                 signalEvent();
             }
             return NO_ERROR;
-            case 1005: // ask GPU revoke
-                if (mGPU != 0) {
-                    mGPU->friendlyRevoke();
-                }
-                return NO_ERROR;
-            case 1006: // revoke GPU
-                if (mGPU != 0) {
-                    mGPU->unconditionalRevoke();
-                }
-                return NO_ERROR;
             case 1007: // set mFreezeCount
                 mFreezeCount = data.readInt32();
                 return NO_ERROR;
             case 1010:  // interrogate.
-                reply->writeInt32(mDebugCpu);
+                reply->writeInt32(0);
                 reply->writeInt32(0);
                 reply->writeInt32(mDebugRegion);
                 reply->writeInt32(mDebugBackground);
@@ -1651,16 +1619,15 @@
 Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
     : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
 {
-    mSharedHeapAllocator = getSurfaceHeapManager()->createHeap();
     const int pgsize = getpagesize();
-    const int cblksize=((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
-    mCblkHeap = new MemoryDealer(cblksize);
-    mCblkMemory = mCblkHeap->allocate(cblksize);
-    if (mCblkMemory != 0) {
-        ctrlblk = static_cast<per_client_cblk_t *>(mCblkMemory->pointer());
-        if (ctrlblk) { // construct the shared structure in-place.
-            new(ctrlblk) per_client_cblk_t;
-        }
+    const int cblksize = ((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
+
+    mCblkHeap = new MemoryHeapBase(cblksize, 0,
+            "SurfaceFlinger Client control-block");
+
+    ctrlblk = static_cast<per_client_cblk_t *>(mCblkHeap->getBase());
+    if (ctrlblk) { // construct the shared structure in-place.
+        new(ctrlblk) per_client_cblk_t;
     }
 }
 
@@ -1671,10 +1638,6 @@
     }
 }
 
-const sp<SurfaceHeapManager>& Client::getSurfaceHeapManager() const {
-    return mFlinger->getSurfaceHeapManager();
-}
-
 int32_t Client::generateId(int pid)
 {
     const uint32_t i = clz( ~mBitmap );
@@ -1686,13 +1649,15 @@
     mBitmap |= 1<<(31-i);
     return i;
 }
-status_t Client::bindLayer(LayerBaseClient* layer, int32_t id)
+
+status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
 {
     ssize_t idx = mInUse.indexOf(id);
     if (idx < 0)
         return NAME_NOT_FOUND;
     return mLayers.insertAt(layer, idx);
 }
+
 void Client::free(int32_t id)
 {
     ssize_t idx = mInUse.remove(uint8_t(id));
@@ -1702,27 +1667,18 @@
     }
 }
 
-sp<MemoryDealer> Client::createAllocator(uint32_t flags)
-{
-    sp<MemoryDealer> allocator;
-    allocator = getSurfaceHeapManager()->createHeap(
-            flags, getClientPid(), mSharedHeapAllocator);
-    return allocator;
-}
-
 bool Client::isValid(int32_t i) const {
     return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
 }
-const uint8_t* Client::inUseArray() const {
-    return mInUse.array();
-}
-size_t Client::numActiveLayers() const {
-    return mInUse.size();
-}
-LayerBaseClient* Client::getLayerUser(int32_t i) const {
+
+sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
+    sp<LayerBaseClient> lbc;
     ssize_t idx = mInUse.indexOf(uint8_t(i));
-    if (idx<0) return 0;
-    return mLayers[idx];
+    if (idx >= 0) {
+        lbc = mLayers[idx].promote();
+        LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
+    }
+    return lbc;
 }
 
 void Client::dump(const char* what)
@@ -1734,7 +1690,7 @@
 #pragma mark -
 #endif
 
-BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemory>& cblk)
+BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemoryHeap>& cblk)
     : mId(cid), mFlinger(flinger), mCblk(cblk)
 {
 }
@@ -1744,8 +1700,8 @@
     mFlinger->destroyConnection(mId);
 }
 
-void BClient::getControlBlocks(sp<IMemory>* ctrl) const {
-    *ctrl = mCblk;
+sp<IMemoryHeap> BClient::getControlBlock() const {
+    return mCblk;
 }
 
 sp<ISurface> BClient::createSurface(
@@ -1759,7 +1715,7 @@
 status_t BClient::destroySurface(SurfaceID sid)
 {
     sid |= (mId << 16); // add the client-part to id
-    return mFlinger->destroySurface(sid);
+    return mFlinger->removeSurface(sid);
 }
 
 status_t BClient::setState(int32_t count, const layer_state_t* states)
@@ -1859,6 +1815,10 @@
     return mGlobalTransform;
 }
 
+EGLDisplay GraphicPlane::getEGLDisplay() const {
+    return mHw->getEGLDisplay();
+}
+
 // ---------------------------------------------------------------------------
 
 }; // namespace android
diff --git a/libs/surfaceflinger/SurfaceFlinger.h b/libs/surfaceflinger/SurfaceFlinger.h
index 15913f2..e8687a7 100644
--- a/libs/surfaceflinger/SurfaceFlinger.h
+++ b/libs/surfaceflinger/SurfaceFlinger.h
@@ -25,7 +25,10 @@
 #include <utils/threads.h>
 #include <utils/Atomic.h>
 #include <utils/Errors.h>
-#include <utils/MemoryDealer.h>
+#include <utils/RefBase.h>
+
+#include <binder/IMemory.h>
+#include <binder/Permission.h>
 
 #include <ui/PixelFormat.h>
 #include <ui/ISurfaceComposer.h>
@@ -33,13 +36,13 @@
 
 #include <private/ui/SharedState.h>
 #include <private/ui/LayerState.h>
-#include <private/ui/SurfaceFlingerSynchro.h>
 
 #include "Barrier.h"
-#include "CPUGauge.h"
 #include "Layer.h"
 #include "Tokenizer.h"
 
+#include "MessageQueue.h"
+
 struct copybit_device_t;
 struct overlay_device_t;
 
@@ -51,13 +54,8 @@
 class BClient;
 class DisplayHardware;
 class FreezeLock;
-class GPUHardwareInterface;
-class IGPUCallback;
 class Layer;
 class LayerBuffer;
-class LayerOrientationAnim;
-class OrientationAnimation;
-class SurfaceHeapManager;
 
 typedef int32_t ClientID;
 
@@ -66,7 +64,7 @@
 
 // ---------------------------------------------------------------------------
 
-class Client
+class Client : public RefBase
 {
 public:
             Client(ClientID cid, const sp<SurfaceFlinger>& flinger);
@@ -74,17 +72,19 @@
 
             int32_t                 generateId(int pid);
             void                    free(int32_t id);
-            status_t                bindLayer(LayerBaseClient* layer, int32_t id);
-            sp<MemoryDealer>        createAllocator(uint32_t memory_type);
+            status_t                bindLayer(const sp<LayerBaseClient>& layer, int32_t id);
 
     inline  bool                    isValid(int32_t i) const;
-    inline  const uint8_t*          inUseArray() const;
-    inline  size_t                  numActiveLayers() const;
-    LayerBaseClient*                getLayerUser(int32_t i) const;
-    const Vector<LayerBaseClient*>& getLayers() const { return mLayers; }
-    const sp<IMemory>&              controlBlockMemory() const { return mCblkMemory; }
+    sp<LayerBaseClient>             getLayerUser(int32_t i) const;
     void                            dump(const char* what);
-    const sp<SurfaceHeapManager>&   getSurfaceHeapManager() const;
+    
+    const Vector< wp<LayerBaseClient> >& getLayers() const { 
+        return mLayers; 
+    }
+    
+    const sp<IMemoryHeap>& getControlBlockMemory() const {
+        return mCblkHeap; 
+    }
     
     // pointer to this client's control block
     per_client_cblk_t*      ctrlblk;
@@ -92,17 +92,14 @@
 
     
 private:
-    int                     getClientPid() const { return mPid; }
+    int getClientPid() const { return mPid; }
         
-    int                         mPid;
-    uint32_t                    mBitmap;
-    SortedVector<uint8_t>       mInUse;
-    Vector<LayerBaseClient*>    mLayers;
-    sp<MemoryDealer>            mCblkHeap;
-    sp<SurfaceFlinger>          mFlinger;
-    sp<MemoryDealer>            mSharedHeapAllocator;
-    sp<MemoryDealer>            mPMemAllocator;
-    sp<IMemory>                 mCblkMemory;
+    int                             mPid;
+    uint32_t                        mBitmap;
+    SortedVector<uint8_t>           mInUse;
+    Vector< wp<LayerBaseClient> >   mLayers;
+    sp<IMemoryHeap>                 mCblkHeap;
+    sp<SurfaceFlinger>              mFlinger;
 };
 
 // ---------------------------------------------------------------------------
@@ -125,6 +122,8 @@
 
         const DisplayHardware&  displayHardware() const;
         const Transform&        transform() const;
+        EGLDisplay              getEGLDisplay() const;
+        
 private:
                                 GraphicPlane(const GraphicPlane&);
         GraphicPlane            operator = (const GraphicPlane&);
@@ -160,7 +159,7 @@
 
     // ISurfaceComposer interface
     virtual sp<ISurfaceFlingerClient>   createConnection();
-    virtual sp<IMemory>                 getCblk() const;
+    virtual sp<IMemoryHeap>             getCblk() const;
     virtual void                        bootFinished();
     virtual void                        openGlobalTransaction();
     virtual void                        closeGlobalTransaction();
@@ -168,56 +167,52 @@
     virtual status_t                    unfreezeDisplay(DisplayID dpy, uint32_t flags);
     virtual int                         setOrientation(DisplayID dpy, int orientation, uint32_t flags);
     virtual void                        signal() const;
-    virtual status_t requestGPU(const sp<IGPUCallback>& callback, 
-            gpu_info_t* gpu);
-    virtual status_t revokeGPU();
 
             void                        screenReleased(DisplayID dpy);
             void                        screenAcquired(DisplayID dpy);
 
-            const sp<SurfaceHeapManager>& getSurfaceHeapManager() const { 
-                return mSurfaceHeapManager; 
-            }
-
-            const sp<GPUHardwareInterface>& getGPU() const {
-                return mGPU; 
-            }
-
-            copybit_device_t* getBlitEngine() const;
             overlay_control_device_t* getOverlayEngine() const;
 
             
-    status_t removeLayer(LayerBase* layer);
-    status_t addLayer(LayerBase* layer);
-    status_t invalidateLayerVisibility(LayerBase* layer);
+    status_t removeLayer(const sp<LayerBase>& layer);
+    status_t addLayer(const sp<LayerBase>& layer);
+    status_t invalidateLayerVisibility(const sp<LayerBase>& layer);
     
 private:
     friend class BClient;
     friend class LayerBase;
     friend class LayerBuffer;
     friend class LayerBaseClient;
+    friend class LayerBaseClient::Surface;
     friend class Layer;
     friend class LayerBlur;
+    friend class LayerDim;
 
     sp<ISurface> createSurface(ClientID client, int pid, 
             ISurfaceFlingerClient::surface_data_t* params,
             DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
             uint32_t flags);
 
-    LayerBaseClient* createNormalSurfaceLocked(Client* client, DisplayID display,
-            int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags);
+    sp<LayerBaseClient> createNormalSurfaceLocked(
+            const sp<Client>& client, DisplayID display,
+            int32_t id, uint32_t w, uint32_t h, 
+            PixelFormat format, uint32_t flags);
 
-    LayerBaseClient* createBlurSurfaceLocked(Client* client, DisplayID display,
+    sp<LayerBaseClient> createBlurSurfaceLocked(
+            const sp<Client>& client, DisplayID display,
             int32_t id, uint32_t w, uint32_t h, uint32_t flags);
 
-    LayerBaseClient* createDimSurfaceLocked(Client* client, DisplayID display,
+    sp<LayerBaseClient> createDimSurfaceLocked(
+            const sp<Client>& client, DisplayID display,
             int32_t id, uint32_t w, uint32_t h, uint32_t flags);
 
-    LayerBaseClient* createPushBuffersSurfaceLocked(Client* client, DisplayID display,
+    sp<LayerBaseClient> createPushBuffersSurfaceLocked(
+            const sp<Client>& client, DisplayID display,
             int32_t id, uint32_t w, uint32_t h, uint32_t flags);
 
-    status_t    destroySurface(SurfaceID surface_id);
-    status_t    setClientState(ClientID cid, int32_t count, const layer_state_t* states);
+    status_t removeSurface(SurfaceID surface_id);
+    status_t destroySurface(const sp<LayerBaseClient>& layer);
+    status_t setClientState(ClientID cid, int32_t count, const layer_state_t* states);
 
 
     class LayerVector {
@@ -225,15 +220,15 @@
         inline              LayerVector() { }
                             LayerVector(const LayerVector&);
         inline size_t       size() const { return layers.size(); }
-        inline LayerBase*const* array() const { return layers.array(); }
-        ssize_t             add(LayerBase*, Vector<LayerBase*>::compar_t);
-        ssize_t             remove(LayerBase*);
-        ssize_t             reorder(LayerBase*, Vector<LayerBase*>::compar_t);
-        ssize_t             indexOf(LayerBase* key, size_t guess=0) const;
-        inline LayerBase*   operator [] (size_t i) const { return layers[i]; }
+        inline sp<LayerBase> const* array() const { return layers.array(); }
+        ssize_t             add(const sp<LayerBase>&, Vector< sp<LayerBase> >::compar_t);
+        ssize_t             remove(const sp<LayerBase>&);
+        ssize_t             reorder(const sp<LayerBase>&, Vector< sp<LayerBase> >::compar_t);
+        ssize_t             indexOf(const sp<LayerBase>& key, size_t guess=0) const;
+        inline sp<LayerBase> operator [] (size_t i) const { return layers[i]; }
     private:
-        KeyedVector<LayerBase*, size_t> lookup;
-        Vector<LayerBase*>              layers;
+        KeyedVector< sp<LayerBase> , size_t> lookup;
+        Vector< sp<LayerBase> >              layers;
     };
 
     struct State {
@@ -247,25 +242,6 @@
         uint8_t         freezeDisplay;
     };
 
-    class DelayedTransaction : public Thread
-    {
-        friend class SurfaceFlinger;
-        sp<SurfaceFlinger>  mFlinger;
-        nsecs_t             mDelay;
-    public:
-        DelayedTransaction(const sp<SurfaceFlinger>& flinger, nsecs_t delay)
-            : Thread(false), mFlinger(flinger), mDelay(delay) {
-        }
-        virtual bool threadLoop() {
-            usleep(mDelay / 1000);
-            if (android_atomic_and(~1,
-                    &mFlinger->mDeplayedTransactionPending) == 1) {
-                mFlinger->signalEvent();
-            }
-            return false;
-        }
-    };
-
     virtual bool        threadLoop();
     virtual status_t    readyToRun();
     virtual void        onFirstRef();
@@ -279,6 +255,9 @@
 
             void        handleConsoleEvents();
             void        handleTransaction(uint32_t transactionFlags);
+            void        handleTransactionLocked(
+                            uint32_t transactionFlags, 
+                            Vector< sp<LayerBase> >& ditchedLayers);
 
             void        computeVisibleRegions(
                             LayerVector& currentLayers,
@@ -289,8 +268,7 @@
             bool        lockPageFlip(const LayerVector& currentLayers);
             void        unlockPageFlip(const LayerVector& currentLayers);
             void        handleRepaint();
-            void        handleDebugCpu();
-            void        scheduleBroadcast(Client* client);
+            void        scheduleBroadcast(const sp<Client>& client);
             void        executeScheduledBroadcasts();
             void        postFramebuffer();
             void        composeSurfaces(const Region& dirty);
@@ -298,10 +276,10 @@
 
 
             void        destroyConnection(ClientID cid);
-            LayerBaseClient* getLayerUser_l(SurfaceID index) const;
-            status_t    addLayer_l(LayerBase* layer);
-            status_t    removeLayer_l(LayerBase* layer);
-            void        destroy_all_removed_layers_l();
+            sp<LayerBaseClient> getLayerUser_l(SurfaceID index) const;
+            status_t    addLayer_l(const sp<LayerBase>& layer);
+            status_t    removeLayer_l(const sp<LayerBase>& layer);
+            status_t    purgatorizeLayer_l(const sp<LayerBase>& layer);
             void        free_resources_l();
 
             uint32_t    getTransactionFlags(uint32_t flags);
@@ -323,6 +301,11 @@
             void        debugShowFPS() const;
             void        drawWormhole() const;
            
+
+    mutable     MessageQueue    mEventQueue;
+    
+                
+                
                 // access must be protected by mStateLock
     mutable     Mutex                   mStateLock;
                 State                   mCurrentState;
@@ -330,53 +313,43 @@
     volatile    int32_t                 mTransactionFlags;
     volatile    int32_t                 mTransactionCount;
                 Condition               mTransactionCV;
-
+                
                 // protected by mStateLock (but we could use another lock)
                 Tokenizer                               mTokens;
-                DefaultKeyedVector<ClientID, Client*>   mClientsMap;
-                DefaultKeyedVector<SurfaceID, LayerBaseClient*>   mLayerMap;
+                DefaultKeyedVector<ClientID, sp<Client> >   mClientsMap;
+                DefaultKeyedVector<SurfaceID, sp<LayerBaseClient> >   mLayerMap;
                 GraphicPlane                            mGraphicPlanes[1];
-                SortedVector<LayerBase*>                mRemovedLayers;
-                Vector<Client*>                         mDisconnectedClients;
+                bool                                    mLayersRemoved;
+                Vector< sp<Client> >                    mDisconnectedClients;
 
                 // constant members (no synchronization needed for access)
-                sp<MemoryDealer>            mServerHeap;
-                sp<IMemory>                 mServerCblkMemory;
+                sp<IMemoryHeap>             mServerHeap;
                 surface_flinger_cblk_t*     mServerCblk;
-                sp<SurfaceHeapManager>      mSurfaceHeapManager;
-                sp<GPUHardwareInterface>    mGPU;
                 GLuint                      mWormholeTexName;
                 nsecs_t                     mBootTime;
+                Permission                  mHardwareTest;
+                Permission                  mAccessSurfaceFlinger;
+                Permission                  mDump;
                 
                 // Can only accessed from the main thread, these members
                 // don't need synchronization
                 Region                      mDirtyRegion;
                 Region                      mInvalidRegion;
                 Region                      mWormholeRegion;
-                Client*                     mLastScheduledBroadcast;
-                SortedVector<Client*>       mScheduledBroadcasts;
+                wp<Client>                  mLastScheduledBroadcast;
+                SortedVector< wp<Client> >  mScheduledBroadcasts;
                 bool                        mVisibleRegionsDirty;
                 bool                        mDeferReleaseConsole;
                 bool                        mFreezeDisplay;
                 int32_t                     mFreezeCount;
                 nsecs_t                     mFreezeDisplayTime;
-                friend class OrientationAnimation;
-                OrientationAnimation*       mOrientationAnimation;
-
-                // access protected by mDebugLock
-    mutable     Mutex                       mDebugLock;
-                sp<CPUGauge>                mCpuGauge;
 
                 // don't use a lock for these, we don't care
                 int                         mDebugRegion;
-                int                         mDebugCpu;
-                int                         mDebugFps;
                 int                         mDebugBackground;
 
                 // these are thread safe
     mutable     Barrier                     mReadyToRunBarrier;
-    mutable     SurfaceFlingerSynchro       mSyncObject;
-    volatile    int32_t                     mDeplayedTransactionPending;
 
                 // atomic variables
                 enum {
@@ -409,11 +382,11 @@
 {
 public:
     BClient(SurfaceFlinger *flinger, ClientID cid,
-            const sp<IMemory>& cblk);
+            const sp<IMemoryHeap>& cblk);
     ~BClient();
 
     // ISurfaceFlingerClient interface
-    virtual void getControlBlocks(sp<IMemory>* ctrl) const;
+    virtual sp<IMemoryHeap> getControlBlock() const;
 
     virtual sp<ISurface> createSurface(
             surface_data_t* params, int pid,
@@ -426,7 +399,7 @@
 private:
     ClientID            mId;
     SurfaceFlinger*     mFlinger;
-    sp<IMemory>         mCblk;
+    sp<IMemoryHeap>     mCblk;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/libs/surfaceflinger/Tokenizer.cpp b/libs/surfaceflinger/Tokenizer.cpp
index ef51d6a..be3a239 100644
--- a/libs/surfaceflinger/Tokenizer.cpp
+++ b/libs/surfaceflinger/Tokenizer.cpp
@@ -162,9 +162,10 @@
 {
     const run_t* ranges = mRanges.array();
     const size_t c = mRanges.size();
-    printf("Tokenizer (%p, size = %lu)\n", this, c);
+    printf("Tokenizer (%p, size = %d)\n", this, int(c));
     for (size_t i=0 ; i<c ; i++) {
-        printf("%lu: (%u, %u)\n", i, ranges[i].first, ranges[i].length);
+        printf("%u: (%u, %u)\n", i,
+                uint32_t(ranges[i].first), uint32_t(ranges[i].length));
     }
 }
 
diff --git a/libs/surfaceflinger/Transform.cpp b/libs/surfaceflinger/Transform.cpp
index e8b0f45..1501536 100644
--- a/libs/surfaceflinger/Transform.cpp
+++ b/libs/surfaceflinger/Transform.cpp
@@ -177,10 +177,10 @@
     Region out;
     if (UNLIKELY(transformed())) {
         if (LIKELY(preserveRects())) {
-            Rect r;
-            Region::iterator iterator(reg);
-            while (iterator.iterate(&r)) {
-                out.orSelf(transform(r));
+            Region::const_iterator it = reg.begin();
+            Region::const_iterator const end = reg.end();
+            while (it != end) {
+                out.orSelf(transform(*it++));
             }
         } else {
             out.set(transform(reg.bounds()));
diff --git a/libs/surfaceflinger/GPUHardware/GPUHardware.cpp b/libs/surfaceflinger/purgatory/GPUHardware/GPUHardware.cpp
similarity index 98%
rename from libs/surfaceflinger/GPUHardware/GPUHardware.cpp
rename to libs/surfaceflinger/purgatory/GPUHardware/GPUHardware.cpp
index 7168bf2..2de628b 100644
--- a/libs/surfaceflinger/GPUHardware/GPUHardware.cpp
+++ b/libs/surfaceflinger/purgatory/GPUHardware/GPUHardware.cpp
@@ -30,12 +30,12 @@
 #include <cutils/log.h>
 #include <cutils/properties.h>
 
-#include <utils/IBinder.h>
-#include <utils/MemoryDealer.h>
-#include <utils/MemoryBase.h>
-#include <utils/MemoryHeapPmem.h>
-#include <utils/MemoryHeapBase.h>
-#include <utils/IPCThreadState.h>
+#include <binder/IBinder.h>
+#include <binder/MemoryDealer.h>
+#include <binder/MemoryBase.h>
+#include <binder/MemoryHeapPmem.h>
+#include <binder/MemoryHeapBase.h>
+#include <binder/IPCThreadState.h>
 #include <utils/StopWatch.h>
 
 #include <ui/ISurfaceComposer.h>
diff --git a/libs/surfaceflinger/GPUHardware/GPUHardware.h b/libs/surfaceflinger/purgatory/GPUHardware/GPUHardware.h
similarity index 100%
rename from libs/surfaceflinger/GPUHardware/GPUHardware.h
rename to libs/surfaceflinger/purgatory/GPUHardware/GPUHardware.h
diff --git a/libs/surfaceflinger/purgatory/LayerOrientationAnim.cpp b/libs/surfaceflinger/purgatory/LayerOrientationAnim.cpp
new file mode 100644
index 0000000..41c42d1
--- /dev/null
+++ b/libs/surfaceflinger/purgatory/LayerOrientationAnim.cpp
@@ -0,0 +1,272 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "SurfaceFlinger"
+
+#include <stdlib.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/Log.h>
+#include <utils/StopWatch.h>
+
+#include "BlurFilter.h"
+#include "LayerBase.h"
+#include "LayerOrientationAnim.h"
+#include "SurfaceFlinger.h"
+#include "DisplayHardware/DisplayHardware.h"
+#include "OrientationAnimation.h"
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+const uint32_t LayerOrientationAnim::typeInfo = LayerBase::typeInfo | 0x80;
+const char* const LayerOrientationAnim::typeID = "LayerOrientationAnim";
+
+// ---------------------------------------------------------------------------
+
+// Animation...
+const float DURATION = ms2ns(200);
+const float BOUNCES_PER_SECOND = 0.5f;
+//const float BOUNCES_AMPLITUDE = 1.0f/16.0f;
+const float BOUNCES_AMPLITUDE = 0;
+const float DIM_TARGET = 0.40f;
+//#define INTERPOLATED_TIME(_t)   ((_t)*(_t))
+#define INTERPOLATED_TIME(_t)   (_t)
+
+// ---------------------------------------------------------------------------
+
+LayerOrientationAnim::LayerOrientationAnim(
+        SurfaceFlinger* flinger, DisplayID display, 
+        OrientationAnimation* anim, 
+        const sp<Buffer>& bitmapIn,
+        const sp<Buffer>& bitmapOut)
+    : LayerOrientationAnimBase(flinger, display), mAnim(anim), 
+      mBitmapIn(bitmapIn), mBitmapOut(bitmapOut), 
+      mTextureName(-1), mTextureNameIn(-1)
+{
+    // blur that texture. 
+    mStartTime = systemTime();
+    mFinishTime = 0;
+    mOrientationCompleted = false;
+    mFirstRedraw = false;
+    mLastNormalizedTime = 0;
+    mNeedsBlending = false;
+    mAlphaInLerp.set(1.0f, DIM_TARGET);
+    mAlphaOutLerp.set(0.5f, 1.0f);
+}
+
+LayerOrientationAnim::~LayerOrientationAnim()
+{
+    if (mTextureName != -1U) {
+        glDeleteTextures(1, &mTextureName);
+    }
+    if (mTextureNameIn != -1U) {
+        glDeleteTextures(1, &mTextureNameIn);
+    }
+}
+
+bool LayerOrientationAnim::needsBlending() const 
+{
+    return mNeedsBlending; 
+}
+
+Point LayerOrientationAnim::getPhysicalSize() const
+{
+    const GraphicPlane& plane(graphicPlane(0));
+    const DisplayHardware& hw(plane.displayHardware());
+    return Point(hw.getWidth(), hw.getHeight());
+}
+
+void LayerOrientationAnim::validateVisibility(const Transform&)
+{
+    const Layer::State& s(drawingState());
+    const Transform tr(s.transform);
+    const Point size(getPhysicalSize());
+    uint32_t w = size.x;
+    uint32_t h = size.y;
+    mTransformedBounds = tr.makeBounds(w, h);
+    mLeft = tr.tx();
+    mTop  = tr.ty();
+    transparentRegionScreen.clear();
+    mTransformed = true;
+}
+
+void LayerOrientationAnim::onOrientationCompleted()
+{
+    mFinishTime = systemTime();
+    mOrientationCompleted = true;
+    mFirstRedraw = true;
+    mNeedsBlending = true;
+    mFlinger->invalidateLayerVisibility(this);
+}
+
+void LayerOrientationAnim::onDraw(const Region& clip) const
+{
+    const nsecs_t now = systemTime();
+    float alphaIn, alphaOut;
+    
+    if (mOrientationCompleted) {
+        if (mFirstRedraw) {
+            mFirstRedraw = false;
+            
+            // make a copy of what's on screen
+            copybit_image_t image;
+            mBitmapOut->getBitmapSurface(&image);
+            const DisplayHardware& hw(graphicPlane(0).displayHardware());
+            hw.copyBackToImage(image);
+
+            // and erase the screen for this round
+            glDisable(GL_BLEND);
+            glDisable(GL_DITHER);
+            glDisable(GL_SCISSOR_TEST);
+            glClearColor(0,0,0,0);
+            glClear(GL_COLOR_BUFFER_BIT);
+            
+            // FIXME: code below is gross
+            mNeedsBlending = false;
+            LayerOrientationAnim* self(const_cast<LayerOrientationAnim*>(this));
+            mFlinger->invalidateLayerVisibility(self);
+        }
+
+        // make sure pick-up where we left off
+        const float duration = DURATION * mLastNormalizedTime;
+        const float normalizedTime = (float(now - mFinishTime) / duration);
+        if (normalizedTime <= 1.0f) {
+            const float interpolatedTime = INTERPOLATED_TIME(normalizedTime);
+            alphaIn = mAlphaInLerp.getOut();
+            alphaOut = mAlphaOutLerp(interpolatedTime);
+        } else {
+            mAnim->onAnimationFinished();
+            alphaIn = mAlphaInLerp.getOut();
+            alphaOut = mAlphaOutLerp.getOut();
+        }
+    } else {
+        const float normalizedTime = float(now - mStartTime) / DURATION;
+        if (normalizedTime <= 1.0f) {
+            mLastNormalizedTime = normalizedTime;
+            const float interpolatedTime = INTERPOLATED_TIME(normalizedTime);
+            alphaIn = mAlphaInLerp(interpolatedTime);
+            alphaOut = 0.0f;
+        } else {
+            mLastNormalizedTime = 1.0f;
+            const float to_seconds = DURATION / seconds(1);
+            alphaIn = mAlphaInLerp.getOut();
+            if (BOUNCES_AMPLITUDE > 0.0f) {
+                const float phi = BOUNCES_PER_SECOND * 
+                        (((normalizedTime - 1.0f) * to_seconds)*M_PI*2);
+                if (alphaIn > 1.0f) alphaIn = 1.0f;
+                else if (alphaIn < 0.0f) alphaIn = 0.0f;
+                alphaIn += BOUNCES_AMPLITUDE * (1.0f - cosf(phi));
+            }
+            alphaOut = 0.0f;
+        }
+        mAlphaOutLerp.setIn(alphaIn);
+    }
+    drawScaled(1.0f, alphaIn, alphaOut);
+}
+
+void LayerOrientationAnim::drawScaled(float scale, float alphaIn, float alphaOut) const
+{
+    copybit_image_t dst;
+    const GraphicPlane& plane(graphicPlane(0));
+    const DisplayHardware& hw(plane.displayHardware());
+    //hw.getDisplaySurface(&dst);
+
+    // clear screen
+    // TODO: with update on demand, we may be able 
+    // to not erase the screen at all during the animation 
+    if (!mOrientationCompleted) {
+        if (scale==1.0f && (alphaIn>=1.0f || alphaOut>=1.0f)) {
+            // we don't need to erase the screen in that case
+        } else {
+            glDisable(GL_BLEND);
+            glDisable(GL_DITHER);
+            glDisable(GL_SCISSOR_TEST);
+            glClearColor(0,0,0,0);
+            glClear(GL_COLOR_BUFFER_BIT);
+        }
+    }
+    
+    copybit_image_t src;
+    mBitmapIn->getBitmapSurface(&src);
+
+    copybit_image_t srcOut;
+    mBitmapOut->getBitmapSurface(&srcOut);
+
+    const int w = dst.w*scale; 
+    const int h = dst.h*scale; 
+    const int xc = uint32_t(dst.w-w)/2;
+    const int yc = uint32_t(dst.h-h)/2;
+    const copybit_rect_t drect = { xc, yc, xc+w, yc+h }; 
+    const copybit_rect_t srect = { 0, 0, src.w, src.h };
+    const Region reg(Rect( drect.l, drect.t, drect.r, drect.b ));
+
+    GGLSurface t;
+    t.version = sizeof(GGLSurface);
+    t.width  = src.w;
+    t.height = src.h;
+    t.stride = src.w;
+    t.vstride= src.h;
+    t.format = src.format;
+    t.data = (GGLubyte*)(intptr_t(src.base) + src.offset);
+
+    Transform tr;
+    tr.set(scale,0,0,scale);
+    tr.set(xc, yc);
+    
+    // FIXME: we should not access mVertices and mDrawingState like that,
+    // but since we control the animation, we know it's going to work okay.
+    // eventually we'd need a more formal way of doing things like this.
+    LayerOrientationAnim& self(const_cast<LayerOrientationAnim&>(*this));
+    tr.transform(self.mVertices[0], 0, 0);
+    tr.transform(self.mVertices[1], 0, src.h);
+    tr.transform(self.mVertices[2], src.w, src.h);
+    tr.transform(self.mVertices[3], src.w, 0);
+    if (!(mFlags & DisplayHardware::SLOW_CONFIG)) {
+        // Too slow to do this in software
+        self.mDrawingState.flags |= ISurfaceComposer::eLayerFilter;
+    }
+
+    if (alphaIn > 0.0f) {
+        t.data = (GGLubyte*)(intptr_t(src.base) + src.offset);
+        if (UNLIKELY(mTextureNameIn == -1LU)) {
+            mTextureNameIn = createTexture();
+            GLuint w=0, h=0;
+            const Region dirty(Rect(t.width, t.height));
+            loadTexture(dirty, mTextureNameIn, t, w, h);
+        }
+        self.mDrawingState.alpha = int(alphaIn*255);
+        drawWithOpenGL(reg, mTextureNameIn, t);
+    }
+
+    if (alphaOut > 0.0f) {
+        t.data = (GGLubyte*)(intptr_t(srcOut.base) + srcOut.offset);
+        if (UNLIKELY(mTextureName == -1LU)) {
+            mTextureName = createTexture();
+            GLuint w=0, h=0;
+            const Region dirty(Rect(t.width, t.height));
+            loadTexture(dirty, mTextureName, t, w, h);
+        }
+        self.mDrawingState.alpha = int(alphaOut*255);
+        drawWithOpenGL(reg, mTextureName, t);
+    }
+}
+
+// ---------------------------------------------------------------------------
+
+}; // namespace android
diff --git a/libs/surfaceflinger/LayerOrientationAnim.h b/libs/surfaceflinger/purgatory/LayerOrientationAnim.h
similarity index 67%
copy from libs/surfaceflinger/LayerOrientationAnim.h
copy to libs/surfaceflinger/purgatory/LayerOrientationAnim.h
index 12b6f1c..a1a2654 100644
--- a/libs/surfaceflinger/LayerOrientationAnim.h
+++ b/libs/surfaceflinger/purgatory/LayerOrientationAnim.h
@@ -20,7 +20,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 #include <utils/threads.h>
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 
 #include "LayerBase.h"
 #include "LayerBitmap.h"
@@ -52,8 +52,8 @@
     
                 LayerOrientationAnim(SurfaceFlinger* flinger, DisplayID display,
                         OrientationAnimation* anim, 
-                        const LayerBitmap& bitmapIn,
-                        const LayerBitmap& bitmapOut);
+                        const sp<Buffer>& bitmapIn,
+                        const sp<Buffer>& bitmapOut);
         virtual ~LayerOrientationAnim();
 
             void onOrientationCompleted();
@@ -64,13 +64,45 @@
     virtual bool needsBlending() const;
     virtual bool isSecure() const       { return false; }
 private:
+    void drawScaled(float scale, float alphaIn, float alphaOut) const;
+
+    class Lerp {
+        float in;
+        float outMinusIn;
+    public:
+        Lerp() : in(0), outMinusIn(0) { }
+        Lerp(float in, float out) : in(in), outMinusIn(out-in) { }
+        float getIn() const { return in; };
+        float getOut() const { return in + outMinusIn; }
+        void set(float in, float out) { 
+            this->in = in; 
+            this->outMinusIn = out-in; 
+        }
+        void setIn(float in) { 
+            this->in = in; 
+        }
+        void setOut(float out) { 
+            this->outMinusIn = out - this->in; 
+        }
+        float operator()(float t) const { 
+            return outMinusIn*t + in; 
+        }
+    };
+    
     OrientationAnimation* mAnim;
-    LayerBitmap mBitmapIn;
-    LayerBitmap mBitmapOut;
+    sp<Buffer> mBitmapIn;
+    sp<Buffer> mBitmapOut;
+    nsecs_t mStartTime;
+    nsecs_t mFinishTime;
     bool mOrientationCompleted;
+    mutable bool mFirstRedraw;
+    mutable float mLastNormalizedTime;
     mutable GLuint  mTextureName;
     mutable GLuint  mTextureNameIn;
     mutable bool mNeedsBlending;
+    
+    mutable Lerp mAlphaInLerp;
+    mutable Lerp mAlphaOutLerp;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/libs/surfaceflinger/purgatory/LayerOrientationAnimRotate.cpp b/libs/surfaceflinger/purgatory/LayerOrientationAnimRotate.cpp
new file mode 100644
index 0000000..dc6b632
--- /dev/null
+++ b/libs/surfaceflinger/purgatory/LayerOrientationAnimRotate.cpp
@@ -0,0 +1,269 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "SurfaceFlinger"
+
+#include <stdlib.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/Log.h>
+
+#include "LayerBase.h"
+#include "LayerOrientationAnim.h"
+#include "LayerOrientationAnimRotate.h"
+#include "SurfaceFlinger.h"
+#include "DisplayHardware/DisplayHardware.h"
+#include "OrientationAnimation.h"
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+const uint32_t LayerOrientationAnimRotate::typeInfo = LayerBase::typeInfo | 0x100;
+const char* const LayerOrientationAnimRotate::typeID = "LayerOrientationAnimRotate";
+
+// ---------------------------------------------------------------------------
+
+const float ROTATION = M_PI * 0.5f;
+const float ROTATION_FACTOR = 1.0f; // 1.0 or 2.0
+const float DURATION = ms2ns(200);
+const float BOUNCES_PER_SECOND = 0.8;
+const float BOUNCES_AMPLITUDE = (5.0f/180.f) * M_PI;
+
+LayerOrientationAnimRotate::LayerOrientationAnimRotate(
+        SurfaceFlinger* flinger, DisplayID display, 
+        OrientationAnimation* anim, 
+        const sp<Buffer>& bitmapIn,
+        const sp<Buffer>& bitmapOut)
+    : LayerOrientationAnimBase(flinger, display), mAnim(anim), 
+      mBitmapIn(bitmapIn), mBitmapOut(bitmapOut), 
+      mTextureName(-1), mTextureNameIn(-1)
+{
+    mStartTime = systemTime();
+    mFinishTime = 0;
+    mOrientationCompleted = false;
+    mFirstRedraw = false;
+    mLastNormalizedTime = 0;
+    mLastAngle = 0;
+    mLastScale = 0;
+    mNeedsBlending = false;
+    const GraphicPlane& plane(graphicPlane(0));
+    mOriginalTargetOrientation = plane.getOrientation(); 
+}
+
+LayerOrientationAnimRotate::~LayerOrientationAnimRotate()
+{
+    if (mTextureName != -1U) {
+        glDeleteTextures(1, &mTextureName);
+    }
+    if (mTextureNameIn != -1U) {
+        glDeleteTextures(1, &mTextureNameIn);
+    }
+}
+
+bool LayerOrientationAnimRotate::needsBlending() const 
+{
+    return mNeedsBlending; 
+}
+
+Point LayerOrientationAnimRotate::getPhysicalSize() const
+{
+    const GraphicPlane& plane(graphicPlane(0));
+    const DisplayHardware& hw(plane.displayHardware());
+    return Point(hw.getWidth(), hw.getHeight());
+}
+
+void LayerOrientationAnimRotate::validateVisibility(const Transform&)
+{
+    const Layer::State& s(drawingState());
+    const Transform tr(s.transform);
+    const Point size(getPhysicalSize());
+    uint32_t w = size.x;
+    uint32_t h = size.y;
+    mTransformedBounds = tr.makeBounds(w, h);
+    mLeft = tr.tx();
+    mTop  = tr.ty();
+    transparentRegionScreen.clear();
+    mTransformed = true;
+}
+
+void LayerOrientationAnimRotate::onOrientationCompleted()
+{
+    mFinishTime = systemTime();
+    mOrientationCompleted = true;
+    mFirstRedraw = true;
+    mNeedsBlending = true;
+    mFlinger->invalidateLayerVisibility(this);
+}
+
+void LayerOrientationAnimRotate::onDraw(const Region& clip) const
+{
+    // Animation...
+
+    const nsecs_t now = systemTime();
+    float angle, scale, alpha;
+    
+    if (mOrientationCompleted) {
+        if (mFirstRedraw) {
+            // make a copy of what's on screen
+            copybit_image_t image;
+            mBitmapIn->getBitmapSurface(&image);
+            const DisplayHardware& hw(graphicPlane(0).displayHardware());
+            hw.copyBackToImage(image);
+            
+            // FIXME: code below is gross
+            mFirstRedraw = false; 
+            mNeedsBlending = false;
+            LayerOrientationAnimRotate* self(const_cast<LayerOrientationAnimRotate*>(this));
+            mFlinger->invalidateLayerVisibility(self);
+        }
+
+        // make sure pick-up where we left off
+        const float duration = DURATION * mLastNormalizedTime;
+        const float normalizedTime = (float(now - mFinishTime) / duration);
+        if (normalizedTime <= 1.0f) {
+            const float squaredTime = normalizedTime*normalizedTime;
+            angle = (ROTATION*ROTATION_FACTOR - mLastAngle)*squaredTime + mLastAngle;
+            scale = (1.0f - mLastScale)*squaredTime + mLastScale;
+            alpha = normalizedTime;
+        } else {
+            mAnim->onAnimationFinished();
+            angle = ROTATION;
+            alpha = 1.0f;
+            scale = 1.0f;
+        }
+    } else {
+        // FIXME: works only for portrait framebuffers
+        const Point size(getPhysicalSize());
+        const float TARGET_SCALE = size.x * (1.0f / size.y);
+        const float normalizedTime = float(now - mStartTime) / DURATION;
+        if (normalizedTime <= 1.0f) {
+            mLastNormalizedTime = normalizedTime;
+            const float squaredTime = normalizedTime*normalizedTime;
+            angle = ROTATION * squaredTime;
+            scale = (TARGET_SCALE - 1.0f)*squaredTime + 1.0f;
+            alpha = 0;
+        } else {
+            mLastNormalizedTime = 1.0f;
+            angle = ROTATION;
+            if (BOUNCES_AMPLITUDE) {
+                const float to_seconds = DURATION / seconds(1);
+                const float phi = BOUNCES_PER_SECOND * 
+                (((normalizedTime - 1.0f) * to_seconds)*M_PI*2);
+                angle += BOUNCES_AMPLITUDE * sinf(phi);
+            }
+            scale = TARGET_SCALE;
+            alpha = 0;
+        }
+        mLastAngle = angle;
+        mLastScale = scale;
+    }
+    drawScaled(angle, scale, alpha);
+}
+
+void LayerOrientationAnimRotate::drawScaled(float f, float s, float alpha) const
+{
+    copybit_image_t dst;
+    const GraphicPlane& plane(graphicPlane(0));
+    const DisplayHardware& hw(plane.displayHardware());
+    //hw.getDisplaySurface(&dst);
+
+    // clear screen
+    // TODO: with update on demand, we may be able 
+    // to not erase the screen at all during the animation 
+    glDisable(GL_BLEND);
+    glDisable(GL_DITHER);
+    glDisable(GL_SCISSOR_TEST);
+    glClearColor(0,0,0,0);
+    glClear(GL_COLOR_BUFFER_BIT);
+    
+    const int w = dst.w; 
+    const int h = dst.h; 
+
+    copybit_image_t src;
+    mBitmapIn->getBitmapSurface(&src);
+    const copybit_rect_t srect = { 0, 0, src.w, src.h };
+
+
+    GGLSurface t;
+    t.version = sizeof(GGLSurface);
+    t.width  = src.w;
+    t.height = src.h;
+    t.stride = src.w;
+    t.vstride= src.h;
+    t.format = src.format;
+    t.data = (GGLubyte*)(intptr_t(src.base) + src.offset);
+
+    if (!mOriginalTargetOrientation) {
+        f = -f;
+    }
+
+    Transform tr;
+    tr.set(f, w*0.5f, h*0.5f);
+    tr.scale(s, w*0.5f, h*0.5f);
+
+    // FIXME: we should not access mVertices and mDrawingState like that,
+    // but since we control the animation, we know it's going to work okay.
+    // eventually we'd need a more formal way of doing things like this.
+    LayerOrientationAnimRotate& self(const_cast<LayerOrientationAnimRotate&>(*this));
+    tr.transform(self.mVertices[0], 0, 0);
+    tr.transform(self.mVertices[1], 0, src.h);
+    tr.transform(self.mVertices[2], src.w, src.h);
+    tr.transform(self.mVertices[3], src.w, 0);
+
+    if (!(mFlags & DisplayHardware::SLOW_CONFIG)) {
+        // Too slow to do this in software
+        self.mDrawingState.flags |= ISurfaceComposer::eLayerFilter;
+    }
+
+    if (UNLIKELY(mTextureName == -1LU)) {
+        mTextureName = createTexture();
+        GLuint w=0, h=0;
+        const Region dirty(Rect(t.width, t.height));
+        loadTexture(dirty, mTextureName, t, w, h);
+    }
+    self.mDrawingState.alpha = 255; //-int(alpha*255);
+    const Region clip(Rect( srect.l, srect.t, srect.r, srect.b ));
+    drawWithOpenGL(clip, mTextureName, t);
+    
+    if (alpha > 0) {
+        const float sign = (!mOriginalTargetOrientation) ? 1.0f : -1.0f;
+        tr.set(f + sign*(M_PI * 0.5f * ROTATION_FACTOR), w*0.5f, h*0.5f);
+        tr.scale(s, w*0.5f, h*0.5f);
+        tr.transform(self.mVertices[0], 0, 0);
+        tr.transform(self.mVertices[1], 0, src.h);
+        tr.transform(self.mVertices[2], src.w, src.h);
+        tr.transform(self.mVertices[3], src.w, 0);
+
+        copybit_image_t src;
+        mBitmapIn->getBitmapSurface(&src);
+        t.data = (GGLubyte*)(intptr_t(src.base) + src.offset);
+        if (UNLIKELY(mTextureNameIn == -1LU)) {
+            mTextureNameIn = createTexture();
+            GLuint w=0, h=0;
+            const Region dirty(Rect(t.width, t.height));
+            loadTexture(dirty, mTextureNameIn, t, w, h);
+        }
+        self.mDrawingState.alpha = int(alpha*255);
+        const Region clip(Rect( srect.l, srect.t, srect.r, srect.b ));
+        drawWithOpenGL(clip, mTextureNameIn, t);
+    }
+}
+
+// ---------------------------------------------------------------------------
+
+}; // namespace android
diff --git a/libs/surfaceflinger/LayerOrientationAnim.h b/libs/surfaceflinger/purgatory/LayerOrientationAnimRotate.h
similarity index 67%
rename from libs/surfaceflinger/LayerOrientationAnim.h
rename to libs/surfaceflinger/purgatory/LayerOrientationAnimRotate.h
index 12b6f1c..a88eec0 100644
--- a/libs/surfaceflinger/LayerOrientationAnim.h
+++ b/libs/surfaceflinger/purgatory/LayerOrientationAnimRotate.h
@@ -14,13 +14,13 @@
  * limitations under the License.
  */
 
-#ifndef ANDROID_LAYER_ORIENTATION_ANIM_H
-#define ANDROID_LAYER_ORIENTATION_ANIM_H
+#ifndef ANDROID_LAYER_ORIENTATION_ANIM_ROTATE_H
+#define ANDROID_LAYER_ORIENTATION_ANIM_ROTATE_H
 
 #include <stdint.h>
 #include <sys/types.h>
 #include <utils/threads.h>
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 
 #include "LayerBase.h"
 #include "LayerBitmap.h"
@@ -30,19 +30,7 @@
 // ---------------------------------------------------------------------------
 class OrientationAnimation;
 
-
-class LayerOrientationAnimBase : public LayerBase
-{
-public:
-    LayerOrientationAnimBase(SurfaceFlinger* flinger, DisplayID display)
-        : LayerBase(flinger, display) {
-    }
-    virtual void onOrientationCompleted() = 0;
-};
-
-// ---------------------------------------------------------------------------
-
-class LayerOrientationAnim : public LayerOrientationAnimBase
+class LayerOrientationAnimRotate : public LayerOrientationAnimBase
 {
 public:    
     static const uint32_t typeInfo;
@@ -50,11 +38,11 @@
     virtual char const* getTypeID() const { return typeID; }
     virtual uint32_t getTypeInfo() const { return typeInfo; }
     
-                LayerOrientationAnim(SurfaceFlinger* flinger, DisplayID display,
+    LayerOrientationAnimRotate(SurfaceFlinger* flinger, DisplayID display,
                         OrientationAnimation* anim, 
-                        const LayerBitmap& bitmapIn,
-                        const LayerBitmap& bitmapOut);
-        virtual ~LayerOrientationAnim();
+                        const sp<Buffer>& bitmapIn,
+                        const sp<Buffer>& bitmapOut);
+        virtual ~LayerOrientationAnimRotate();
 
             void onOrientationCompleted();
 
@@ -64,10 +52,19 @@
     virtual bool needsBlending() const;
     virtual bool isSecure() const       { return false; }
 private:
+    void drawScaled(float angle, float scale, float alpha) const;
+    
     OrientationAnimation* mAnim;
-    LayerBitmap mBitmapIn;
-    LayerBitmap mBitmapOut;
+    sp<Buffer> mBitmapIn;
+    sp<Buffer> mBitmapOut;
+    nsecs_t mStartTime;
+    nsecs_t mFinishTime;
     bool mOrientationCompleted;
+    int mOriginalTargetOrientation;
+    mutable bool mFirstRedraw;
+    mutable float mLastNormalizedTime;
+    mutable float mLastAngle;
+    mutable float mLastScale;
     mutable GLuint  mTextureName;
     mutable GLuint  mTextureNameIn;
     mutable bool mNeedsBlending;
@@ -77,4 +74,4 @@
 
 }; // namespace android
 
-#endif // ANDROID_LAYER_ORIENTATION_ANIM_H
+#endif // ANDROID_LAYER_ORIENTATION_ANIM_ROTATE_H
diff --git a/libs/surfaceflinger/OrientationAnimation.cpp b/libs/surfaceflinger/purgatory/OrientationAnimation.cpp
similarity index 81%
rename from libs/surfaceflinger/OrientationAnimation.cpp
rename to libs/surfaceflinger/purgatory/OrientationAnimation.cpp
index 12c0eef..a6c9c28 100644
--- a/libs/surfaceflinger/OrientationAnimation.cpp
+++ b/libs/surfaceflinger/purgatory/OrientationAnimation.cpp
@@ -14,16 +14,14 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <stdint.h>
 #include <sys/types.h>
 #include <limits.h>
 
 #include "LayerOrientationAnim.h"
+#include "LayerOrientationAnimRotate.h"
 #include "OrientationAnimation.h"
 #include "SurfaceFlinger.h"
-#include "VRamHeap.h"
 
 #include "DisplayHardware/DisplayHardware.h"
 
@@ -34,9 +32,6 @@
 OrientationAnimation::OrientationAnimation(const sp<SurfaceFlinger>& flinger)
     : mFlinger(flinger), mLayerOrientationAnim(NULL), mState(DONE)
 {
-    // allocate a memory-dealer for this the first time
-    mTemporaryDealer = mFlinger->getSurfaceHeapManager()->createHeap(
-            ISurfaceComposer::eHardware);
 }
 
 OrientationAnimation::~OrientationAnimation()
@@ -97,22 +92,22 @@
     const uint32_t w = hw.getWidth();
     const uint32_t h = hw.getHeight();
 
-    LayerBitmap bitmap;
-    bitmap.init(mTemporaryDealer);
-    bitmap.setBits(w, h, 1, hw.getFormat());
-
-    LayerBitmap bitmapIn;
-    bitmapIn.init(mTemporaryDealer);
-    bitmapIn.setBits(w, h, 1, hw.getFormat());
+    sp<Buffer> bitmap = new Buffer(w, h, hw.getFormat());
+    sp<Buffer> bitmapIn = new Buffer(w, h, hw.getFormat());
 
     copybit_image_t front;
-    bitmap.getBitmapSurface(&front);
-    hw.copyFrontToImage(front);
+    bitmap->getBitmapSurface(&front);
+    hw.copyFrontToImage(front); // FIXME: we need an extension to do this
 
-    LayerOrientationAnimBase* l;
+    sp<LayerOrientationAnimBase> l;
     
-    l = new LayerOrientationAnim(
-            mFlinger.get(), 0, this, bitmap, bitmapIn);
+    if (mType & 0x80) {
+        l = new LayerOrientationAnimRotate(
+                mFlinger.get(), 0, this, bitmap, bitmapIn);
+    } else {
+        l = new LayerOrientationAnim(
+                mFlinger.get(), 0, this, bitmap, bitmapIn);
+    }
 
     l->initStates(w, h, 0);
     l->setLayer(INT_MAX-1);
@@ -131,7 +126,7 @@
         return true;
         
     }
-    //mLayerOrientationAnim->invalidate();
+    mLayerOrientationAnim->invalidate();
     return false;
 }
 
@@ -146,7 +141,7 @@
 {
     mState = DONE;
     mFlinger->removeLayer(mLayerOrientationAnim);
-    mLayerOrientationAnim = NULL;
+    mLayerOrientationAnim.clear();
     return true;
 }
 
diff --git a/libs/surfaceflinger/OrientationAnimation.h b/libs/surfaceflinger/purgatory/OrientationAnimation.h
similarity index 95%
rename from libs/surfaceflinger/OrientationAnimation.h
rename to libs/surfaceflinger/purgatory/OrientationAnimation.h
index cafa38d..8ba6621 100644
--- a/libs/surfaceflinger/OrientationAnimation.h
+++ b/libs/surfaceflinger/purgatory/OrientationAnimation.h
@@ -72,8 +72,7 @@
     bool finished();
 
     sp<SurfaceFlinger> mFlinger;
-    sp<MemoryDealer> mTemporaryDealer;
-    LayerOrientationAnimBase* mLayerOrientationAnim;
+    sp< LayerOrientationAnimBase > mLayerOrientationAnim;
     int mState;
     uint32_t mType;
 };
diff --git a/libs/surfaceflinger/VRamHeap.cpp b/libs/surfaceflinger/purgatory/VRamHeap.cpp
similarity index 97%
rename from libs/surfaceflinger/VRamHeap.cpp
rename to libs/surfaceflinger/purgatory/VRamHeap.cpp
index 5f633bd..f3ed790 100644
--- a/libs/surfaceflinger/VRamHeap.cpp
+++ b/libs/surfaceflinger/purgatory/VRamHeap.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlinger"
-
 #include <stdlib.h>
 #include <stdio.h>
 #include <stdint.h>
@@ -35,8 +33,6 @@
 #include <utils/MemoryHeapPmem.h>
 #include <utils/MemoryHeapBase.h>
 
-#include <EGL/eglnatives.h>
-
 #include "GPUHardware/GPUHardware.h"
 #include "SurfaceFlinger.h"
 #include "VRamHeap.h"
@@ -100,7 +96,7 @@
         }
     }
 
-    if ((flags & ISurfaceComposer::eGPU) && (mFlinger->getGPU() != 0)) {
+    if (flags & ISurfaceComposer::eGPU) {
         // FIXME: this is msm7201A specific, where gpu surfaces may not be secure
         if (!(flags & ISurfaceComposer::eSecure)) {
             // if GPU doesn't work, we try eHardware
diff --git a/libs/surfaceflinger/VRamHeap.h b/libs/surfaceflinger/purgatory/VRamHeap.h
similarity index 100%
rename from libs/surfaceflinger/VRamHeap.h
rename to libs/surfaceflinger/purgatory/VRamHeap.h
diff --git a/libs/surfaceflinger/tests/overlays/overlays.cpp b/libs/surfaceflinger/tests/overlays/overlays.cpp
index f3c046f..0b9322e 100644
--- a/libs/surfaceflinger/tests/overlays/overlays.cpp
+++ b/libs/surfaceflinger/tests/overlays/overlays.cpp
@@ -1,6 +1,6 @@
-#include <utils/IPCThreadState.h>
-#include <utils/ProcessState.h>
-#include <utils/IServiceManager.h>
+#include <binder/IPCThreadState.h>
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
 #include <utils/Log.h>
 
 #include <ui/Surface.h>
diff --git a/libs/surfaceflinger/tests/resize/Android.mk b/libs/surfaceflinger/tests/resize/Android.mk
new file mode 100644
index 0000000..ef1532f
--- /dev/null
+++ b/libs/surfaceflinger/tests/resize/Android.mk
@@ -0,0 +1,16 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+	resize.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+	libcutils \
+	libutils \
+    libui
+
+LOCAL_MODULE:= test-resize
+
+LOCAL_MODULE_TAGS := tests
+
+include $(BUILD_EXECUTABLE)
diff --git a/libs/surfaceflinger/tests/resize/resize.cpp b/libs/surfaceflinger/tests/resize/resize.cpp
new file mode 100644
index 0000000..21c6ab6
--- /dev/null
+++ b/libs/surfaceflinger/tests/resize/resize.cpp
@@ -0,0 +1,60 @@
+#include <cutils/memory.h>
+
+#include <utils/IPCThreadState.h>
+#include <utils/ProcessState.h>
+#include <utils/IServiceManager.h>
+#include <utils/Log.h>
+
+#include <ui/Surface.h>
+#include <ui/ISurface.h>
+#include <ui/Overlay.h>
+#include <ui/SurfaceComposerClient.h>
+
+using namespace android;
+
+namespace android {
+class Test {
+public:
+    static const sp<ISurface>& getISurface(const sp<Surface>& s) {
+        return s->getISurface();
+    }
+};
+};
+
+int main(int argc, char** argv)
+{
+    // set up the thread-pool
+    sp<ProcessState> proc(ProcessState::self());
+    ProcessState::self()->startThreadPool();
+
+    // create a client to surfaceflinger
+    sp<SurfaceComposerClient> client = new SurfaceComposerClient();
+    
+    // create pushbuffer surface
+    sp<Surface> surface = client->createSurface(getpid(), 0, 160, 240, 
+            PIXEL_FORMAT_RGB_565);
+
+
+    client->openTransaction();
+    surface->setLayer(100000);
+    client->closeTransaction();
+
+    Surface::SurfaceInfo info;
+    surface->lock(&info);
+    ssize_t bpr = info.s * bytesPerPixel(info.format);
+    android_memset16((uint16_t*)info.bits, 0xF800, bpr*info.h);
+    surface->unlockAndPost();
+
+    surface->lock(&info);
+    android_memset16((uint16_t*)info.bits, 0x07E0, bpr*info.h);
+    surface->unlockAndPost();
+
+    client->openTransaction();
+    surface->setSize(320, 240);
+    client->closeTransaction();
+
+    
+    IPCThreadState::self()->joinThreadPool();
+    
+    return 0;
+}
diff --git a/libs/ui/Android.mk b/libs/ui/Android.mk
index 7bbe38b..49939ca 100644
--- a/libs/ui/Android.mk
+++ b/libs/ui/Android.mk
@@ -2,12 +2,12 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= \
+	BufferMapper.cpp \
 	Camera.cpp \
 	CameraParameters.cpp \
-	EGLDisplaySurface.cpp \
-	EGLNativeWindowSurface.cpp \
 	EventHub.cpp \
 	EventRecurrence.cpp \
+	FramebufferNativeWindow.cpp \
 	KeyLayoutMap.cpp \
 	KeyCharacterMap.cpp \
 	ICamera.cpp \
@@ -27,9 +27,9 @@
 	SurfaceFlingerSynchro.cpp 
 
 LOCAL_SHARED_LIBRARIES := \
-	libcorecg \
 	libcutils \
 	libutils \
+	libbinder \
 	libpixelflinger \
 	libhardware \
 	libhardware_legacy
diff --git a/libs/ui/BufferMapper.cpp b/libs/ui/BufferMapper.cpp
new file mode 100644
index 0000000..92a9a86
--- /dev/null
+++ b/libs/ui/BufferMapper.cpp
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "BufferMapper"
+
+#include <stdint.h>
+#include <errno.h>
+
+#include <utils/Errors.h>
+#include <utils/Log.h>
+
+#include <ui/BufferMapper.h>
+#include <ui/Rect.h>
+
+#include <hardware/gralloc.h>
+
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+ANDROID_SINGLETON_STATIC_INSTANCE( BufferMapper )
+
+BufferMapper::BufferMapper()
+    : mAllocMod(0)
+{
+    hw_module_t const* module;
+    int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
+    LOGE_IF(err, "FATAL: can't find the %s module", GRALLOC_HARDWARE_MODULE_ID);
+    if (err == 0) {
+        mAllocMod = (gralloc_module_t const *)module;
+    }
+}
+
+status_t BufferMapper::registerBuffer(buffer_handle_t handle)
+{
+    status_t err = mAllocMod->registerBuffer(mAllocMod, handle);
+    LOGW_IF(err, "registerBuffer(%p) failed %d (%s)",
+            handle, err, strerror(-err));
+    return err;
+}
+
+status_t BufferMapper::unregisterBuffer(buffer_handle_t handle)
+{
+    status_t err = mAllocMod->unregisterBuffer(mAllocMod, handle);
+    LOGW_IF(err, "unregisterBuffer(%p) failed %d (%s)",
+            handle, err, strerror(-err));
+    return err;
+}
+
+status_t BufferMapper::lock(buffer_handle_t handle, 
+        int usage, const Rect& bounds, void** vaddr)
+{
+    status_t err = mAllocMod->lock(mAllocMod, handle, usage,
+            bounds.left, bounds.top, bounds.width(), bounds.height(), vaddr);
+    LOGW_IF(err, "unlock(...) failed %d (%s)", err, strerror(-err));
+    return err;
+}
+
+status_t BufferMapper::unlock(buffer_handle_t handle)
+{
+    status_t err = mAllocMod->unlock(mAllocMod, handle);
+    LOGW_IF(err, "unlock(...) failed %d (%s)", err, strerror(-err));
+    return err;
+}
+
+// ---------------------------------------------------------------------------
+}; // namespace android
diff --git a/libs/ui/Camera.cpp b/libs/ui/Camera.cpp
index 5015379..12a7725 100644
--- a/libs/ui/Camera.cpp
+++ b/libs/ui/Camera.cpp
@@ -19,9 +19,9 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "Camera"
 #include <utils/Log.h>
-#include <utils/IServiceManager.h>
+#include <binder/IServiceManager.h>
 #include <utils/threads.h>
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 #include <ui/Surface.h>
 #include <ui/Camera.h>
 #include <ui/ICameraService.h>
diff --git a/libs/ui/EGLDisplaySurface.cpp b/libs/ui/EGLDisplaySurface.cpp
deleted file mode 100644
index d06c98b..0000000
--- a/libs/ui/EGLDisplaySurface.cpp
+++ /dev/null
@@ -1,519 +0,0 @@
-/*
- **
- ** Copyright 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.
- */
-
-#define LOG_TAG "EGLDisplaySurface"
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <sys/types.h>
-#include <sys/mman.h>
-
-#include <cutils/log.h>
-#include <cutils/atomic.h>
-#include <cutils/properties.h>
-
-#include <hardware/copybit.h>
-
-#include <ui/SurfaceComposerClient.h>
-#include <ui/DisplayInfo.h>
-#include <ui/Rect.h>
-#include <ui/Region.h>
-#include <ui/EGLDisplaySurface.h>
-
-#if HAVE_ANDROID_OS
-#include <linux/msm_mdp.h>
-#endif
-
-#include <EGL/egl.h>
-
-#include <pixelflinger/format.h>
-
-
-// ----------------------------------------------------------------------------
-
-egl_native_window_t* android_createDisplaySurface()
-{
-    egl_native_window_t* s = new android::EGLDisplaySurface();
-    s->memory_type = NATIVE_MEMORY_TYPE_GPU;
-    return s;
-}
-
-#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
-#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
-
-// ----------------------------------------------------------------------------
-namespace android {
-// ----------------------------------------------------------------------------
-
-EGLDisplaySurface::EGLDisplaySurface()
-    : EGLNativeSurface<EGLDisplaySurface>()
-{
-    egl_native_window_t::version = sizeof(egl_native_window_t);
-    egl_native_window_t::ident = 0;
-    egl_native_window_t::incRef = &EGLDisplaySurface::hook_incRef;
-    egl_native_window_t::decRef = &EGLDisplaySurface::hook_decRef;
-    egl_native_window_t::swapBuffers = &EGLDisplaySurface::hook_swapBuffers;
-    egl_native_window_t::connect = 0;
-    egl_native_window_t::disconnect = 0;
-
-    mFb[0].data = 0;
-    mFb[1].data = 0;
-    mBlitEngine = 0;
-    egl_native_window_t::fd = mapFrameBuffer();
-    if (egl_native_window_t::fd >= 0) {
-        
-        hw_module_t const* module;
-        if (hw_get_module(COPYBIT_HARDWARE_MODULE_ID, &module) == 0) {
-            copybit_open(module, &mBlitEngine);
-        }
-        
-        const float in2mm = 25.4f;
-        float refreshRate = 1000000000000000LLU / (
-                float( mInfo.upper_margin + mInfo.lower_margin + mInfo.yres )
-                * ( mInfo.left_margin  + mInfo.right_margin + mInfo.xres )
-                * mInfo.pixclock);
-
-        const GGLSurface& buffer = mFb[1 - mIndex];
-        egl_native_window_t::width  = buffer.width;
-        egl_native_window_t::height = buffer.height;
-        egl_native_window_t::stride = buffer.stride;
-        egl_native_window_t::format = buffer.format;
-        egl_native_window_t::base   = intptr_t(mFb[0].data);
-        egl_native_window_t::offset =
-            intptr_t(buffer.data) - egl_native_window_t::base;
-        egl_native_window_t::flags  = 0;
-        egl_native_window_t::xdpi = (mInfo.xres * in2mm) / mInfo.width;
-        egl_native_window_t::ydpi = (mInfo.yres * in2mm) / mInfo.height;
-        egl_native_window_t::fps  = refreshRate;
-        egl_native_window_t::memory_type = NATIVE_MEMORY_TYPE_FB;
-        // no error, set the magic word
-        egl_native_window_t::magic = 0x600913;
-    }
-    mSwapCount = -1;
-    mPageFlipCount = 0;
-}
-
-EGLDisplaySurface::~EGLDisplaySurface()
-{
-    magic = 0;
-    copybit_close(mBlitEngine);
-    mBlitEngine = 0;
-    close(egl_native_window_t::fd);
-    munmap(mFb[0].data, mSize);
-    if (!(mFlags & PAGE_FLIP))
-        free((void*)mFb[1].data);
-}
-
-void EGLDisplaySurface::hook_incRef(NativeWindowType window) {
-    EGLDisplaySurface* that = static_cast<EGLDisplaySurface*>(window);
-    that->incStrong(that);
-}
-void EGLDisplaySurface::hook_decRef(NativeWindowType window) {
-    EGLDisplaySurface* that = static_cast<EGLDisplaySurface*>(window);
-    that->decStrong(that);
-}
-uint32_t EGLDisplaySurface::hook_swapBuffers(NativeWindowType window) {
-    EGLDisplaySurface* that = static_cast<EGLDisplaySurface*>(window);
-    return that->swapBuffers();
-}
-
-void EGLDisplaySurface::setSwapRectangle(int l, int t, int w, int h)
-{
-    mInfo.reserved[0] = 0x54445055; // "UPDT";
-    mInfo.reserved[1] = (uint16_t)l | ((uint32_t)t << 16);
-    mInfo.reserved[2] = (uint16_t)(l+w) | ((uint32_t)(t+h) << 16);
-}
-
-uint32_t EGLDisplaySurface::swapBuffers()
-{
-#define SHOW_FPS 0
-#if SHOW_FPS
-    nsecs_t now = systemTime();
-    if (mSwapCount == -1) {
-        mTime = now;
-        mSwapCount = 0;
-        mSleep = 0;
-    } else {
-        nsecs_t d = now-mTime;
-        if (d >= seconds(1)) {
-            double fps = (mSwapCount * double(seconds(1))) / double(d);
-            LOGD("%f fps, sleep=%d / frame",
-                    fps, (int)ns2us(mSleep / mSwapCount));
-            mSwapCount = 0;
-            mTime = now;
-            mSleep = 0;
-        } else {
-            mSwapCount++;
-        }
-    }
-#endif
-    /* If we can't do the page_flip, just copy the back buffer to the front */
-    if (!(mFlags & PAGE_FLIP)) {
-        memcpy(mFb[0].data, mFb[1].data, mInfo.xres*mInfo.yres*2);
-        return 0;
-    }
-
-    // do the actual flip
-    mIndex = 1 - mIndex;
-    mInfo.activate = FB_ACTIVATE_VBL;
-    mInfo.yoffset = mIndex ? mInfo.yres : 0;
-    if (ioctl(egl_native_window_t::fd, FBIOPUT_VSCREENINFO, &mInfo) == -1) {
-        LOGE("FBIOPUT_VSCREENINFO failed");
-        return 0;
-    }
-
-    /*
-     * this is a monstrous hack: Because the h/w accelerator is not able
-     * to render directly into the framebuffer, we need to copy its
-     * internal framebuffer out to the fb.
-     * oem[0] is used to access the fd of internal fb.
-     * All this is needed only in standalone mode, in SurfaceFlinger mode
-     * we control where the GPU renders.
-     * We do this only if we have copybit, since this hack is needed only
-     * with msm7k.
-     */
-    if (egl_native_window_t::memory_type == NATIVE_MEMORY_TYPE_GPU && oem[0] && mBlitEngine) {
-        copybit_device_t *copybit = mBlitEngine;
-        copybit_rect_t sdrect = { 0, 0,
-                egl_native_window_t::width, egl_native_window_t::height };
-        copybit_image_t dst = {
-                egl_native_window_t::width,
-                egl_native_window_t::height,
-                egl_native_window_t::format,
-                egl_native_window_t::offset,
-                (void*)egl_native_window_t::base,
-                egl_native_window_t::fd
-        };
-        copybit_image_t src = {
-                egl_native_window_t::width,
-                egl_native_window_t::height,
-                egl_native_window_t::format, // XXX: use proper format
-                egl_native_window_t::offset,
-                (void*)egl_native_window_t::base,  // XXX: use proper base
-                egl_native_window_t::oem[0]
-        };
-        region_iterator it(Region(Rect(
-                egl_native_window_t::width, egl_native_window_t::height)));
-        copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0);
-        copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 0xFF);
-        copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_DISABLE);
-        copybit->stretch(copybit, &dst, &src, &sdrect, &sdrect, &it);
-    }
-
-    // update the address of the buffer to draw to next
-    const GGLSurface& buffer = mFb[1 - mIndex];
-    egl_native_window_t::offset =
-        intptr_t(buffer.data) - egl_native_window_t::base;
-
-#if SHOW_FPS
-    mSleep += systemTime()-now;
-#endif
-
-    mPageFlipCount++;
-
-    // We don't support screen-size changes for now
-    return 0;
-}
-
-int32_t EGLDisplaySurface::getPageFlipCount() const
-{
-    return mPageFlipCount;
-}
-
-void EGLDisplaySurface::copyFrontToBack(const Region& copyback)
-{
-#if HAVE_ANDROID_OS
-    if (mBlitEngine) {
-        copybit_image_t dst = {
-                w:      egl_native_window_t::stride,
-                h:      egl_native_window_t::height,
-                format: egl_native_window_t::format,
-                offset: mFb[1-mIndex].data - mFb[0].data,
-                base:   (void*)egl_native_window_t::base,
-                fd:     egl_native_window_t::fd
-        };
-        copybit_image_t src = {
-                w:      egl_native_window_t::stride,
-                h:      egl_native_window_t::height,
-                format: egl_native_window_t::format,
-                offset: mFb[mIndex].data - mFb[0].data,
-                base:   (void*)egl_native_window_t::base,
-                fd:     egl_native_window_t::fd
-        };
-        region_iterator it(copyback);
-        mBlitEngine->blit(mBlitEngine, &dst, &src, &it);
-    } else
-#endif
-    {
-        /* no extra copy needed since we copied back to front instead of
-         * flipping */
-        if (!(mFlags & PAGE_FLIP)) {
-            return;
-        }
-
-        Region::iterator iterator(copyback);
-        if (iterator) {
-            Rect r;
-            uint8_t* const screen_src = mFb[  mIndex].data;
-            uint8_t* const screen_dst = mFb[1-mIndex].data;
-            const size_t bpp = bytesPerPixel(egl_native_window_t::format);
-            const size_t bpr = egl_native_window_t::stride * bpp;
-            while (iterator.iterate(&r)) {
-                ssize_t h = r.bottom - r.top;
-                if (h) {
-                    size_t size = (r.right - r.left) * bpp;
-                    size_t o = (r.left + egl_native_window_t::stride * r.top) * bpp;
-                    uint8_t* s = screen_src + o;
-                    uint8_t* d = screen_dst + o;
-                    if (size == bpr) {
-                        size *= h;
-                        h = 1;
-                    }
-                    do {
-                        memcpy(d, s, size);
-                        d += bpr;
-                        s += bpr;
-                    } while (--h > 0);
-                }
-            }
-        }
-    }
-}
-
-void EGLDisplaySurface::copyFrontToImage(const copybit_image_t& dst)
-{
-#if HAVE_ANDROID_OS
-    if (mBlitEngine) {
-        copybit_image_t src = {
-                w:      egl_native_window_t::stride,
-                h:      egl_native_window_t::height,
-                format: egl_native_window_t::format,
-                offset: mFb[mIndex].data - mFb[0].data,
-                base:   (void*)egl_native_window_t::base,
-                fd:     egl_native_window_t::fd
-        };
-        region_iterator it(Region(Rect(
-                egl_native_window_t::width, egl_native_window_t::height)));
-        mBlitEngine->blit(mBlitEngine, &dst, &src, &it);
-    } else
-#endif
-    {
-        uint8_t* const screen_src = mFb[  mIndex].data;
-        const size_t bpp = bytesPerPixel(egl_native_window_t::format);
-        const size_t bpr = egl_native_window_t::stride * bpp;
-        memcpy((char*)dst.base + dst.offset, screen_src,
-                bpr*egl_native_window_t::height);
-    }
-}
-
-void EGLDisplaySurface::copyBackToImage(const copybit_image_t& dst)
-{
-#if HAVE_ANDROID_OS
-    if (mBlitEngine) {
-        copybit_image_t src = {
-                w:      egl_native_window_t::stride,
-                h:      egl_native_window_t::height,
-                format: egl_native_window_t::format,
-                offset: mFb[1-mIndex].data - mFb[0].data,
-                base:   (void*)egl_native_window_t::base,
-                fd:     egl_native_window_t::fd
-        };
-        region_iterator it(Region(Rect(
-                egl_native_window_t::width, egl_native_window_t::height)));
-        mBlitEngine->blit(mBlitEngine, &dst, &src, &it);
-    } else
-#endif
-    {
-        uint8_t* const screen_src = mFb[1-mIndex].data;
-        const size_t bpp = bytesPerPixel(egl_native_window_t::format);
-        const size_t bpr = egl_native_window_t::stride * bpp;
-        memcpy((char*)dst.base + dst.offset, screen_src,
-                bpr*egl_native_window_t::height);
-    }
-}
-
-
-status_t EGLDisplaySurface::mapFrameBuffer()
-{
-    char const * const device_template[] = {
-            "/dev/graphics/fb%u",
-            "/dev/fb%u",
-            0 };
-    int fd = -1;
-    int i=0;
-    char name[64];
-    while ((fd==-1) && device_template[i]) {
-        snprintf(name, 64, device_template[i], 0);
-        fd = open(name, O_RDWR, 0);
-        i++;
-    }
-    if (fd < 0)
-        return -errno;
-
-    struct fb_fix_screeninfo finfo;
-    if (ioctl(fd, FBIOGET_FSCREENINFO, &finfo) == -1)
-        return -errno;
-
-    struct fb_var_screeninfo info;
-    if (ioctl(fd, FBIOGET_VSCREENINFO, &info) == -1)
-        return -errno;
-
-    info.reserved[0] = 0;
-    info.reserved[1] = 0;
-    info.reserved[2] = 0;
-    info.xoffset = 0;
-    info.yoffset = 0;
-    info.yres_virtual = info.yres * 2;
-    info.bits_per_pixel = 16;
-    /* Explicitly request 5/6/5 */
-    info.red.offset = 11;
-    info.red.length = 5;
-    info.green.offset = 5;
-    info.green.length = 6;
-    info.blue.offset = 0;
-    info.blue.length = 5;
-    info.transp.offset = 0;
-    info.transp.length = 0;
-    info.activate = FB_ACTIVATE_NOW;
-
-    uint32_t flags = PAGE_FLIP;
-    if (ioctl(fd, FBIOPUT_VSCREENINFO, &info) == -1) {
-        info.yres_virtual = info.yres;
-        flags &= ~PAGE_FLIP;
-        LOGW("FBIOPUT_VSCREENINFO failed, page flipping not supported");
-    }
-
-    if (info.yres_virtual < info.yres * 2) {
-        info.yres_virtual = info.yres;
-        flags &= ~PAGE_FLIP;
-        LOGW("page flipping not supported (yres_virtual=%d, requested=%d)",
-                info.yres_virtual, info.yres*2);
-    }
-
-    if (ioctl(fd, FBIOGET_VSCREENINFO, &info) == -1)
-        return -errno;
-
-    int refreshRate = 1000000000000000LLU /
-    (
-            uint64_t( info.upper_margin + info.lower_margin + info.yres )
-            * ( info.left_margin  + info.right_margin + info.xres )
-            * info.pixclock
-    );
-
-    if (refreshRate == 0) {
-        // bleagh, bad info from the driver
-        refreshRate = 60*1000;  // 60 Hz
-    }
-    if (int(info.width) <= 0 || int(info.height) <= 0) {
-        // the driver doesn't return that information
-        // default to 160 dpi
-        info.width  = ((info.xres * 25.4f)/160.0f + 0.5f);
-        info.height = ((info.yres * 25.4f)/160.0f + 0.5f);
-    }
-
-    float xdpi = (info.xres * 25.4f) / info.width;
-    float ydpi = (info.yres * 25.4f) / info.height;
-    float fps  = refreshRate / 1000.0f;
-
-    LOGI(   "using (fd=%d)\n"
-            "id           = %s\n"
-            "xres         = %d px\n"
-            "yres         = %d px\n"
-            "xres_virtual = %d px\n"
-            "yres_virtual = %d px\n"
-            "bpp          = %d\n"
-            "r            = %2u:%u\n"
-            "g            = %2u:%u\n"
-            "b            = %2u:%u\n",
-            fd,
-            finfo.id,
-            info.xres,
-            info.yres,
-            info.xres_virtual,
-            info.yres_virtual,
-            info.bits_per_pixel,
-            info.red.offset, info.red.length,
-            info.green.offset, info.green.length,
-            info.blue.offset, info.blue.length
-    );
-
-    LOGI(   "width        = %d mm (%f dpi)\n"
-            "height       = %d mm (%f dpi)\n"
-            "refresh rate = %.2f Hz\n",
-            info.width,  xdpi,
-            info.height, ydpi,
-            fps
-    );
-
-
-    if (ioctl(fd, FBIOGET_FSCREENINFO, &finfo) == -1)
-        return -errno;
-
-    if (finfo.smem_len <= 0)
-        return -errno;
-
-    /*
-     * Open and map the display.
-     */
-
-    void* buffer  = (uint16_t*) mmap(
-            0, finfo.smem_len,
-            PROT_READ | PROT_WRITE,
-            MAP_SHARED,
-            fd, 0);
-
-    if (buffer == MAP_FAILED)
-        return -errno;
-
-    // at least for now, always clear the fb
-    memset(buffer, 0, finfo.smem_len);
-
-    uint8_t* offscreen[2];
-    offscreen[0] = (uint8_t*)buffer;
-    if (flags & PAGE_FLIP) {
-        offscreen[1] = (uint8_t*)buffer + finfo.line_length*info.yres;
-    } else {
-        offscreen[1] = (uint8_t*)malloc(finfo.smem_len);
-        if (offscreen[1] == 0) {
-            munmap(buffer, finfo.smem_len);
-            return NO_MEMORY;
-        }
-    }
-
-    mFlags = flags;
-    mInfo = info;
-    mFinfo = finfo;
-    mSize = finfo.smem_len;
-    mIndex = 0;
-    for (int i=0 ; i<2 ; i++) {
-        mFb[i].version = sizeof(GGLSurface);
-        mFb[i].width   = info.xres;
-        mFb[i].height  = info.yres;
-        mFb[i].stride  = finfo.line_length / (info.bits_per_pixel >> 3);
-        mFb[i].data    = (GGLubyte*)(offscreen[i]);
-        mFb[i].format  = GGL_PIXEL_FORMAT_RGB_565;
-    }
-    return fd;
-}
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-// ----------------------------------------------------------------------------
diff --git a/libs/ui/EGLNativeWindowSurface.cpp b/libs/ui/EGLNativeWindowSurface.cpp
deleted file mode 100644
index f1071cf..0000000
--- a/libs/ui/EGLNativeWindowSurface.cpp
+++ /dev/null
@@ -1,161 +0,0 @@
-/* 
-**
-** Copyright 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.
-*/
-
-#define LOG_TAG "EGLNativeWindowSurface"
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <cutils/log.h>
-#include <cutils/atomic.h>
-
-#include <ui/SurfaceComposerClient.h>
-#include <ui/DisplayInfo.h>
-#include <ui/Rect.h>
-
-#include <EGL/egl.h>
-
-#include <pixelflinger/format.h>
-
-#include <ui/EGLNativeWindowSurface.h>
-
-// ----------------------------------------------------------------------------
-namespace android {
-// ----------------------------------------------------------------------------
-
-EGLNativeWindowSurface::EGLNativeWindowSurface(const sp<Surface>& surface)
-    : EGLNativeSurface<EGLNativeWindowSurface>(),
-    mSurface(surface), mConnected(false)
-{
-    egl_native_window_t::magic = 0x600913;
-    egl_native_window_t::version = sizeof(egl_native_window_t);
-    egl_native_window_t::ident = 0;
-    egl_native_window_t::incRef = &EGLNativeWindowSurface::hook_incRef;
-    egl_native_window_t::decRef = &EGLNativeWindowSurface::hook_decRef;
-    egl_native_window_t::swapBuffers = &EGLNativeWindowSurface::hook_swapBuffers;
-    egl_native_window_t::connect = &EGLNativeWindowSurface::hook_connect;
-    egl_native_window_t::disconnect = &EGLNativeWindowSurface::hook_disconnect;
-    
-    DisplayInfo dinfo;
-    SurfaceComposerClient::getDisplayInfo(0, &dinfo);
-    egl_native_window_t::xdpi = dinfo.xdpi;
-    egl_native_window_t::ydpi = dinfo.ydpi;
-    egl_native_window_t::fps  = dinfo.fps;
-    egl_native_window_t::flags= EGL_NATIVES_FLAG_DESTROY_BACKBUFFER;
-}
-
-EGLNativeWindowSurface::~EGLNativeWindowSurface()
-{
-    disconnect();
-    mSurface.clear();
-    magic = 0;
-}
-
-void EGLNativeWindowSurface::hook_incRef(NativeWindowType window)
-{
-    EGLNativeWindowSurface* that = static_cast<EGLNativeWindowSurface*>(window);
-    that->incStrong(that);
-}
-
-void EGLNativeWindowSurface::hook_decRef(NativeWindowType window)
-{
-    EGLNativeWindowSurface* that = static_cast<EGLNativeWindowSurface*>(window);
-    that->decStrong(that);
-}
-
-void EGLNativeWindowSurface::hook_connect(NativeWindowType window)
-{
-    EGLNativeWindowSurface* that = static_cast<EGLNativeWindowSurface*>(window);
-    that->connect();
-}
-
-void EGLNativeWindowSurface::hook_disconnect(NativeWindowType window)
-{
-    EGLNativeWindowSurface* that = static_cast<EGLNativeWindowSurface*>(window);
-    that->disconnect();
-}
-
-uint32_t EGLNativeWindowSurface::hook_swapBuffers(NativeWindowType window)
-{
-    EGLNativeWindowSurface* that = static_cast<EGLNativeWindowSurface*>(window);
-    return that->swapBuffers();
-}
-
-void EGLNativeWindowSurface::setSwapRectangle(int l, int t, int w, int h)
-{
-    mSurface->setSwapRectangle(Rect(l, t, l+w, t+h));
-}
-
-uint32_t EGLNativeWindowSurface::swapBuffers()
-{
-    const int w = egl_native_window_t::width;
-    const int h = egl_native_window_t::height;
-    const sp<Surface>& surface(mSurface);
-    Surface::SurfaceInfo info;
-    surface->unlockAndPost();
-    surface->lock(&info);
-    // update the address of the buffer to draw to next
-    egl_native_window_t::base   = intptr_t(info.base);
-    egl_native_window_t::offset = intptr_t(info.bits) - intptr_t(info.base);
-    
-    // update size if it changed
-    if (w != int(info.w) || h != int(info.h)) {
-        egl_native_window_t::width  = info.w;
-        egl_native_window_t::height = info.h;
-        egl_native_window_t::stride = info.bpr / bytesPerPixel(info.format);
-        egl_native_window_t::format = info.format;
-        return EGL_NATIVES_FLAG_SIZE_CHANGED;
-    }
-    return 0;
-}
-
-void EGLNativeWindowSurface::connect()
-{   
-    if (!mConnected) {
-        Surface::SurfaceInfo info;
-        mSurface->lock(&info);
-        mSurface->setSwapRectangle(Rect(info.w, info.h));
-        mConnected = true;
-
-        egl_native_window_t::width  = info.w;
-        egl_native_window_t::height = info.h;
-        egl_native_window_t::stride = info.bpr / bytesPerPixel(info.format);
-        egl_native_window_t::format = info.format;
-        egl_native_window_t::base   = intptr_t(info.base);
-        egl_native_window_t::offset = intptr_t(info.bits) - intptr_t(info.base);
-        // FIXME: egl_native_window_t::memory_type used to be set from
-        // mSurface, but we wanted to break this dependency. We set it to
-        // GPU because the software rendered doesn't care, but the h/w
-        // accelerator needs it. Eventually, this value should go away
-        // completely, since memory will be managed by OpenGL.
-        egl_native_window_t::memory_type = NATIVE_MEMORY_TYPE_GPU; 
-        egl_native_window_t::fd = 0;
-    }
-}
-
-void EGLNativeWindowSurface::disconnect()
-{
-    if (mConnected) {
-        mSurface->unlock();
-        mConnected = false;
-    }
-}
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-// ----------------------------------------------------------------------------
diff --git a/libs/ui/EventHub.cpp b/libs/ui/EventHub.cpp
index 7c2fc8e..59c9476 100644
--- a/libs/ui/EventHub.cpp
+++ b/libs/ui/EventHub.cpp
@@ -19,10 +19,10 @@
 #include <hardware_legacy/power.h>
 
 #include <cutils/properties.h>
-#include <utils/IServiceManager.h>
 #include <utils/Log.h>
 #include <utils/Timers.h>
-#include <utils.h>
+#include <utils/threads.h>
+#include <utils/Errors.h>
 
 #include <stdlib.h>
 #include <stdio.h>
@@ -83,7 +83,7 @@
     : mError(NO_INIT), mHaveFirstKeyboard(false), mFirstKeyboardId(0)
     , mDevicesById(0), mNumDevicesById(0)
     , mOpeningDevices(0), mClosingDevices(0)
-    , mDevices(0), mFDs(0), mFDCount(0)
+    , mDevices(0), mFDs(0), mFDCount(0), mOpened(false)
 {
     acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
 #ifdef EV_SW
@@ -100,11 +100,6 @@
     // we should free stuff here...
 }
 
-void EventHub::onFirstRef()
-{
-    mError = openPlatformInput() ? NO_ERROR : UNKNOWN_ERROR;
-}
-
 status_t EventHub::errorCheck() const
 {
     return mError;
@@ -239,6 +234,41 @@
     return 0;
 }
 
+status_t EventHub::scancodeToKeycode(int32_t deviceId, int scancode,
+        int32_t* outKeycode, uint32_t* outFlags) const
+{
+    AutoMutex _l(mLock);
+    device_t* device = getDevice(deviceId);
+    
+    if (device != NULL && device->layoutMap != NULL) {
+        status_t err = device->layoutMap->map(scancode, outKeycode, outFlags);
+        if (err == NO_ERROR) {
+            return NO_ERROR;
+        }
+    }
+    
+    if (mHaveFirstKeyboard) {
+        device = getDevice(mFirstKeyboardId);
+        
+        if (device != NULL && device->layoutMap != NULL) {
+            status_t err = device->layoutMap->map(scancode, outKeycode, outFlags);
+            if (err == NO_ERROR) {
+                return NO_ERROR;
+            }
+        }
+    }
+    
+    *outKeycode = 0;
+    *outFlags = 0;
+    return NAME_NOT_FOUND;
+}
+
+void EventHub::addExcludedDevice(const char* deviceName)
+{
+    String8 name(deviceName);
+    mExcludedDevices.push_back(name);
+}
+
 EventHub::device_t* EventHub::getDevice(int32_t deviceId) const
 {
     if (deviceId == 0) deviceId = mFirstKeyboardId;
@@ -276,7 +306,12 @@
 
     // Note that we only allow one caller to getEvent(), so don't need
     // to do locking here...  only when adding/removing devices.
-    
+
+    if (!mOpened) {
+        mError = openPlatformInput() ? NO_ERROR : UNKNOWN_ERROR;
+        mOpened = true;
+    }
+
     while(1) {
 
         // First, report any devices that had last been added/removed.
@@ -474,6 +509,20 @@
         //fprintf(stderr, "could not get device name for %s, %s\n", deviceName, strerror(errno));
         name[0] = '\0';
     }
+
+    // check to see if the device is on our excluded list
+    List<String8>::iterator iter = mExcludedDevices.begin();
+    List<String8>::iterator end = mExcludedDevices.end();
+    for ( ; iter != end; iter++) {
+        const char* test = *iter;
+        if (strcmp(name, test) == 0) {
+            LOGI("ignoring event id %s driver %s\n", deviceName, test);
+            close(fd);
+            fd = -1;
+            return -1;
+        }
+    }
+
     if(ioctl(fd, EVIOCGPHYS(sizeof(location) - 1), &location) < 1) {
         //fprintf(stderr, "could not get location for %s, %s\n", deviceName, strerror(errno));
         location[0] = '\0';
@@ -733,6 +782,7 @@
     int event_pos = 0;
     struct inotify_event *event;
 
+LOGD("EventHub::read_notify nfd: %d\n", nfd);
     res = read(nfd, event_buf, sizeof(event_buf));
     if(res < (int)sizeof(*event)) {
         if(errno == EINTR)
diff --git a/libs/ui/FramebufferNativeWindow.cpp b/libs/ui/FramebufferNativeWindow.cpp
new file mode 100644
index 0000000..8c8fd6b
--- /dev/null
+++ b/libs/ui/FramebufferNativeWindow.cpp
@@ -0,0 +1,210 @@
+/* 
+**
+** Copyright 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.
+*/
+
+#define LOG_TAG "FramebufferNativeWindow"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <cutils/log.h>
+#include <cutils/atomic.h>
+#include <utils/threads.h>
+
+#include <ui/SurfaceComposerClient.h>
+#include <ui/Rect.h>
+#include <ui/FramebufferNativeWindow.h>
+
+#include <EGL/egl.h>
+
+#include <pixelflinger/format.h>
+#include <pixelflinger/pixelflinger.h>
+
+#include <hardware/hardware.h>
+#include <hardware/gralloc.h>
+
+#include <private/ui/android_natives_priv.h>
+
+// ----------------------------------------------------------------------------
+namespace android {
+// ----------------------------------------------------------------------------
+
+class NativeBuffer 
+    : public EGLNativeBase<
+        android_native_buffer_t, 
+        NativeBuffer, 
+        LightRefBase<NativeBuffer> >
+{
+public:
+    NativeBuffer(int w, int h, int f, int u) : BASE() {
+        android_native_buffer_t::width  = w;
+        android_native_buffer_t::height = h;
+        android_native_buffer_t::format = f;
+        android_native_buffer_t::usage  = u;
+    }
+private:
+    friend class LightRefBase<NativeBuffer>;    
+    ~NativeBuffer() { }; // this class cannot be overloaded
+};
+
+
+/*
+ * This implements the (main) framebuffer management. This class is used
+ * mostly by SurfaceFlinger, but also by command line GL application.
+ * 
+ * In fact this is an implementation of android_native_window_t on top of
+ * the framebuffer.
+ * 
+ * Currently it is pretty simple, it manages only two buffers (the front and 
+ * back buffer).
+ * 
+ */
+
+FramebufferNativeWindow::FramebufferNativeWindow() 
+    : BASE(), fbDev(0), grDev(0), mUpdateOnDemand(false)
+{
+    hw_module_t const* module;
+    if (hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module) == 0) {
+        int stride;
+        framebuffer_open(module, &fbDev);
+        gralloc_open(module, &grDev);
+        int err;
+
+        
+        mUpdateOnDemand = (fbDev->setUpdateRect != 0);
+        
+        // initialize the buffer FIFO
+        mNumBuffers = 2;
+        mNumFreeBuffers = 2;
+        mBufferHead = mNumBuffers-1;
+        buffers[0] = new NativeBuffer(
+                fbDev->width, fbDev->height, fbDev->format, GRALLOC_USAGE_HW_FB);
+        buffers[1] = new NativeBuffer(
+                fbDev->width, fbDev->height, fbDev->format, GRALLOC_USAGE_HW_FB);
+        
+        err = grDev->alloc(grDev,
+                fbDev->width, fbDev->height, fbDev->format, 
+                GRALLOC_USAGE_HW_FB, &buffers[0]->handle, &buffers[0]->stride);
+
+        LOGE_IF(err, "fb buffer 0 allocation failed w=%d, h=%d, err=%s",
+                fbDev->width, fbDev->height, strerror(-err));
+
+        err = grDev->alloc(grDev,
+                fbDev->width, fbDev->height, fbDev->format, 
+                GRALLOC_USAGE_HW_FB, &buffers[1]->handle, &buffers[1]->stride);
+
+        LOGE_IF(err, "fb buffer 1 allocation failed w=%d, h=%d, err=%s",
+                fbDev->width, fbDev->height, strerror(-err));
+    }
+
+    const_cast<uint32_t&>(android_native_window_t::flags) = fbDev->flags; 
+    const_cast<float&>(android_native_window_t::xdpi) = fbDev->xdpi;
+    const_cast<float&>(android_native_window_t::ydpi) = fbDev->ydpi;
+    const_cast<int&>(android_native_window_t::minSwapInterval) = 
+        fbDev->minSwapInterval;
+    const_cast<int&>(android_native_window_t::maxSwapInterval) = 
+        fbDev->maxSwapInterval;
+
+    android_native_window_t::setSwapInterval = setSwapInterval;
+    android_native_window_t::dequeueBuffer = dequeueBuffer;
+    android_native_window_t::lockBuffer = lockBuffer;
+    android_native_window_t::queueBuffer = queueBuffer;
+}
+
+FramebufferNativeWindow::~FramebufferNativeWindow() {
+    grDev->free(grDev, buffers[0]->handle);
+    grDev->free(grDev, buffers[1]->handle);
+    gralloc_close(grDev);
+    framebuffer_close(fbDev);
+}
+
+status_t FramebufferNativeWindow::setUpdateRectangle(const Rect& r) 
+{
+    if (!mUpdateOnDemand) {
+        return INVALID_OPERATION;
+    }
+    return fbDev->setUpdateRect(fbDev, r.left, r.top, r.width(), r.height());
+}
+
+int FramebufferNativeWindow::setSwapInterval(
+        android_native_window_t* window, int interval) 
+{
+    framebuffer_device_t* fb = getSelf(window)->fbDev;
+    return fb->setSwapInterval(fb, interval);
+}
+
+int FramebufferNativeWindow::dequeueBuffer(android_native_window_t* window, 
+        android_native_buffer_t** buffer)
+{
+    FramebufferNativeWindow* self = getSelf(window);
+    Mutex::Autolock _l(self->mutex);
+    framebuffer_device_t* fb = self->fbDev;
+
+    // wait for a free buffer
+    while (!self->mNumFreeBuffers) {
+        self->mCondition.wait(self->mutex);
+    }
+    // get this buffer
+    self->mNumFreeBuffers--;
+    int index = self->mBufferHead++;
+    if (self->mBufferHead >= self->mNumBuffers)
+        self->mBufferHead = 0;
+
+    *buffer = self->buffers[index].get();
+
+    return 0;
+}
+
+int FramebufferNativeWindow::lockBuffer(android_native_window_t* window, 
+        android_native_buffer_t* buffer)
+{
+    FramebufferNativeWindow* self = getSelf(window);
+    Mutex::Autolock _l(self->mutex);
+
+    // wait that the buffer we're locking is not front anymore
+    while (self->front == buffer) {
+        self->mCondition.wait(self->mutex);
+    }
+
+    return NO_ERROR;
+}
+
+int FramebufferNativeWindow::queueBuffer(android_native_window_t* window, 
+        android_native_buffer_t* buffer)
+{
+    FramebufferNativeWindow* self = getSelf(window);
+    Mutex::Autolock _l(self->mutex);
+    framebuffer_device_t* fb = self->fbDev;
+    buffer_handle_t handle = static_cast<NativeBuffer*>(buffer)->handle;
+    int res = fb->post(fb, handle);
+    self->front = static_cast<NativeBuffer*>(buffer);
+    self->mNumFreeBuffers++;
+    self->mCondition.broadcast();
+    return res;
+}
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+// ----------------------------------------------------------------------------
+
+
+EGLNativeWindowType android_createDisplaySurface(void)
+{
+    return new android::FramebufferNativeWindow();
+}
+
diff --git a/libs/ui/ICamera.cpp b/libs/ui/ICamera.cpp
index ab0fef1..805c2ca 100644
--- a/libs/ui/ICamera.cpp
+++ b/libs/ui/ICamera.cpp
@@ -20,7 +20,7 @@
 #include <utils/Log.h>
 #include <stdint.h>
 #include <sys/types.h>
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 #include <ui/ICamera.h>
 
 namespace android {
@@ -221,12 +221,6 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnCamera::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/libs/ui/ICameraClient.cpp b/libs/ui/ICameraClient.cpp
index 59a6cf2..42b4da4 100644
--- a/libs/ui/ICameraClient.cpp
+++ b/libs/ui/ICameraClient.cpp
@@ -78,12 +78,6 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnCameraClient::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/libs/ui/ICameraService.cpp b/libs/ui/ICameraService.cpp
index e5687fe..84986c6 100644
--- a/libs/ui/ICameraService.cpp
+++ b/libs/ui/ICameraService.cpp
@@ -18,9 +18,9 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Parcel.h>
-#include <utils/IPCThreadState.h>
-#include <utils/IServiceManager.h>
+#include <binder/Parcel.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
 
 #include <ui/ICameraService.h>
 
@@ -49,12 +49,6 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnCameraService::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/libs/ui/IOverlay.cpp b/libs/ui/IOverlay.cpp
index fed47c2..65e6b4f 100644
--- a/libs/ui/IOverlay.cpp
+++ b/libs/ui/IOverlay.cpp
@@ -18,8 +18,8 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Parcel.h>
-#include <utils/IInterface.h>
+#include <binder/Parcel.h>
+#include <binder/IInterface.h>
 
 #include <ui/IOverlay.h>
 
@@ -49,12 +49,6 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnOverlay::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/libs/ui/ISurface.cpp b/libs/ui/ISurface.cpp
index d5e9f81..9fbae1e 100644
--- a/libs/ui/ISurface.cpp
+++ b/libs/ui/ISurface.cpp
@@ -14,19 +14,25 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "ISurface"
+
 #include <stdio.h>
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Parcel.h>
-#include <utils/IMemory.h>
+#include <binder/Parcel.h>
+#include <binder/IMemory.h>
 
 #include <ui/ISurface.h>
 #include <ui/Overlay.h>
+#include <ui/Surface.h>
 
+#include <private/ui/SurfaceBuffer.h>
 
 namespace android {
 
+// ----------------------------------------------------------------------
+
 ISurface::BufferHeap::BufferHeap() 
     : w(0), h(0), hor_stride(0), ver_stride(0), format(0),
     transform(0), flags(0) 
@@ -55,6 +61,8 @@
 {     
 }
 
+// ----------------------------------------------------------------------
+
 class BpSurface : public BpInterface<ISurface>
 {
 public:
@@ -63,6 +71,15 @@
     {
     }
 
+    virtual sp<SurfaceBuffer> getBuffer()
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(ISurface::getInterfaceDescriptor());
+        remote()->transact(GET_BUFFER, data, &reply);
+        sp<SurfaceBuffer> buffer = new SurfaceBuffer(reply);
+        return buffer;
+    }
+
     virtual status_t registerBuffers(const BufferHeap& buffers)
     {
         Parcel data, reply;
@@ -112,16 +129,15 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnSurface::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
     switch(code) {
+        case GET_BUFFER: {
+            CHECK_INTERFACE(ISurface, data, reply);
+            sp<SurfaceBuffer> buffer(getBuffer());
+            return SurfaceBuffer::writeToParcel(reply, buffer.get());
+        }
         case REGISTER_BUFFERS: {
             CHECK_INTERFACE(ISurface, data, reply);
             BufferHeap buffer;
diff --git a/libs/ui/ISurfaceComposer.cpp b/libs/ui/ISurfaceComposer.cpp
index 76597e1..fd2a590 100644
--- a/libs/ui/ISurfaceComposer.cpp
+++ b/libs/ui/ISurfaceComposer.cpp
@@ -20,10 +20,10 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Parcel.h>
-#include <utils/IMemory.h>
-#include <utils/IPCThreadState.h>
-#include <utils/IServiceManager.h>
+#include <binder/Parcel.h>
+#include <binder/IMemory.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
 
 #include <ui/ISurfaceComposer.h>
 #include <ui/DisplayInfo.h>
@@ -54,12 +54,12 @@
         return interface_cast<ISurfaceFlingerClient>(reply.readStrongBinder());
     }
 
-    virtual sp<IMemory> getCblk() const
+    virtual sp<IMemoryHeap> getCblk() const
     {
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
         remote()->transact(BnSurfaceComposer::GET_CBLK, data, &reply);
-        return interface_cast<IMemory>(reply.readStrongBinder());
+        return interface_cast<IMemoryHeap>(reply.readStrongBinder());
     }
 
     virtual void openGlobalTransaction()
@@ -114,36 +114,6 @@
         remote()->transact(BnSurfaceComposer::BOOT_FINISHED, data, &reply);
     }
 
-    virtual status_t requestGPU(
-            const sp<IGPUCallback>& callback, gpu_info_t* gpu)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
-        data.writeStrongBinder(callback->asBinder());
-        remote()->transact(BnSurfaceComposer::REQUEST_GPU, data, &reply);
-        gpu->regs = interface_cast<IMemory>(reply.readStrongBinder());
-        gpu->count = reply.readInt32();
-
-        // FIXME: for now, we don't dynamically allocate the regions array
-        size_t maxCount = sizeof(gpu->regions)/sizeof(*gpu->regions);
-        if (gpu->count > maxCount)
-            return BAD_VALUE;
-
-        for (size_t i=0 ; i<gpu->count ; i++) {
-            gpu->regions[i].region = interface_cast<IMemory>(reply.readStrongBinder());
-            gpu->regions[i].reserved = reply.readInt32();
-        }
-        return reply.readInt32();
-    }
-
-    virtual status_t revokeGPU()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
-        remote()->transact(BnSurfaceComposer::REVOKE_GPU, data, &reply);
-        return reply.readInt32();
-    }
-
     virtual void signal() const
     {
         Parcel data, reply;
@@ -156,124 +126,61 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnSurfaceComposer::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
-    status_t err = BnInterface<ISurfaceComposer>::onTransact(code, data, reply, flags);
-    if (err == NO_ERROR)
-        return err;
-
-    CHECK_INTERFACE(ISurfaceComposer, data, reply);
-
     switch(code) {
         case CREATE_CONNECTION: {
+            CHECK_INTERFACE(ISurfaceComposer, data, reply);
             sp<IBinder> b = createConnection()->asBinder();
             reply->writeStrongBinder(b);
         } break;
         case OPEN_GLOBAL_TRANSACTION: {
+            CHECK_INTERFACE(ISurfaceComposer, data, reply);
             openGlobalTransaction();
         } break;
         case CLOSE_GLOBAL_TRANSACTION: {
+            CHECK_INTERFACE(ISurfaceComposer, data, reply);
             closeGlobalTransaction();
         } break;
         case SET_ORIENTATION: {
+            CHECK_INTERFACE(ISurfaceComposer, data, reply);
             DisplayID dpy = data.readInt32();
             int orientation = data.readInt32();
             uint32_t flags = data.readInt32();
             reply->writeInt32( setOrientation(dpy, orientation, flags) );
         } break;
         case FREEZE_DISPLAY: {
+            CHECK_INTERFACE(ISurfaceComposer, data, reply);
             DisplayID dpy = data.readInt32();
             uint32_t flags = data.readInt32();
             reply->writeInt32( freezeDisplay(dpy, flags) );
         } break;
         case UNFREEZE_DISPLAY: {
+            CHECK_INTERFACE(ISurfaceComposer, data, reply);
             DisplayID dpy = data.readInt32();
             uint32_t flags = data.readInt32();
             reply->writeInt32( unfreezeDisplay(dpy, flags) );
         } break;
         case BOOT_FINISHED: {
+            CHECK_INTERFACE(ISurfaceComposer, data, reply);
             bootFinished();
         } break;
-        case REVOKE_GPU: {
-            reply->writeInt32( revokeGPU() );
-        } break;
         case SIGNAL: {
+            CHECK_INTERFACE(ISurfaceComposer, data, reply);
             signal();
         } break;
         case GET_CBLK: {
+            CHECK_INTERFACE(ISurfaceComposer, data, reply);
             sp<IBinder> b = getCblk()->asBinder();
             reply->writeStrongBinder(b);
         } break;
-        case REQUEST_GPU: {
-            // TODO: this should be protected by a permission
-            gpu_info_t info;
-            sp<IGPUCallback> callback
-                = interface_cast<IGPUCallback>(data.readStrongBinder());
-            status_t res = requestGPU(callback, &info);
-
-            // FIXME: for now, we don't dynamically allocate the regions array
-            size_t maxCount = sizeof(info.regions)/sizeof(*info.regions);
-            if (info.count > maxCount)
-                return BAD_VALUE;
-
-            reply->writeStrongBinder(info.regs->asBinder());
-            reply->writeInt32(info.count);
-            for (size_t i=0 ; i<info.count ; i++) {
-                reply->writeStrongBinder(info.regions[i].region->asBinder());
-                reply->writeInt32(info.regions[i].reserved);
-            }
-            reply->writeInt32(res);
-        } break;
         default:
-            return UNKNOWN_TRANSACTION;
+            return BBinder::onTransact(code, data, reply, flags);
     }
     return NO_ERROR;
 }
 
 // ----------------------------------------------------------------------------
 
-enum {
-    // Note: BOOT_FINISHED must remain this value, it is called by ActivityManagerService.
-    GPU_LOST = IBinder::FIRST_CALL_TRANSACTION
-};
-
-class BpGPUCallback : public BpInterface<IGPUCallback>
-{
-public:
-    BpGPUCallback(const sp<IBinder>& impl)
-        : BpInterface<IGPUCallback>(impl)
-    {
-    }
-
-    virtual void gpuLost()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IGPUCallback::getInterfaceDescriptor());
-        remote()->transact(GPU_LOST, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-};
-
-IMPLEMENT_META_INTERFACE(GPUCallback, "android.ui.IGPUCallback");
-
-status_t BnGPUCallback::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch(code) {
-        case GPU_LOST: {
-            CHECK_INTERFACE(IGPUCallback, data, reply);
-            gpuLost();
-            return NO_ERROR;
-        } break;
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
 };
diff --git a/libs/ui/ISurfaceFlingerClient.cpp b/libs/ui/ISurfaceFlingerClient.cpp
index dab5f71..51e8422 100644
--- a/libs/ui/ISurfaceFlingerClient.cpp
+++ b/libs/ui/ISurfaceFlingerClient.cpp
@@ -21,10 +21,10 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Parcel.h>
-#include <utils/IMemory.h>
-#include <utils/IPCThreadState.h>
-#include <utils/IServiceManager.h>
+#include <binder/Parcel.h>
+#include <binder/IMemory.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
 
 #include <ui/ISurface.h>
 #include <ui/ISurfaceFlingerClient.h>
@@ -64,12 +64,12 @@
     {
     }
 
-    virtual void getControlBlocks(sp<IMemory>* ctl) const
+    virtual sp<IMemoryHeap> getControlBlock() const
     {
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceFlingerClient::getInterfaceDescriptor());
         remote()->transact(GET_CBLK, data, &reply);
-        *ctl  = interface_cast<IMemory>(reply.readStrongBinder());
+        return interface_cast<IMemoryHeap>(reply.readStrongBinder());
     }
 
     virtual sp<ISurface> createSurface( surface_data_t* params,
@@ -118,12 +118,6 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnSurfaceFlingerClient::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
@@ -132,8 +126,7 @@
     switch(code) {
         case GET_CBLK: {
             CHECK_INTERFACE(ISurfaceFlingerClient, data, reply);
-            sp<IMemory> ctl;
-            getControlBlocks(&ctl);
+            sp<IMemoryHeap> ctl(getControlBlock());
             reply->writeStrongBinder(ctl->asBinder());
             return NO_ERROR;
         } break;
@@ -198,8 +191,6 @@
 {
     token = parcel.readInt32();
     identity  = parcel.readInt32();
-    heap[0] = interface_cast<IMemoryHeap>(parcel.readStrongBinder());
-    heap[1] = interface_cast<IMemoryHeap>(parcel.readStrongBinder());
     return NO_ERROR;
 }
 
@@ -207,8 +198,6 @@
 {
     parcel->writeInt32(token);
     parcel->writeInt32(identity);
-    parcel->writeStrongBinder(heap[0]!=0 ? heap[0]->asBinder() : NULL);
-    parcel->writeStrongBinder(heap[1]!=0 ? heap[1]->asBinder() : NULL);
     return NO_ERROR;
 }
 
diff --git a/libs/ui/LayerState.cpp b/libs/ui/LayerState.cpp
index 0b6374b..a53ffb7 100644
--- a/libs/ui/LayerState.cpp
+++ b/libs/ui/LayerState.cpp
@@ -15,7 +15,7 @@
  */
 
 #include <utils/Errors.h>
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 #include <private/ui/LayerState.h>
 
 namespace android {
diff --git a/libs/ui/Overlay.cpp b/libs/ui/Overlay.cpp
index 59c6514..4854d6a 100644
--- a/libs/ui/Overlay.cpp
+++ b/libs/ui/Overlay.cpp
@@ -14,10 +14,10 @@
  * limitations under the License.
  */
 
-#include <utils/IMemory.h>
-#include <utils/Parcel.h>
+#include <binder/IMemory.h>
+#include <binder/Parcel.h>
 #include <utils/Errors.h>
-#include <utils/MemoryHeapBase.h>
+#include <binder/MemoryHeapBase.h>
 
 #include <ui/IOverlay.h>
 #include <ui/Overlay.h>
@@ -59,6 +59,18 @@
     return mOverlayData->queueBuffer(mOverlayData, buffer);
 }
 
+status_t Overlay::setCrop(uint32_t x, uint32_t y, uint32_t w, uint32_t h)
+{
+    if (mStatus != NO_ERROR) return mStatus;
+    return mOverlayData->setCrop(mOverlayData, x, y, w, h);
+}
+
+status_t Overlay::getCrop(uint32_t* x, uint32_t* y, uint32_t* w, uint32_t* h)
+{
+    if (mStatus != NO_ERROR) return mStatus;
+    return mOverlayData->getCrop(mOverlayData, x, y, w, h);
+}
+
 int32_t Overlay::getBufferCount() const
 {
     if (mStatus != NO_ERROR) return mStatus;
@@ -73,6 +85,15 @@
 
 void Overlay::destroy() {  
     if (mStatus != NO_ERROR) return;
+
+    // Must delete the objects in reverse creation order, thus the
+    //  data side must be closed first and then the destroy send to
+    //  the control side.
+    if (mOverlayData) {
+        overlay_data_close(mOverlayData);
+        mOverlayData = NULL;
+    }
+
     mOverlayRef->mOverlayChannel->destroy();
 }
 
diff --git a/libs/ui/Region.cpp b/libs/ui/Region.cpp
index 26e694a..d21ed57 100644
--- a/libs/ui/Region.cpp
+++ b/libs/ui/Region.cpp
@@ -16,295 +16,661 @@
 
 #define LOG_TAG "Region"
 
-#include <stdio.h>
-#include <utils/Atomic.h>
-#include <utils/Debug.h>
+#include <limits.h>
+
+#include <utils/Log.h>
 #include <utils/String8.h>
+
+#include <ui/Rect.h>
 #include <ui/Region.h>
+#include <ui/Point.h>
+
+#include <private/ui/RegionHelper.h>
+
+// ----------------------------------------------------------------------------
+#define VALIDATE_REGIONS        (false)
+#define VALIDATE_WITH_CORECG    (false)
+// ----------------------------------------------------------------------------
+
+#if VALIDATE_WITH_CORECG
+#include <core/SkRegion.h>
+#endif
 
 namespace android {
+// ----------------------------------------------------------------------------
+
+enum {
+    op_nand = region_operator<Rect>::op_nand,
+    op_and  = region_operator<Rect>::op_and,
+    op_or   = region_operator<Rect>::op_or,
+    op_xor  = region_operator<Rect>::op_xor
+};
 
 // ----------------------------------------------------------------------------
 
 Region::Region()
+    : mBounds(0,0)
 {
 }
 
 Region::Region(const Region& rhs)
-    : mRegion(rhs.mRegion)
+    : mBounds(rhs.mBounds), mStorage(rhs.mStorage)
 {
 }
 
-Region::Region(const SkRegion& rhs)
-    : mRegion(rhs)
+Region::Region(const Rect& rhs)
+    : mBounds(rhs)
 {
 }
 
+Region::Region(const Parcel& parcel)
+{
+    status_t err = read(parcel);
+    LOGE_IF(err<0, "error %s reading Region from parcel", strerror(err));
+}
+
+Region::Region(const void* buffer)
+{
+    status_t err = read(buffer);
+    LOGE_IF(err<0, "error %s reading Region from parcel", strerror(err));
+}
+
 Region::~Region()
 {
 }
 
-Region::Region(const Rect& rhs)
-{
-    set(rhs);
-}
-
-Region::Region(const Parcel& parcel)
-{
-    read(parcel);
-}
-
-Region::Region(const void* buffer)
-{
-    read(buffer);
-}
-
 Region& Region::operator = (const Region& rhs)
 {
-    mRegion = rhs.mRegion;
+#if VALIDATE_REGIONS
+    validate(rhs, "operator=");
+#endif
+    mBounds = rhs.mBounds;
+    mStorage = rhs.mStorage;
     return *this;
 }
 
-const SkRegion& Region::toSkRegion() const
+Region& Region::makeBoundsSelf()
 {
-    return mRegion;
-}
-
-Rect Region::bounds() const
-{
-    const SkIRect& b(mRegion.getBounds());
-    return Rect(b.fLeft, b.fTop, b.fRight, b.fBottom);
+    mStorage.clear();
+    return *this;
 }
 
 void Region::clear()
 {
-    mRegion.setEmpty();
+    mBounds.clear();
+    mStorage.clear();
 }
 
 void Region::set(const Rect& r)
 {
-    SkIRect ir;
-    ir.set(r.left, r.top, r.right, r.bottom);
-    mRegion.setRect(ir);
+    mBounds = r;
+    mStorage.clear();
+}
+
+void Region::set(uint32_t w, uint32_t h)
+{
+    mBounds = Rect(int(w), int(h));
+    mStorage.clear();
 }
 
 // ----------------------------------------------------------------------------
 
-Region& Region::orSelf(const Rect& r)
+void Region::addRectUnchecked(int l, int t, int r, int b)
 {
-    SkIRect ir;
-    ir.set(r.left, r.top, r.right, r.bottom);
-    mRegion.op(ir, SkRegion::kUnion_Op);
-    return *this;
+    mStorage.add(Rect(l,t,r,b));
+#if VALIDATE_REGIONS
+    validate(*this, "addRectUnchecked");
+#endif
 }
 
-Region& Region::andSelf(const Rect& r)
-{
-    SkIRect ir;
-    ir.set(r.left, r.top, r.right, r.bottom);
-    mRegion.op(ir, SkRegion::kIntersect_Op);
+// ----------------------------------------------------------------------------
+
+Region& Region::orSelf(const Rect& r) {
+    return operationSelf(r, op_or);
+}
+Region& Region::andSelf(const Rect& r) {
+    return operationSelf(r, op_and);
+}
+Region& Region::subtractSelf(const Rect& r) {
+    return operationSelf(r, op_nand);
+}
+Region& Region::operationSelf(const Rect& r, int op) {
+    Region lhs(*this);
+    boolean_operation(op, *this, lhs, r);
     return *this;
 }
 
 // ----------------------------------------------------------------------------
 
 Region& Region::orSelf(const Region& rhs) {
-    mRegion.op(rhs.mRegion, SkRegion::kUnion_Op);
-    return *this;
+    return operationSelf(rhs, op_or);
 }
-
 Region& Region::andSelf(const Region& rhs) {
-    mRegion.op(rhs.mRegion, SkRegion::kIntersect_Op);
-    return *this;
+    return operationSelf(rhs, op_and);
 }
-
 Region& Region::subtractSelf(const Region& rhs) {
-    mRegion.op(rhs.mRegion, SkRegion::kDifference_Op);
+    return operationSelf(rhs, op_nand);
+}
+Region& Region::operationSelf(const Region& rhs, int op) {
+    Region lhs(*this);
+    boolean_operation(op, *this, lhs, rhs);
     return *this;
 }
 
 Region& Region::translateSelf(int x, int y) {
-    if (x|y) mRegion.translate(x, y);
+    if (x|y) translate(*this, x, y);
     return *this;
 }
 
-Region Region::merge(const Region& rhs) const {
+// ----------------------------------------------------------------------------
+
+const Region Region::merge(const Rect& rhs) const {
+    return operation(rhs, op_or);
+}
+const Region Region::intersect(const Rect& rhs) const {
+    return operation(rhs, op_and);
+}
+const Region Region::subtract(const Rect& rhs) const {
+    return operation(rhs, op_nand);
+}
+const Region Region::operation(const Rect& rhs, int op) const {
     Region result;
-    result.mRegion.op(mRegion, rhs.mRegion, SkRegion::kUnion_Op);
+    boolean_operation(op, result, *this, rhs);
     return result;
 }
 
-Region Region::intersect(const Region& rhs) const {
+// ----------------------------------------------------------------------------
+
+const Region Region::merge(const Region& rhs) const {
+    return operation(rhs, op_or);
+}
+const Region Region::intersect(const Region& rhs) const {
+    return operation(rhs, op_and);
+}
+const Region Region::subtract(const Region& rhs) const {
+    return operation(rhs, op_nand);
+}
+const Region Region::operation(const Region& rhs, int op) const {
     Region result;
-    result.mRegion.op(mRegion, rhs.mRegion, SkRegion::kIntersect_Op);
+    boolean_operation(op, result, *this, rhs);
     return result;
 }
 
-Region Region::subtract(const Region& rhs) const {
+const Region Region::translate(int x, int y) const {
     Region result;
-    result.mRegion.op(mRegion, rhs.mRegion, SkRegion::kDifference_Op);
-    return result;
-}
-
-Region Region::translate(int x, int y) const {
-    Region result;
-    mRegion.translate(x, y, &result.mRegion);
+    translate(result, *this, x, y);
     return result;
 }
 
 // ----------------------------------------------------------------------------
 
 Region& Region::orSelf(const Region& rhs, int dx, int dy) {
-    SkRegion r(rhs.mRegion);
-    r.translate(dx, dy);
-    mRegion.op(r, SkRegion::kUnion_Op);
-    return *this;
+    return operationSelf(rhs, dx, dy, op_or);
 }
-
 Region& Region::andSelf(const Region& rhs, int dx, int dy) {
-    SkRegion r(rhs.mRegion);
-    r.translate(dx, dy);
-    mRegion.op(r, SkRegion::kIntersect_Op);
-    return *this;
+    return operationSelf(rhs, dx, dy, op_and);
 }
-
 Region& Region::subtractSelf(const Region& rhs, int dx, int dy) {
-    SkRegion r(rhs.mRegion);
-    r.translate(dx, dy);
-    mRegion.op(r, SkRegion::kDifference_Op);
+    return operationSelf(rhs, dx, dy, op_nand);
+}
+Region& Region::operationSelf(const Region& rhs, int dx, int dy, int op) {
+    Region lhs(*this);
+    boolean_operation(op, *this, lhs, rhs, dx, dy);
     return *this;
 }
 
-Region Region::merge(const Region& rhs, int dx, int dy) const {
-    Region result;
-    SkRegion r(rhs.mRegion);
-    r.translate(dx, dy);
-    result.mRegion.op(mRegion, r, SkRegion::kUnion_Op);
-    return result;
-}
+// ----------------------------------------------------------------------------
 
-Region Region::intersect(const Region& rhs, int dx, int dy) const {
-    Region result;
-    SkRegion r(rhs.mRegion);
-    r.translate(dx, dy);
-    result.mRegion.op(mRegion, r, SkRegion::kIntersect_Op);
-    return result;
+const Region Region::merge(const Region& rhs, int dx, int dy) const {
+    return operation(rhs, dx, dy, op_or);
 }
-
-Region Region::subtract(const Region& rhs, int dx, int dy) const {
+const Region Region::intersect(const Region& rhs, int dx, int dy) const {
+    return operation(rhs, dx, dy, op_and);
+}
+const Region Region::subtract(const Region& rhs, int dx, int dy) const {
+    return operation(rhs, dx, dy, op_nand);
+}
+const Region Region::operation(const Region& rhs, int dx, int dy, int op) const {
     Region result;
-    SkRegion r(rhs.mRegion);
-    r.translate(dx, dy);
-    result.mRegion.op(mRegion, r, SkRegion::kDifference_Op);
+    boolean_operation(op, result, *this, rhs, dx, dy);
     return result;
 }
 
 // ----------------------------------------------------------------------------
 
-Region::iterator::iterator(const Region& r)
-    : mIt(r.mRegion)
+// This is our region rasterizer, which merges rects and spans together
+// to obtain an optimal region.
+class Region::rasterizer : public region_operator<Rect>::region_rasterizer 
 {
+    Rect& bounds;
+    Vector<Rect>& storage;
+    Rect* head;
+    Rect* tail;
+    Vector<Rect> span;
+    Rect* cur;
+public:
+    rasterizer(Region& reg) 
+        : bounds(reg.mBounds), storage(reg.mStorage), head(), tail(), cur() {
+        bounds.top = bounds.bottom = 0;
+        bounds.left   = INT_MAX;
+        bounds.right  = INT_MIN;
+        storage.clear();
+    }
+
+    ~rasterizer() {
+        if (span.size()) {
+            flushSpan();
+        }
+        if (storage.size()) {
+            bounds.top = storage.itemAt(0).top;
+            bounds.bottom = storage.top().bottom;
+            if (storage.size() == 1) {
+                storage.clear();
+            }
+        } else {
+            bounds.left  = 0;
+            bounds.right = 0;
+        }
+    }
+    
+    virtual void operator()(const Rect& rect) {
+        //LOGD(">>> %3d, %3d, %3d, %3d", 
+        //        rect.left, rect.top, rect.right, rect.bottom);
+        if (span.size()) {
+            if (cur->top != rect.top) {
+                flushSpan();
+            } else if (cur->right == rect.left) {
+                cur->right = rect.right;
+                return;
+            }
+        }
+        span.add(rect);
+        cur = span.editArray() + (span.size() - 1);
+    }
+private:
+    template<typename T> 
+    static inline T min(T rhs, T lhs) { return rhs < lhs ? rhs : lhs; }
+    template<typename T> 
+    static inline T max(T rhs, T lhs) { return rhs > lhs ? rhs : lhs; }
+    void flushSpan() {
+        bool merge = false;
+        if (tail-head == ssize_t(span.size())) {
+            Rect const* p = cur;
+            Rect const* q = head;
+            if (p->top == q->bottom) {
+                merge = true;
+                while (q != tail) {
+                    if ((p->left != q->left) || (p->right != q->right)) {
+                        merge = false;
+                        break;
+                    }
+                    p++, q++;
+                }
+            }
+        }
+        if (merge) {
+            const int bottom = span[0].bottom;
+            Rect* r = head;
+            while (r != tail) {
+                r->bottom = bottom;
+                r++;
+            }
+        } else {
+            bounds.left = min(span.itemAt(0).left, bounds.left);
+            bounds.right = max(span.top().right, bounds.right);
+            storage.appendVector(span);
+            tail = storage.editArray() + storage.size();
+            head = tail - span.size();
+        }
+        span.clear();
+    }
+};
+
+bool Region::validate(const Region& reg, const char* name)
+{
+    bool result = true;
+    const_iterator cur = reg.begin();
+    const_iterator const tail = reg.end();
+    const_iterator prev = cur++;
+    Rect b(*prev);
+    while (cur != tail) {
+        b.left   = b.left   < cur->left   ? b.left   : cur->left;
+        b.top    = b.top    < cur->top    ? b.top    : cur->top;
+        b.right  = b.right  > cur->right  ? b.right  : cur->right;
+        b.bottom = b.bottom > cur->bottom ? b.bottom : cur->bottom;
+        if (cur->top == prev->top) {
+            if (cur->bottom != prev->bottom) {
+                LOGE("%s: invalid span %p", name, cur);
+                result = false;
+            } else if (cur->left < prev->right) {
+                LOGE("%s: spans overlap horizontally prev=%p, cur=%p",
+                        name, prev, cur);
+                result = false;
+            }
+        } else if (cur->top < prev->bottom) {
+            LOGE("%s: spans overlap vertically prev=%p, cur=%p",
+                    name, prev, cur);
+            result = false;
+        }
+        prev = cur;
+        cur++;
+    }
+    if (b != reg.getBounds()) {
+        result = false;
+        LOGE("%s: invalid bounds [%d,%d,%d,%d] vs. [%d,%d,%d,%d]", name,
+                b.left, b.top, b.right, b.bottom,
+                reg.getBounds().left, reg.getBounds().top, 
+                reg.getBounds().right, reg.getBounds().bottom);
+    }
+    if (result == false) {
+        reg.dump(name);
+    }
+    return result;
 }
 
-int Region::iterator::iterate(Rect* rect)
+void Region::boolean_operation(int op, Region& dst,
+        const Region& lhs,
+        const Region& rhs, int dx, int dy)
 {
-    if (mIt.done())
-        return 0;
-    const SkIRect& r(mIt.rect());
-    rect->left  = r.fLeft;
-    rect->top   = r.fTop;
-    rect->right = r.fRight;
-    rect->bottom= r.fBottom;
-    mIt.next();
-    return 1;
+    size_t lhs_count;
+    Rect const * const lhs_rects = lhs.getArray(&lhs_count);
+
+    size_t rhs_count;
+    Rect const * const rhs_rects = rhs.getArray(&rhs_count);
+
+    region_operator<Rect>::region lhs_region(lhs_rects, lhs_count);
+    region_operator<Rect>::region rhs_region(rhs_rects, rhs_count, dx, dy);
+    region_operator<Rect> operation(op, lhs_region, rhs_region);
+    { // scope for rasterizer (dtor has side effects)
+        rasterizer r(dst);
+        operation(r);
+    }
+
+#if VALIDATE_REGIONS
+    validate(lhs, "boolean_operation: lhs");
+    validate(rhs, "boolean_operation: rhs");
+    validate(dst, "boolean_operation: dst");
+#endif
+
+#if VALIDATE_WITH_CORECG
+    SkRegion sk_lhs;
+    SkRegion sk_rhs;
+    SkRegion sk_dst;
+    
+    for (size_t i=0 ; i<lhs_count ; i++)
+        sk_lhs.op(
+                lhs_rects[i].left   + dx,
+                lhs_rects[i].top    + dy,
+                lhs_rects[i].right  + dx,
+                lhs_rects[i].bottom + dy,
+                SkRegion::kUnion_Op);
+    
+    for (size_t i=0 ; i<rhs_count ; i++)
+        sk_rhs.op(
+                rhs_rects[i].left   + dx,
+                rhs_rects[i].top    + dy,
+                rhs_rects[i].right  + dx,
+                rhs_rects[i].bottom + dy,
+                SkRegion::kUnion_Op);
+ 
+    const char* name = "---";
+    SkRegion::Op sk_op;
+    switch (op) {
+        case op_or: sk_op = SkRegion::kUnion_Op; name="OR"; break;
+        case op_and: sk_op = SkRegion::kIntersect_Op; name="AND"; break;
+        case op_nand: sk_op = SkRegion::kDifference_Op; name="NAND"; break;
+    }
+    sk_dst.op(sk_lhs, sk_rhs, sk_op);
+
+    if (sk_dst.isEmpty() && dst.isEmpty())
+        return;
+    
+    bool same = true;
+    Region::const_iterator head = dst.begin();
+    Region::const_iterator const tail = dst.end();
+    SkRegion::Iterator it(sk_dst);
+    while (!it.done()) {
+        if (head != tail) {
+            if (
+                    head->left != it.rect().fLeft ||     
+                    head->top != it.rect().fTop ||     
+                    head->right != it.rect().fRight ||     
+                    head->bottom != it.rect().fBottom
+            ) {
+                same = false;
+                break;
+            }
+        } else {
+            same = false;
+            break;
+        }
+        head++;
+        it.next();
+    }
+    
+    if (head != tail) {
+        same = false;
+    }
+    
+    if(!same) {
+        LOGD("---\nregion boolean %s failed", name);
+        lhs.dump("lhs");
+        rhs.dump("rhs");
+        dst.dump("dst");
+        LOGD("should be");
+        SkRegion::Iterator it(sk_dst);
+        while (!it.done()) {
+            LOGD("    [%3d, %3d, %3d, %3d]",
+                it.rect().fLeft,
+                it.rect().fTop,
+                it.rect().fRight,
+                it.rect().fBottom);
+            it.next();
+        }
+    }
+#endif
+}
+
+void Region::boolean_operation(int op, Region& dst,
+        const Region& lhs,
+        const Rect& rhs, int dx, int dy)
+{
+#if VALIDATE_WITH_CORECG || VALIDATE_REGIONS
+    boolean_operation(op, dst, lhs, Region(rhs), dx, dy);
+#else
+    size_t lhs_count;
+    Rect const * const lhs_rects = lhs.getArray(&lhs_count);
+
+    region_operator<Rect>::region lhs_region(lhs_rects, lhs_count);
+    region_operator<Rect>::region rhs_region(&rhs, 1, dx, dy);
+    region_operator<Rect> operation(op, lhs_region, rhs_region);
+    { // scope for rasterizer (dtor has side effects)
+        rasterizer r(dst);
+        operation(r);
+    }
+
+#endif
+}
+
+void Region::boolean_operation(int op, Region& dst,
+        const Region& lhs, const Region& rhs)
+{
+    boolean_operation(op, dst, lhs, rhs, 0, 0);
+}
+
+void Region::boolean_operation(int op, Region& dst,
+        const Region& lhs, const Rect& rhs)
+{
+    boolean_operation(op, dst, lhs, rhs, 0, 0);
+}
+
+void Region::translate(Region& reg, int dx, int dy)
+{
+    if (!reg.isEmpty()) {
+#if VALIDATE_REGIONS
+        validate(reg, "translate (before)");
+#endif
+        reg.mBounds.translate(dx, dy);
+        size_t count = reg.mStorage.size();
+        Rect* rects = reg.mStorage.editArray();
+        while (count) {
+            rects->translate(dx, dy);
+            rects++;
+            count--;
+        }
+#if VALIDATE_REGIONS
+        validate(reg, "translate (after)");
+#endif
+    }
+}
+
+void Region::translate(Region& dst, const Region& reg, int dx, int dy)
+{
+    dst = reg;
+    translate(dst, dx, dy);
 }
 
 // ----------------------------------------------------------------------------
 
-// we write a 4byte size ahead of the actual region, so we know how much we'll need for reading
-
 status_t Region::write(Parcel& parcel) const
 {
-    int32_t size = mRegion.flatten(NULL);
-    parcel.writeInt32(size);
-    mRegion.flatten(parcel.writeInplace(size));
+#if VALIDATE_REGIONS
+    validate(*this, "write(Parcel)");
+#endif
+    status_t err;
+    const size_t count = mStorage.size();
+    const size_t sizeNeeded = sizeof(int32_t) + (1+count)*sizeof(Rect);
+    void* buffer = parcel.writeInplace(sizeNeeded);
+    if (!buffer) return NO_MEMORY;
+    ssize_t written = Region::write(buffer, sizeNeeded);
+    if (written < 0) return status_t(written);
     return NO_ERROR;
 }
 
 status_t Region::read(const Parcel& parcel)
 {
-    size_t size = parcel.readInt32();
-    mRegion.unflatten(parcel.readInplace(size));
+    void const* buffer = parcel.readInplace(sizeof(int32_t));
+    if (!buffer) return NO_MEMORY;
+    const size_t count = *static_cast<int32_t const *>(buffer);
+    void const* dummy = parcel.readInplace((1+count)*sizeof(Rect));
+    if (!dummy) return NO_MEMORY;
+    const size_t sizeNeeded = sizeof(int32_t) + (1+count)*sizeof(Rect);
+    const ssize_t read = Region::read(buffer);
+    if (read < 0) return status_t(read);
+#if VALIDATE_REGIONS
+    validate(*this, "read(Parcel)");
+#endif
     return NO_ERROR;
 }
 
 ssize_t Region::write(void* buffer, size_t size) const
 {
-    size_t sizeNeeded = mRegion.flatten(NULL);
+#if VALIDATE_REGIONS
+    validate(*this, "write(buffer)");
+#endif
+    const size_t count = mStorage.size();
+    const size_t sizeNeeded = sizeof(int32_t) + (1+count)*sizeof(Rect);
     if (sizeNeeded > size) return NO_MEMORY;
-    return mRegion.flatten(buffer);
+    int32_t* const p = static_cast<int32_t*>(buffer); 
+    *p = count;
+    memcpy(p+1, &mBounds, sizeof(Rect));
+    if (count) {
+        memcpy(p+5, mStorage.array(), count*sizeof(Rect));
+    }
+    return ssize_t(sizeNeeded);
 }
 
 ssize_t Region::read(const void* buffer)
 {
-    return mRegion.unflatten(buffer);
+    int32_t const* const p = static_cast<int32_t const*>(buffer); 
+    const size_t count = *p;
+    memcpy(&mBounds, p+1, sizeof(Rect));
+    mStorage.clear();
+    if (count) {
+        mStorage.insertAt(0, count);
+        memcpy(mStorage.editArray(), p+5, count*sizeof(Rect));
+    }
+#if VALIDATE_REGIONS
+    validate(*this, "read(buffer)");
+#endif
+    return ssize_t(sizeof(int32_t) + (1+count)*sizeof(Rect));
 }
 
 ssize_t Region::writeEmpty(void* buffer, size_t size)
 {
-    if (size < 4) return NO_MEMORY;
-    // this needs to stay in sync with SkRegion
-    *static_cast<int32_t*>(buffer) = -1;
-    return 4;
+    const size_t sizeNeeded = sizeof(int32_t) + sizeof(Rect);
+    if (sizeNeeded > size) return NO_MEMORY;
+    int32_t* const p = static_cast<int32_t*>(buffer); 
+    memset(p, 0, sizeNeeded);
+    return ssize_t(sizeNeeded);
 }
 
 bool Region::isEmpty(void* buffer)
 {
-    // this needs to stay in sync with SkRegion
-    return *static_cast<int32_t*>(buffer) == -1;
+    int32_t const* const p = static_cast<int32_t const*>(buffer); 
+    Rect const* const b = reinterpret_cast<Rect const *>(p+1);
+    return b->isEmpty();
 }
 
-size_t Region::rects(Vector<Rect>& rectList) const
+// ----------------------------------------------------------------------------
+
+Region::const_iterator Region::begin() const {
+    return isRect() ? &mBounds : mStorage.array();
+}
+
+Region::const_iterator Region::end() const {
+    return isRect() ? ((&mBounds) + 1) : (mStorage.array() + mStorage.size());
+}
+
+Rect const* Region::getArray(size_t* count) const {
+    const_iterator const b(begin());
+    const_iterator const e(end());
+    if (count) *count = e-b;
+    return b;
+}
+
+size_t Region::getRects(Vector<Rect>& rectList) const
 {
-    rectList.clear();
-    if (!isEmpty()) {
-        SkRegion::Iterator iterator(mRegion);
-        while( !iterator.done() ) {
-            const SkIRect& ir(iterator.rect());
-            rectList.push(Rect(ir.fLeft, ir.fTop, ir.fRight, ir.fBottom));
-            iterator.next();
-        }
+    rectList = mStorage;
+    if (rectList.isEmpty()) {
+        rectList.clear();
+        rectList.add(mBounds);
     }
     return rectList.size();
 }
 
+// ----------------------------------------------------------------------------
+
 void Region::dump(String8& out, const char* what, uint32_t flags) const
 {
     (void)flags;
-    Vector<Rect> r;
-    rects(r);
-    
+    const_iterator head = begin();
+    const_iterator const tail = end();
+
     size_t SIZE = 256;
     char buffer[SIZE];
-    
-    snprintf(buffer, SIZE, "  Region %s (this=%p, count=%d)\n", what, this, r.size());
+
+    snprintf(buffer, SIZE, "  Region %s (this=%p, count=%d)\n",
+            what, this, tail-head);
     out.append(buffer);
-    for (size_t i=0 ; i<r.size() ; i++) {
+    while (head != tail) {
         snprintf(buffer, SIZE, "    [%3d, %3d, %3d, %3d]\n",
-            r[i].left, r[i].top,r[i].right,r[i].bottom);
+                head->left, head->top, head->right, head->bottom);
         out.append(buffer);
+        head++;
     }
 }
 
 void Region::dump(const char* what, uint32_t flags) const
 {
     (void)flags;
-    Vector<Rect> r;
-    rects(r);
-    LOGD("  Region %s (this=%p, count=%d)\n", what, this, r.size());
-    for (size_t i=0 ; i<r.size() ; i++) {
+    const_iterator head = begin();
+    const_iterator const tail = end();
+    LOGD("  Region %s (this=%p, count=%d)\n", what, this, tail-head);
+    while (head != tail) {
         LOGD("    [%3d, %3d, %3d, %3d]\n",
-            r[i].left, r[i].top,r[i].right,r[i].bottom);
+                head->left, head->top, head->right, head->bottom);
+        head++;
     }
 }
 
diff --git a/libs/ui/Surface.cpp b/libs/ui/Surface.cpp
index 4ea9ae2..aef47fd 100644
--- a/libs/ui/Surface.cpp
+++ b/libs/ui/Surface.cpp
@@ -23,202 +23,333 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 
-#include <utils/Atomic.h>
 #include <utils/Errors.h>
 #include <utils/threads.h>
-#include <utils/IPCThreadState.h>
-#include <utils/IMemory.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IMemory.h>
 #include <utils/Log.h>
 
+#include <ui/DisplayInfo.h>
+#include <ui/BufferMapper.h>
 #include <ui/ISurface.h>
 #include <ui/Surface.h>
 #include <ui/SurfaceComposerClient.h>
 #include <ui/Rect.h>
 
+#include <pixelflinger/pixelflinger.h>
+
 #include <private/ui/SharedState.h>
 #include <private/ui/LayerState.h>
+#include <private/ui/SurfaceBuffer.h>
 
 namespace android {
 
-// ---------------------------------------------------------------------------
+// ============================================================================
+//  SurfaceBuffer
+// ============================================================================
 
-Surface::Surface(const sp<SurfaceComposerClient>& client, 
+SurfaceBuffer::SurfaceBuffer() 
+    : BASE(), mOwner(false), mBufferMapper(BufferMapper::get())
+{
+    width  = 
+    height = 
+    stride = 
+    format = 
+    usage  = 0;
+    handle = NULL;
+}
+
+SurfaceBuffer::SurfaceBuffer(const Parcel& data) 
+    : BASE(), mOwner(true), mBufferMapper(BufferMapper::get())
+{
+    // we own the handle in this case
+    width  = data.readInt32();
+    height = data.readInt32();
+    stride = data.readInt32();
+    format = data.readInt32();
+    usage  = data.readInt32();
+    handle = data.readNativeHandle();
+}
+
+SurfaceBuffer::~SurfaceBuffer()
+{
+    if (handle && mOwner) {
+        native_handle_close(handle);
+        native_handle_delete(const_cast<native_handle*>(handle));
+    }
+}
+
+status_t SurfaceBuffer::lock(uint32_t usage, void** vaddr)
+{
+    const Rect lockBounds(width, height);
+    status_t res = lock(usage, lockBounds, vaddr);
+    return res;
+}
+
+status_t SurfaceBuffer::lock(uint32_t usage, const Rect& rect, void** vaddr)
+{
+    if (rect.left < 0 || rect.right  > this->width || 
+        rect.top  < 0 || rect.bottom > this->height) {
+        LOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
+                rect.left, rect.top, rect.right, rect.bottom, 
+                this->width, this->height);
+        return BAD_VALUE;
+    }
+    status_t res = getBufferMapper().lock(handle, usage, rect, vaddr);
+    return res;
+}
+
+status_t SurfaceBuffer::unlock()
+{
+    status_t res = getBufferMapper().unlock(handle);
+    return res;
+}
+
+status_t SurfaceBuffer::writeToParcel(Parcel* reply, 
+        android_native_buffer_t const* buffer)
+{
+    reply->writeInt32(buffer->width);
+    reply->writeInt32(buffer->height);
+    reply->writeInt32(buffer->stride);
+    reply->writeInt32(buffer->format);
+    reply->writeInt32(buffer->usage);
+    reply->writeNativeHandle(buffer->handle);
+    return NO_ERROR;
+}
+
+// ----------------------------------------------------------------------
+
+static status_t copyBlt(
+        const sp<SurfaceBuffer>& dst, 
+        const sp<SurfaceBuffer>& src, 
+        const Region& reg)
+{
+    status_t err;
+    uint8_t const * src_bits = NULL;
+    err = src->lock(GRALLOC_USAGE_SW_READ_OFTEN, reg.bounds(), (void**)&src_bits);
+    LOGE_IF(err, "error locking src buffer %s", strerror(-err));
+
+    uint8_t* dst_bits = NULL;
+    err = dst->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, reg.bounds(), (void**)&dst_bits);
+    LOGE_IF(err, "error locking dst buffer %s", strerror(-err));
+
+    Region::const_iterator head(reg.begin());
+    Region::const_iterator tail(reg.end());
+    if (head != tail && src_bits && dst_bits) {
+        // NOTE: dst and src must be the same format
+        const size_t bpp = bytesPerPixel(src->format);
+        const size_t dbpr = dst->stride * bpp;
+        const size_t sbpr = src->stride * bpp;
+
+        while (head != tail) {
+            const Rect& r(*head++);
+            ssize_t h = r.height();
+            if (h <= 0) continue;
+            size_t size = r.width() * bpp;
+            uint8_t const * s = src_bits + (r.left + src->stride * r.top) * bpp;
+            uint8_t       * d = dst_bits + (r.left + dst->stride * r.top) * bpp;
+            if (dbpr==sbpr && size==sbpr) {
+                size *= h;
+                h = 1;
+            }
+            do {
+                memcpy(d, s, size);
+                d += dbpr;
+                s += sbpr;
+            } while (--h > 0);
+        }
+    }
+    
+    if (src_bits)
+        src->unlock();
+    
+    if (dst_bits)
+        dst->unlock();
+    
+    return err;
+}
+
+// ============================================================================
+//  SurfaceControl
+// ============================================================================
+
+SurfaceControl::SurfaceControl(
+        const sp<SurfaceComposerClient>& client, 
         const sp<ISurface>& surface,
         const ISurfaceFlingerClient::surface_data_t& data,
-        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
-        bool owner)
+        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
     : mClient(client), mSurface(surface),
       mToken(data.token), mIdentity(data.identity),
-      mFormat(format), mFlags(flags), mOwner(owner)
+      mFormat(format), mFlags(flags)
 {
-    mSwapRectangle.makeInvalid();
-    mSurfaceHeapBase[0] = 0;
-    mSurfaceHeapBase[1] = 0;
-    mHeap[0] = data.heap[0]; 
-    mHeap[1] = data.heap[1];
+}
+        
+SurfaceControl::~SurfaceControl()
+{
+    destroy();
 }
 
-Surface::Surface(Surface const* rhs)
-    : mOwner(false)
+void SurfaceControl::destroy()
 {
-    mToken   = rhs->mToken;
-    mIdentity= rhs->mIdentity;
-    mClient  = rhs->mClient;
-    mSurface = rhs->mSurface;
-    mHeap[0] = rhs->mHeap[0];
-    mHeap[1] = rhs->mHeap[1];
-    mFormat  = rhs->mFormat;
-    mFlags   = rhs->mFlags;
-    mSurfaceHeapBase[0] = rhs->mSurfaceHeapBase[0];
-    mSurfaceHeapBase[1] = rhs->mSurfaceHeapBase[1];
-    mSwapRectangle.makeInvalid();
-}
-
-Surface::~Surface()
-{
-    if (mOwner && mToken>=0 && mClient!=0) {
+    if (isValid()) {
         mClient->destroySurface(mToken);
     }
+
+    // clear all references and trigger an IPC now, to make sure things
+    // happen without delay, since these resources are quite heavy.
     mClient.clear();
     mSurface.clear();
-    mHeap[0].clear();
-    mHeap[1].clear();
     IPCThreadState::self()->flushCommands();
 }
 
-sp<Surface> Surface::dup() const
+void SurfaceControl::clear() 
 {
-    Surface const * r = this;
-    if (this && mOwner) {
-        // the only reason we need to do this is because of Java's garbage
-        // collector: because we're creating a copy of the Surface
-        // instead of a reference, we can garantee that when our last
-        // reference goes away, the real surface will be deleted.
-        // Without this hack (the code is correct too), we'd have to
-        // wait for a GC for the surface to go away.
-        r = new Surface(this);        
+    // here, the window manager tells us explicitly that we should destroy
+    // the surface's resource. Soon after this call, it will also release
+    // its last reference (which will call the dtor); however, it is possible
+    // that a client living in the same process still holds references which
+    // would delay the call to the dtor -- that is why we need this explicit
+    // "clear()" call.
+    destroy();
+}
+
+bool SurfaceControl::isSameSurface(
+        const sp<SurfaceControl>& lhs, const sp<SurfaceControl>& rhs) 
+{
+    if (lhs == 0 || rhs == 0)
+        return false;
+    return lhs->mSurface->asBinder() == rhs->mSurface->asBinder();
+}
+
+status_t SurfaceControl::setLayer(int32_t layer) {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->setLayer(mToken, layer);
+}
+status_t SurfaceControl::setPosition(int32_t x, int32_t y) {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->setPosition(mToken, x, y);
+}
+status_t SurfaceControl::setSize(uint32_t w, uint32_t h) {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->setSize(mToken, w, h);
+}
+status_t SurfaceControl::hide() {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->hide(mToken);
+}
+status_t SurfaceControl::show(int32_t layer) {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->show(mToken, layer);
+}
+status_t SurfaceControl::freeze() {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->freeze(mToken);
+}
+status_t SurfaceControl::unfreeze() {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->unfreeze(mToken);
+}
+status_t SurfaceControl::setFlags(uint32_t flags, uint32_t mask) {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->setFlags(mToken, flags, mask);
+}
+status_t SurfaceControl::setTransparentRegionHint(const Region& transparent) {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->setTransparentRegionHint(mToken, transparent);
+}
+status_t SurfaceControl::setAlpha(float alpha) {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->setAlpha(mToken, alpha);
+}
+status_t SurfaceControl::setMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->setMatrix(mToken, dsdx, dtdx, dsdy, dtdy);
+}
+status_t SurfaceControl::setFreezeTint(uint32_t tint) {
+    const sp<SurfaceComposerClient>& client(mClient);
+    if (client == 0) return NO_INIT;
+    status_t err = validate(client->mControl);
+    if (err < 0) return err;
+    return client->setFreezeTint(mToken, tint);
+}
+
+status_t SurfaceControl::validate(per_client_cblk_t const* cblk) const
+{
+    if (mToken<0 || mClient==0) {
+        LOGE("invalid token (%d, identity=%u) or client (%p)", 
+                mToken, mIdentity, mClient.get());
+        return NO_INIT;
     }
-    return const_cast<Surface*>(r);
+    if (cblk == 0) {
+        LOGE("cblk is null (surface id=%d, identity=%u)", mToken, mIdentity);
+        return NO_INIT;
+    }
+    status_t err = cblk->validate(mToken);
+    if (err != NO_ERROR) {
+        LOGE("surface (id=%d, identity=%u) is invalid, err=%d (%s)",
+                mToken, mIdentity, err, strerror(-err));
+        return err;
+    }
+    if (mIdentity != uint32_t(cblk->layers[mToken].identity)) {
+        LOGE("using an invalid surface id=%d, identity=%u should be %d",
+                mToken, mIdentity, cblk->layers[mToken].identity);
+        return NO_INIT;
+    }
+    return NO_ERROR;
 }
 
-status_t Surface::nextBuffer(SurfaceInfo* info) {
-    return mClient->nextBuffer(this, info);
-}
-
-status_t Surface::lock(SurfaceInfo* info, bool blocking) {
-    return Surface::lock(info, NULL, blocking);
-}
-
-status_t Surface::lock(SurfaceInfo* info, Region* dirty, bool blocking) {
-    if (heapBase(0) == 0) return INVALID_OPERATION;
-    if (heapBase(1) == 0) return INVALID_OPERATION;
-    return mClient->lockSurface(this, info, dirty, blocking);
-}
-
-status_t Surface::unlockAndPost() {
-    if (heapBase(0) == 0) return INVALID_OPERATION;
-    if (heapBase(1) == 0) return INVALID_OPERATION;
-    return mClient->unlockAndPostSurface(this);
-}
-
-status_t Surface::unlock() {
-    if (heapBase(0) == 0) return INVALID_OPERATION;
-    if (heapBase(1) == 0) return INVALID_OPERATION;
-    return mClient->unlockSurface(this);
-}
-
-status_t Surface::setLayer(int32_t layer) {
-    return mClient->setLayer(this, layer);
-}
-status_t Surface::setPosition(int32_t x, int32_t y) {
-    return mClient->setPosition(this, x, y);
-}
-status_t Surface::setSize(uint32_t w, uint32_t h) {
-    return mClient->setSize(this, w, h);
-}
-status_t Surface::hide() {
-    return mClient->hide(this);
-}
-status_t Surface::show(int32_t layer) {
-    return mClient->show(this, layer);
-}
-status_t Surface::freeze() {
-    return mClient->freeze(this);
-}
-status_t Surface::unfreeze() {
-    return mClient->unfreeze(this);
-}
-status_t Surface::setFlags(uint32_t flags, uint32_t mask) {
-    return mClient->setFlags(this, flags, mask);
-}
-status_t Surface::setTransparentRegionHint(const Region& transparent) {
-    return mClient->setTransparentRegionHint(this, transparent);
-}
-status_t Surface::setAlpha(float alpha) {
-    return mClient->setAlpha(this, alpha);
-}
-status_t Surface::setMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
-    return mClient->setMatrix(this, dsdx, dtdx, dsdy, dtdy);
-}
-status_t Surface::setFreezeTint(uint32_t tint) {
-    return mClient->setFreezeTint(this, tint);
-}
-
-Region Surface::dirtyRegion() const  {
-    return mDirtyRegion; 
-}
-void Surface::setDirtyRegion(const Region& region) const {
-    mDirtyRegion = region;
-}
-const Rect& Surface::swapRectangle() const {
-    return mSwapRectangle;
-}
-void Surface::setSwapRectangle(const Rect& r) {
-    mSwapRectangle = r;
-}
-
-sp<Surface> Surface::readFromParcel(Parcel* parcel)
+status_t SurfaceControl::writeSurfaceToParcel(
+        const sp<SurfaceControl>& control, Parcel* parcel)
 {
-    sp<SurfaceComposerClient> client;
-    ISurfaceFlingerClient::surface_data_t data;
-    sp<IBinder> clientBinder= parcel->readStrongBinder();
-    sp<ISurface> surface    = interface_cast<ISurface>(parcel->readStrongBinder());
-    data.heap[0]            = interface_cast<IMemoryHeap>(parcel->readStrongBinder());
-    data.heap[1]            = interface_cast<IMemoryHeap>(parcel->readStrongBinder());
-    data.token              = parcel->readInt32();
-    data.identity           = parcel->readInt32();
-    PixelFormat format      = parcel->readInt32();
-    uint32_t flags          = parcel->readInt32();
-
-    if (clientBinder != NULL)
-        client = SurfaceComposerClient::clientForConnection(clientBinder);
-
-    return new Surface(client, surface, data, 0, 0, format, flags, false);
-}
-
-status_t Surface::writeToParcel(const sp<Surface>& surface, Parcel* parcel)
-{
-    uint32_t flags=0;
-    uint32_t format=0;
+    uint32_t flags = 0;
+    uint32_t format = 0;
     SurfaceID token = -1;
     uint32_t identity = 0;
     sp<SurfaceComposerClient> client;
     sp<ISurface> sur;
-    sp<IMemoryHeap> heap[2];
-    if (surface->isValid()) {
-        token = surface->mToken;
-        identity = surface->mIdentity;
-        client = surface->mClient;
-        sur = surface->mSurface;
-        heap[0] = surface->mHeap[0];
-        heap[1] = surface->mHeap[1];
-        format = surface->mFormat;
-        flags = surface->mFlags;
+    if (SurfaceControl::isValid(control)) {
+        token    = control->mToken;
+        identity = control->mIdentity;
+        client   = control->mClient;
+        sur      = control->mSurface;
+        format   = control->mFormat;
+        flags    = control->mFlags;
     }
     parcel->writeStrongBinder(client!=0  ? client->connection() : NULL);
     parcel->writeStrongBinder(sur!=0     ? sur->asBinder()      : NULL);
-    parcel->writeStrongBinder(heap[0]!=0 ? heap[0]->asBinder()  : NULL);
-    parcel->writeStrongBinder(heap[1]!=0 ? heap[1]->asBinder()  : NULL);
     parcel->writeInt32(token);
     parcel->writeInt32(identity);
     parcel->writeInt32(format);
@@ -226,30 +357,351 @@
     return NO_ERROR;
 }
 
-bool Surface::isSameSurface(const sp<Surface>& lhs, const sp<Surface>& rhs) 
+sp<Surface> SurfaceControl::getSurface() const
+{
+    Mutex::Autolock _l(mLock);
+    if (mSurfaceData == 0) {
+        mSurfaceData = new Surface(const_cast<SurfaceControl*>(this));
+    }
+    return mSurfaceData;
+}
+
+// ============================================================================
+//  Surface
+// ============================================================================
+
+Surface::Surface(const sp<SurfaceControl>& surface)
+    : mClient(surface->mClient), mSurface(surface->mSurface),
+      mToken(surface->mToken), mIdentity(surface->mIdentity),
+      mFormat(surface->mFormat), mFlags(surface->mFlags),
+      mBufferMapper(BufferMapper::get())
+{
+    init();
+}
+
+Surface::Surface(const Parcel& parcel)
+    :  mBufferMapper(BufferMapper::get())
+{
+    sp<IBinder> clientBinder = parcel.readStrongBinder();
+    mSurface    = interface_cast<ISurface>(parcel.readStrongBinder());
+    mToken      = parcel.readInt32();
+    mIdentity   = parcel.readInt32();
+    mFormat     = parcel.readInt32();
+    mFlags      = parcel.readInt32();
+
+    if (clientBinder != NULL)
+        mClient = SurfaceComposerClient::clientForConnection(clientBinder);
+
+    init();
+}
+
+void Surface::init()
+{
+    android_native_window_t::setSwapInterval  = setSwapInterval;
+    android_native_window_t::dequeueBuffer    = dequeueBuffer;
+    android_native_window_t::lockBuffer       = lockBuffer;
+    android_native_window_t::queueBuffer      = queueBuffer;
+    mSwapRectangle.makeInvalid();
+    DisplayInfo dinfo;
+    SurfaceComposerClient::getDisplayInfo(0, &dinfo);
+    const_cast<float&>(android_native_window_t::xdpi) = dinfo.xdpi;
+    const_cast<float&>(android_native_window_t::ydpi) = dinfo.ydpi;
+    // FIXME: set real values here
+    const_cast<int&>(android_native_window_t::minSwapInterval) = 1;
+    const_cast<int&>(android_native_window_t::maxSwapInterval) = 1;
+    const_cast<uint32_t&>(android_native_window_t::flags) = 0;
+}
+
+
+Surface::~Surface()
+{
+    // this is a client-side operation, the surface is destroyed, unmap
+    // its buffers in this process.
+    for (int i=0 ; i<2 ; i++) {
+        if (mBuffers[i] != 0) {
+            getBufferMapper().unregisterBuffer(mBuffers[i]->handle);
+        }
+    }
+
+    // clear all references and trigger an IPC now, to make sure things
+    // happen without delay, since these resources are quite heavy.
+    mClient.clear();
+    mSurface.clear();
+    IPCThreadState::self()->flushCommands();
+}
+
+status_t Surface::validate(per_client_cblk_t const* cblk) const
+{
+    if (mToken<0 || mClient==0) {
+        LOGE("invalid token (%d, identity=%u) or client (%p)", 
+                mToken, mIdentity, mClient.get());
+        return NO_INIT;
+    }
+    if (cblk == 0) {
+        LOGE("cblk is null (surface id=%d, identity=%u)", mToken, mIdentity);
+        return NO_INIT;
+    }
+    status_t err = cblk->validate(mToken);
+    if (err != NO_ERROR) {
+        LOGE("surface (id=%d, identity=%u) is invalid, err=%d (%s)",
+                mToken, mIdentity, err, strerror(-err));
+        return err;
+    }
+    if (mIdentity != uint32_t(cblk->layers[mToken].identity)) {
+        LOGE("using an invalid surface id=%d, identity=%u should be %d",
+                mToken, mIdentity, cblk->layers[mToken].identity);
+        return NO_INIT;
+    }
+    return NO_ERROR;
+}
+
+
+bool Surface::isSameSurface(
+        const sp<Surface>& lhs, const sp<Surface>& rhs) 
 {
     if (lhs == 0 || rhs == 0)
         return false;
     return lhs->mSurface->asBinder() == rhs->mSurface->asBinder();
 }
 
-void* Surface::heapBase(int i) const 
+// ----------------------------------------------------------------------------
+
+int Surface::setSwapInterval(android_native_window_t* window, int interval)
 {
-    void* heapBase = mSurfaceHeapBase[i];
-    // map lazily so it doesn't get mapped in clients that don't need it
-    if (heapBase == 0) {
-        const sp<IMemoryHeap>& heap(mHeap[i]);
-        if (heap != 0) {
-            heapBase = static_cast<uint8_t*>(heap->base());
-            if (heapBase == MAP_FAILED) {
-                heapBase = NULL;
-                LOGE("Couldn't map Surface's heap (binder=%p, heap=%p)",
-                        heap->asBinder().get(), heap.get());
+    return 0;
+}
+
+int Surface::dequeueBuffer(android_native_window_t* window, 
+        android_native_buffer_t** buffer)
+{
+    Surface* self = getSelf(window);
+    return self->dequeueBuffer(buffer);
+}
+
+int Surface::lockBuffer(android_native_window_t* window, 
+        android_native_buffer_t* buffer)
+{
+    Surface* self = getSelf(window);
+    return self->lockBuffer(buffer);
+}
+
+int Surface::queueBuffer(android_native_window_t* window, 
+        android_native_buffer_t* buffer)
+{
+    Surface* self = getSelf(window);
+    return self->queueBuffer(buffer);
+}
+
+// ----------------------------------------------------------------------------
+
+status_t Surface::dequeueBuffer(sp<SurfaceBuffer>* buffer)
+{
+    android_native_buffer_t* out;
+    status_t err = dequeueBuffer(&out);
+    *buffer = SurfaceBuffer::getSelf(out);
+    return err;
+}
+
+status_t Surface::lockBuffer(const sp<SurfaceBuffer>& buffer)
+{
+    return lockBuffer(buffer.get());
+}
+
+status_t Surface::queueBuffer(const sp<SurfaceBuffer>& buffer)
+{
+    return queueBuffer(buffer.get());
+}
+
+// ----------------------------------------------------------------------------
+
+int Surface::dequeueBuffer(android_native_buffer_t** buffer)
+{
+    // FIXME: dequeueBuffer() needs proper implementation
+
+    Mutex::Autolock _l(mSurfaceLock);
+
+    per_client_cblk_t* const cblk = mClient->mControl;
+    status_t err = validate(cblk);
+    if (err != NO_ERROR)
+        return err;
+
+    SurfaceID index(mToken); 
+    
+    int32_t backIdx = cblk->lock_layer(size_t(index),
+            per_client_cblk_t::BLOCKING);
+
+    if (backIdx < 0)
+        return status_t(backIdx); 
+
+    mBackbufferIndex = backIdx;
+    layer_cblk_t* const lcblk = &(cblk->layers[index]);
+
+    volatile const surface_info_t* const back = lcblk->surface + backIdx;
+    if (back->flags & surface_info_t::eNeedNewBuffer) {
+        getBufferLocked(backIdx);
+    }
+
+    const sp<SurfaceBuffer>& backBuffer(mBuffers[backIdx]);
+    mDirtyRegion.set(backBuffer->width, backBuffer->height);
+    *buffer = backBuffer.get();
+  
+    return NO_ERROR;
+}
+
+int Surface::lockBuffer(android_native_buffer_t* buffer)
+{
+    Mutex::Autolock _l(mSurfaceLock);
+
+    per_client_cblk_t* const cblk = mClient->mControl;
+    status_t err = validate(cblk);
+    if (err != NO_ERROR)
+        return err;
+
+    // FIXME: lockBuffer() needs proper implementation
+    return 0;
+}
+
+int Surface::queueBuffer(android_native_buffer_t* buffer)
+{   
+    Mutex::Autolock _l(mSurfaceLock);
+
+    per_client_cblk_t* const cblk = mClient->mControl;
+    status_t err = validate(cblk);
+    if (err != NO_ERROR)
+        return err;
+
+    if (mSwapRectangle.isValid()) {
+        mDirtyRegion.set(mSwapRectangle);
+    }
+    
+    // transmit the dirty region
+    SurfaceID index(mToken); 
+    layer_cblk_t* const lcblk = &(cblk->layers[index]);
+    _send_dirty_region(lcblk, mDirtyRegion);
+
+    uint32_t newstate = cblk->unlock_layer_and_post(size_t(index));
+    if (!(newstate & eNextFlipPending))
+        mClient->signalServer();
+
+    return NO_ERROR;
+}
+
+// ----------------------------------------------------------------------------
+
+status_t Surface::lock(SurfaceInfo* info, bool blocking) {
+    return Surface::lock(info, NULL, blocking);
+}
+
+status_t Surface::lock(SurfaceInfo* other, Region* dirtyIn, bool blocking) 
+{
+    // FIXME: needs some locking here
+    
+    sp<SurfaceBuffer> backBuffer;
+    status_t err = dequeueBuffer(&backBuffer);
+    if (err == NO_ERROR) {
+        err = lockBuffer(backBuffer);
+        if (err == NO_ERROR) {
+            // we handle copy-back here...
+            
+            const Rect bounds(backBuffer->width, backBuffer->height);
+            Region scratch(bounds);
+            Region& newDirtyRegion(dirtyIn ? *dirtyIn : scratch);
+
+            per_client_cblk_t* const cblk = mClient->mControl;
+            layer_cblk_t* const lcblk = &(cblk->layers[SurfaceID(mToken)]);
+            volatile const surface_info_t* const back = lcblk->surface + mBackbufferIndex;
+            if (back->flags & surface_info_t::eBufferDirty) {
+                // content is meaningless in this case and the whole surface
+                // needs to be redrawn.
+                newDirtyRegion.set(bounds);
+            } else {
+                newDirtyRegion.andSelf(bounds);
+                const sp<SurfaceBuffer>& frontBuffer(mBuffers[1-mBackbufferIndex]);
+                if (backBuffer->width  == frontBuffer->width && 
+                    backBuffer->height == frontBuffer->height &&
+                    !(lcblk->flags & eNoCopyBack)) 
+                {
+                    const Region copyback(mOldDirtyRegion.subtract(newDirtyRegion));
+                    if (!copyback.isEmpty() && frontBuffer!=0) {
+                        // copy front to back
+                        copyBlt(backBuffer, frontBuffer, copyback);
+                    }
+                }
             }
-            mSurfaceHeapBase[i] = heapBase;
+            mDirtyRegion = newDirtyRegion;
+            mOldDirtyRegion = newDirtyRegion;
+
+            void* vaddr;
+            status_t res = backBuffer->lock(
+                    GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
+                    newDirtyRegion.bounds(), &vaddr);
+            
+            LOGW_IF(res, "failed locking buffer %d (%p)", 
+                    mBackbufferIndex, backBuffer->handle);
+
+            mLockedBuffer = backBuffer;
+            other->w      = backBuffer->width;
+            other->h      = backBuffer->height;
+            other->s      = backBuffer->stride;
+            other->usage  = backBuffer->usage;
+            other->format = backBuffer->format;
+            other->bits   = vaddr;
         }
     }
-    return heapBase;
+    return err;
+}
+    
+status_t Surface::unlockAndPost() 
+{
+    // FIXME: needs some locking here
+
+    if (mLockedBuffer == 0)
+        return BAD_VALUE;
+
+    status_t res = mLockedBuffer->unlock();
+    LOGW_IF(res, "failed unlocking buffer %d (%p)",
+            mBackbufferIndex, mLockedBuffer->handle);
+    
+    status_t err = queueBuffer(mLockedBuffer);
+    mLockedBuffer = 0;
+    return err;
+}
+
+void Surface::_send_dirty_region(
+        layer_cblk_t* lcblk, const Region& dirty)
+{
+    const int32_t index = (lcblk->flags & eBufferIndex) >> eBufferIndexShift;
+    flat_region_t* flat_region = lcblk->region + index;
+    status_t err = dirty.write(flat_region, sizeof(flat_region_t));
+    if (err < NO_ERROR) {
+        // region doesn't fit, use the bounds
+        const Region reg(dirty.bounds());
+        reg.write(flat_region, sizeof(flat_region_t));
+    }
+}
+
+void Surface::setSwapRectangle(const Rect& r) {
+    mSwapRectangle = r;
+}
+
+status_t Surface::getBufferLocked(int index)
+{
+    status_t err = NO_MEMORY;
+    sp<SurfaceBuffer> buffer = mSurface->getBuffer();
+    LOGE_IF(buffer==0, "ISurface::getBuffer() returned NULL");
+    if (buffer != 0) {
+        sp<SurfaceBuffer>& currentBuffer(mBuffers[index]);
+        if (currentBuffer != 0) {
+            getBufferMapper().unregisterBuffer(currentBuffer->handle);
+            currentBuffer.clear();
+        }
+        err = getBufferMapper().registerBuffer(buffer->handle);
+        LOGW_IF(err, "map(...) failed %d (%s)", err, strerror(-err));
+        if (err == NO_ERROR) {
+            currentBuffer = buffer;
+        }
+    }
+    return err; 
 }
 
 }; // namespace android
diff --git a/libs/ui/SurfaceComposerClient.cpp b/libs/ui/SurfaceComposerClient.cpp
index fe803ff..d2cef78 100644
--- a/libs/ui/SurfaceComposerClient.cpp
+++ b/libs/ui/SurfaceComposerClient.cpp
@@ -29,27 +29,21 @@
 #include <utils/Errors.h>
 #include <utils/threads.h>
 #include <utils/KeyedVector.h>
-#include <utils/IPCThreadState.h>
-#include <utils/IServiceManager.h>
-#include <utils/IMemory.h>
+#include <binder/IServiceManager.h>
+#include <binder/IMemory.h>
 #include <utils/Log.h>
 
+#include <ui/DisplayInfo.h>
 #include <ui/ISurfaceComposer.h>
 #include <ui/ISurfaceFlingerClient.h>
 #include <ui/ISurface.h>
 #include <ui/SurfaceComposerClient.h>
-#include <ui/DisplayInfo.h>
 #include <ui/Rect.h>
-#include <ui/Point.h>
 
 #include <private/ui/SharedState.h>
 #include <private/ui/LayerState.h>
 #include <private/ui/SurfaceFlingerSynchro.h>
 
-#include <pixelflinger/pixelflinger.h>
-
-#include <utils/BpBinder.h>
-
 #define VERBOSE(...)	((void)0)
 //#define VERBOSE			LOGD
 
@@ -65,7 +59,7 @@
 static sp<ISurfaceComposer>                                 gSurfaceManager;
 static DefaultKeyedVector< sp<IBinder>, sp<SurfaceComposerClient> > gActiveConnections;
 static SortedVector<sp<SurfaceComposerClient> >             gOpenTransactions;
-static sp<IMemory>                                          gServerCblkMemory;
+static sp<IMemoryHeap>                                      gServerCblkMemory;
 static volatile surface_flinger_cblk_t*                     gServerCblk;
 
 const sp<ISurfaceComposer>& _get_surface_manager()
@@ -100,7 +94,7 @@
         if (gServerCblk == 0) {
             gServerCblkMemory = sm->getCblk();
             LOGE_IF(gServerCblkMemory==0, "Can't get server control block");
-            gServerCblk = (surface_flinger_cblk_t *)gServerCblkMemory->pointer();
+            gServerCblk = (surface_flinger_cblk_t *)gServerCblkMemory->getBase();
             LOGE_IF(gServerCblk==0, "Can't get server control block address");
         }
     }
@@ -109,50 +103,8 @@
 
 // ---------------------------------------------------------------------------
 
-static void copyBlt(const GGLSurface& dst,
-        const GGLSurface& src, const Region& reg)
-{
-    Region::iterator iterator(reg);
-    if (iterator) {
-        // NOTE: dst and src must be the same format
-        Rect r;
-        const size_t bpp = bytesPerPixel(src.format);
-        const size_t dbpr = dst.stride * bpp;
-        const size_t sbpr = src.stride * bpp;
-        while (iterator.iterate(&r)) {
-            ssize_t h = r.bottom - r.top;
-            if (h) {
-                size_t size = (r.right - r.left) * bpp;
-                uint8_t* s = src.data + (r.left + src.stride * r.top) * bpp;
-                uint8_t* d = dst.data + (r.left + dst.stride * r.top) * bpp;
-                if (dbpr==sbpr && size==sbpr) {
-                    size *= h;
-                    h = 1;
-                }
-                do {
-                    memcpy(d, s, size);
-                    d += dbpr;
-                    s += sbpr;
-                } while (--h > 0);
-            }
-        }
-    }
-}
-
-// ---------------------------------------------------------------------------
-
-surface_flinger_cblk_t::surface_flinger_cblk_t()
-{
-}
-
-// ---------------------------------------------------------------------------
-
-per_client_cblk_t::per_client_cblk_t()
-{
-}
-
 // these functions are used by the clients
-inline status_t per_client_cblk_t::validate(size_t i) const {
+status_t per_client_cblk_t::validate(size_t i) const {
     if (uint32_t(i) >= NUM_LAYERS_MAX)
         return BAD_INDEX;
     if (layers[i].swapState & eInvalidSurface)
@@ -248,8 +200,9 @@
         index = (state&eIndex) ^ ((state&eFlipRequested)>>1);
 
 	    // make sure this buffer is valid
-	    if (layer->surface[index].bits_offset < 0) {
-	        return status_t(layer->surface[index].bits_offset);
+        status_t err = layer->surface[index].status;
+	    if (err < 0) {
+	        return err;
 	    }
 
         if (inspect) {
@@ -273,7 +226,7 @@
 
 uint32_t per_client_cblk_t::unlock_layer_and_post(size_t i)
 {
-    // atomically set eFlipRequested and clear eLocked and optionnaly
+    // atomically set eFlipRequested and clear eLocked and optionally
     // set eNextFlipPending if eFlipRequested was already set
 
     layer_cblk_t * const layer = layers + i;
@@ -290,7 +243,7 @@
 
         if (oldvalue & eFlipRequested)
             newvalue |= eNextFlipPending;
-            // if eFlipRequested was alread set, set eNextFlipPending
+            // if eFlipRequested was already set, set eNextFlipPending
 
     } while (android_atomic_cmpxchg(oldvalue, newvalue, &(layer->swapState)));
 
@@ -298,9 +251,9 @@
             int(i), int((layer->flags & eBufferIndex) >> eBufferIndexShift),
             int(newvalue));
 
-    // from this point, the server can kick in at anytime and use the first
+    // from this point, the server can kick in at any time and use the first
     // buffer, so we cannot use it anymore, and we must use the 'other'
-    // buffer instead (or wait if it is not availlable yet, see lock_layer).
+    // buffer instead (or wait if it is not available yet, see lock_layer).
 
     return newvalue;
 }
@@ -360,9 +313,9 @@
         return;
     }
 
-    mClient->getControlBlocks(&mControlMemory);
+    mControlMemory = mClient->getControlBlock();
     mSignalServer = new SurfaceFlingerSynchro(sm);
-    mControl = static_cast<per_client_cblk_t *>(mControlMemory->pointer());
+    mControl = static_cast<per_client_cblk_t *>(mControlMemory->getBase());
 }
 
 SurfaceComposerClient::~SurfaceComposerClient()
@@ -376,32 +329,6 @@
     return mStatus;
 }
 
-status_t SurfaceComposerClient::validateSurface(
-        per_client_cblk_t const* cblk, Surface const * surface)
-{
-    SurfaceID index = surface->ID();
-    if (cblk == 0) {
-        LOGE("cblk is null (surface id=%d, identity=%u)",
-                index, surface->getIdentity());
-        return NO_INIT;
-    }
-
-    status_t err = cblk->validate(index);
-    if (err != NO_ERROR) {
-        LOGE("surface (id=%d, identity=%u) is invalid, err=%d (%s)",
-                index, surface->getIdentity(), err, strerror(-err));
-        return err;
-    }
-
-    if (surface->getIdentity() != uint32_t(cblk->layers[index].identity)) {
-        LOGE("using an invalid surface id=%d, identity=%u should be %d",
-                index, surface->getIdentity(), cblk->layers[index].identity);
-        return NO_INIT;
-    }
-
-    return NO_ERROR;
-}
-
 sp<IBinder> SurfaceComposerClient::connection() const
 {
     return (mClient != 0) ? mClient->asBinder() : 0;
@@ -437,9 +364,8 @@
 {
     // this can be called more than once.
 
-    sp<IMemory>                 controlMemory;
+    sp<IMemoryHeap>             controlMemory;
     sp<ISurfaceFlingerClient>   client;
-    sp<IMemoryHeap>             surfaceHeap;
 
     {
         Mutex::Autolock _lg(gLock);
@@ -462,9 +388,7 @@
         delete mPrebuiltLayerState;
         mPrebuiltLayerState = 0;
         controlMemory = mControlMemory;
-        surfaceHeap = mSurfaceHeap;
         mControlMemory.clear();
-        mSurfaceHeap.clear();
         mControl = 0;
         mStatus = NO_INIT;
     }
@@ -528,7 +452,13 @@
     return n;
 }
 
-sp<Surface> SurfaceComposerClient::createSurface(
+
+void SurfaceComposerClient::signalServer()
+{
+    mSignalServer->signal();
+}
+
+sp<SurfaceControl> SurfaceComposerClient::createSurface(
         int pid,
         DisplayID display,
         uint32_t w,
@@ -536,14 +466,14 @@
         PixelFormat format,
         uint32_t flags)
 {
-    sp<Surface> result;
+    sp<SurfaceControl> result;
     if (mStatus == NO_ERROR) {
         ISurfaceFlingerClient::surface_data_t data;
         sp<ISurface> surface = mClient->createSurface(&data, pid,
                 display, w, h, format, flags);
         if (surface != 0) {
             if (uint32_t(data.token) < NUM_LAYERS_MAX) {
-                result = new Surface(this, surface, data, w, h, format, flags);
+                result = new SurfaceControl(this, surface, data, w, h, format, flags);
             }
         }
     }
@@ -568,186 +498,6 @@
     return err;
 }
 
-status_t SurfaceComposerClient::nextBuffer(Surface* surface,
-                        Surface::SurfaceInfo* info)
-{
-    SurfaceID index = surface->ID();
-    per_client_cblk_t* const cblk = mControl;
-    status_t err = validateSurface(cblk, surface);
-    if (err != NO_ERROR)
-        return err;
-
-    int32_t backIdx = surface->mBackbufferIndex;
-    layer_cblk_t* const lcblk = &(cblk->layers[index]);
-    const surface_info_t* const front = lcblk->surface + (1-backIdx);
-        info->w      = front->w;
-        info->h      = front->h;
-        info->format = front->format;
-        info->base   = surface->heapBase(1-backIdx);
-        info->bits   = reinterpret_cast<void*>(intptr_t(info->base) + front->bits_offset);
-        info->bpr    = front->bpr;
-
-    return 0;
-}
-
-status_t SurfaceComposerClient::lockSurface(
-        Surface* surface,
-        Surface::SurfaceInfo* other,
-        Region* dirty,
-        bool blocking)
-{
-    Mutex::Autolock _l(surface->getLock());
-
-    SurfaceID index = surface->ID();
-    per_client_cblk_t* const cblk = mControl;
-    status_t err = validateSurface(cblk, surface);
-    if (err != NO_ERROR)
-        return err;
-
-    int32_t backIdx = cblk->lock_layer(size_t(index),
-            per_client_cblk_t::BLOCKING);
-    if (backIdx >= 0) {
-        surface->mBackbufferIndex = backIdx;
-        layer_cblk_t* const lcblk = &(cblk->layers[index]);
-        const surface_info_t* const back = lcblk->surface + backIdx;
-        const surface_info_t* const front = lcblk->surface + (1-backIdx);
-            other->w      = back->w;
-            other->h      = back->h;
-            other->format = back->format;
-            other->base   = surface->heapBase(backIdx);
-            other->bits   = reinterpret_cast<void*>(intptr_t(other->base) + back->bits_offset);
-            other->bpr    = back->bpr;
-
-        const Rect bounds(other->w, other->h);
-        Region newDirtyRegion;
-
-        if (back->flags & surface_info_t::eBufferDirty) {
-            /* it is safe to write *back here, because we're guaranteed
-             * SurfaceFlinger is not touching it (since it just granted
-             * access to us) */
-            const_cast<surface_info_t*>(back)->flags &=
-                    ~surface_info_t::eBufferDirty;
-
-            // content is meaningless in this case and the whole surface
-            // needs to be redrawn.
-
-            newDirtyRegion.set(bounds);
-            if (dirty) {
-                *dirty = newDirtyRegion;
-            }
-
-            //if (bytesPerPixel(other->format) == 4) {
-            //    android_memset32(
-            //        (uint32_t*)other->bits, 0xFF00FF00, other->h * other->bpr);
-            //} else {
-            //    android_memset16( // fill with green
-            //        (uint16_t*)other->bits, 0x7E0, other->h * other->bpr);
-            //}
-        }
-        else
-        {
-            if (dirty) {
-                dirty->andSelf(Region(bounds));
-                newDirtyRegion = *dirty;
-            } else {
-                newDirtyRegion.set(bounds);
-            }
-
-            Region copyback;
-            if (!(lcblk->flags & eNoCopyBack)) {
-                const Region previousDirtyRegion(surface->dirtyRegion());
-                copyback = previousDirtyRegion.subtract(newDirtyRegion);
-            }
-
-            if (!copyback.isEmpty()) {
-                // copy front to back
-                GGLSurface cb;
-                    cb.version = sizeof(GGLSurface);
-                    cb.width = back->w;
-                    cb.height = back->h;
-                    cb.stride = back->stride;
-                    cb.data = (GGLubyte*)surface->heapBase(backIdx);
-                    cb.data += back->bits_offset;
-                    cb.format = back->format;
-
-                GGLSurface t;
-                    t.version = sizeof(GGLSurface);
-                    t.width = front->w;
-                    t.height = front->h;
-                    t.stride = front->stride;
-                    t.data = (GGLubyte*)surface->heapBase(1-backIdx);
-                    t.data += front->bits_offset;
-                    t.format = front->format;
-
-                //const Region copyback(lcblk->region + 1-backIdx);
-                copyBlt(cb, t, copyback);
-            }
-        }
-
-        // update dirty region
-        surface->setDirtyRegion(newDirtyRegion);
-    }
-    return (backIdx < 0) ? status_t(backIdx) : status_t(NO_ERROR);
-}
-
-void SurfaceComposerClient::_signal_server()
-{
-    mSignalServer->signal();
-}
-
-void SurfaceComposerClient::_send_dirty_region(
-        layer_cblk_t* lcblk, const Region& dirty)
-{
-    const int32_t index = (lcblk->flags & eBufferIndex) >> eBufferIndexShift;
-    flat_region_t* flat_region = lcblk->region + index;
-    status_t err = dirty.write(flat_region, sizeof(flat_region_t));
-    if (err < NO_ERROR) {
-        // region doesn't fit, use the bounds
-        const Region reg(dirty.bounds());
-        reg.write(flat_region, sizeof(flat_region_t));
-    }
-}
-
-status_t SurfaceComposerClient::unlockAndPostSurface(Surface* surface)
-{
-    Mutex::Autolock _l(surface->getLock());
-
-    SurfaceID index = surface->ID();
-    per_client_cblk_t* const cblk = mControl;
-    status_t err = validateSurface(cblk, surface);
-    if (err != NO_ERROR)
-        return err;
-
-    Region dirty(surface->dirtyRegion());
-    const Rect& swapRect(surface->swapRectangle());
-    if (swapRect.isValid()) {
-        dirty.set(swapRect);
-    }
-
-    // transmit the dirty region
-    layer_cblk_t* const lcblk = &(cblk->layers[index]);
-    _send_dirty_region(lcblk, dirty);
-    uint32_t newstate = cblk->unlock_layer_and_post(size_t(index));
-    if (!(newstate & eNextFlipPending))
-        _signal_server();
-    return NO_ERROR;
-}
-
-status_t SurfaceComposerClient::unlockSurface(Surface* surface)
-{
-    Mutex::Autolock _l(surface->getLock());
-
-    SurfaceID index = surface->ID();
-    per_client_cblk_t* const cblk = mControl;
-    status_t err = validateSurface(cblk, surface);
-    if (err != NO_ERROR)
-        return err;
-
-    layer_cblk_t* const lcblk = &(cblk->layers[index]);
-    cblk->unlock_layer(size_t(index));
-    return NO_ERROR;
-}
-
 void SurfaceComposerClient::openGlobalTransaction()
 {
     Mutex::Autolock _l(gLock);
@@ -866,14 +616,8 @@
     return NO_ERROR;
 }
 
-layer_state_t* SurfaceComposerClient::_get_state_l(const sp<Surface>& surface)
+layer_state_t* SurfaceComposerClient::_get_state_l(SurfaceID index)
 {
-    SurfaceID index = surface->ID();
-    per_client_cblk_t* const cblk = mControl;
-    status_t err = validateSurface(cblk, surface.get());
-    if (err != NO_ERROR)
-        return 0;
-
     // API usage error, do nothing.
     if (mTransactionOpen<=0) {
         LOGE("Not in transaction (client=%p, SurfaceID=%d, mTransactionOpen=%d",
@@ -892,11 +636,11 @@
     return mStates.editArray() + i;
 }
 
-layer_state_t* SurfaceComposerClient::_lockLayerState(const sp<Surface>& surface)
+layer_state_t* SurfaceComposerClient::_lockLayerState(SurfaceID id)
 {
     layer_state_t* s;
     mLock.lock();
-    s = _get_state_l(surface);
+    s = _get_state_l(id);
     if (!s) mLock.unlock();
     return s;
 }
@@ -906,9 +650,9 @@
     mLock.unlock();
 }
 
-status_t SurfaceComposerClient::setPosition(Surface* surface, int32_t x, int32_t y)
+status_t SurfaceComposerClient::setPosition(SurfaceID id, int32_t x, int32_t y)
 {
-    layer_state_t* s = _lockLayerState(surface);
+    layer_state_t* s = _lockLayerState(id);
     if (!s) return BAD_INDEX;
     s->what |= ISurfaceComposer::ePositionChanged;
     s->x = x;
@@ -917,9 +661,9 @@
     return NO_ERROR;
 }
 
-status_t SurfaceComposerClient::setSize(Surface* surface, uint32_t w, uint32_t h)
+status_t SurfaceComposerClient::setSize(SurfaceID id, uint32_t w, uint32_t h)
 {
-    layer_state_t* s = _lockLayerState(surface);
+    layer_state_t* s = _lockLayerState(id);
     if (!s) return BAD_INDEX;
     s->what |= ISurfaceComposer::eSizeChanged;
     s->w = w;
@@ -928,9 +672,9 @@
     return NO_ERROR;
 }
 
-status_t SurfaceComposerClient::setLayer(Surface* surface, int32_t z)
+status_t SurfaceComposerClient::setLayer(SurfaceID id, int32_t z)
 {
-    layer_state_t* s = _lockLayerState(surface);
+    layer_state_t* s = _lockLayerState(id);
     if (!s) return BAD_INDEX;
     s->what |= ISurfaceComposer::eLayerChanged;
     s->z = z;
@@ -938,32 +682,32 @@
     return NO_ERROR;
 }
 
-status_t SurfaceComposerClient::hide(Surface* surface)
+status_t SurfaceComposerClient::hide(SurfaceID id)
 {
-    return setFlags(surface, ISurfaceComposer::eLayerHidden,
+    return setFlags(id, ISurfaceComposer::eLayerHidden,
             ISurfaceComposer::eLayerHidden);
 }
 
-status_t SurfaceComposerClient::show(Surface* surface, int32_t)
+status_t SurfaceComposerClient::show(SurfaceID id, int32_t)
 {
-    return setFlags(surface, 0, ISurfaceComposer::eLayerHidden);
+    return setFlags(id, 0, ISurfaceComposer::eLayerHidden);
 }
 
-status_t SurfaceComposerClient::freeze(Surface* surface)
+status_t SurfaceComposerClient::freeze(SurfaceID id)
 {
-    return setFlags(surface, ISurfaceComposer::eLayerFrozen,
+    return setFlags(id, ISurfaceComposer::eLayerFrozen,
             ISurfaceComposer::eLayerFrozen);
 }
 
-status_t SurfaceComposerClient::unfreeze(Surface* surface)
+status_t SurfaceComposerClient::unfreeze(SurfaceID id)
 {
-    return setFlags(surface, 0, ISurfaceComposer::eLayerFrozen);
+    return setFlags(id, 0, ISurfaceComposer::eLayerFrozen);
 }
 
-status_t SurfaceComposerClient::setFlags(Surface* surface,
+status_t SurfaceComposerClient::setFlags(SurfaceID id,
         uint32_t flags, uint32_t mask)
 {
-    layer_state_t* s = _lockLayerState(surface);
+    layer_state_t* s = _lockLayerState(id);
     if (!s) return BAD_INDEX;
     s->what |= ISurfaceComposer::eVisibilityChanged;
     s->flags &= ~mask;
@@ -973,11 +717,10 @@
     return NO_ERROR;
 }
 
-
 status_t SurfaceComposerClient::setTransparentRegionHint(
-        Surface* surface, const Region& transparentRegion)
+        SurfaceID id, const Region& transparentRegion)
 {
-    layer_state_t* s = _lockLayerState(surface);
+    layer_state_t* s = _lockLayerState(id);
     if (!s) return BAD_INDEX;
     s->what |= ISurfaceComposer::eTransparentRegionChanged;
     s->transparentRegion = transparentRegion;
@@ -985,9 +728,9 @@
     return NO_ERROR;
 }
 
-status_t SurfaceComposerClient::setAlpha(Surface* surface, float alpha)
+status_t SurfaceComposerClient::setAlpha(SurfaceID id, float alpha)
 {
-    layer_state_t* s = _lockLayerState(surface);
+    layer_state_t* s = _lockLayerState(id);
     if (!s) return BAD_INDEX;
     s->what |= ISurfaceComposer::eAlphaChanged;
     s->alpha = alpha;
@@ -996,11 +739,11 @@
 }
 
 status_t SurfaceComposerClient::setMatrix(
-        Surface* surface,
+        SurfaceID id,
         float dsdx, float dtdx,
         float dsdy, float dtdy )
 {
-    layer_state_t* s = _lockLayerState(surface);
+    layer_state_t* s = _lockLayerState(id);
     if (!s) return BAD_INDEX;
     s->what |= ISurfaceComposer::eMatrixChanged;
     layer_state_t::matrix22_t matrix;
@@ -1013,9 +756,9 @@
     return NO_ERROR;
 }
 
-status_t SurfaceComposerClient::setFreezeTint(Surface* surface, uint32_t tint)
+status_t SurfaceComposerClient::setFreezeTint(SurfaceID id, uint32_t tint)
 {
-    layer_state_t* s = _lockLayerState(surface);
+    layer_state_t* s = _lockLayerState(id);
     if (!s) return BAD_INDEX;
     s->what |= ISurfaceComposer::eFreezeTintChanged;
     s->tint = tint;
diff --git a/libs/ui/SurfaceFlingerSynchro.cpp b/libs/ui/SurfaceFlingerSynchro.cpp
index 5cd9755..c81db71 100644
--- a/libs/ui/SurfaceFlingerSynchro.cpp
+++ b/libs/ui/SurfaceFlingerSynchro.cpp
@@ -14,19 +14,7 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "SurfaceFlingerSynchro"
-
 #include <stdint.h>
-#include <string.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <limits.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <utils/IPCThreadState.h>
-#include <utils/Log.h>
 
 #include <private/ui/SurfaceFlingerSynchro.h>
 
@@ -34,61 +22,10 @@
 
 // ---------------------------------------------------------------------------
 
-SurfaceFlingerSynchro::Barrier::Barrier()
-    : state(CLOSED) { 
-}
-
-SurfaceFlingerSynchro::Barrier::~Barrier() { 
-}
-
-void SurfaceFlingerSynchro::Barrier::open() {
-    asm volatile ("":::"memory");
-    Mutex::Autolock _l(lock);
-    state = OPENED;
-    cv.broadcast();
-}
-
-void SurfaceFlingerSynchro::Barrier::close() {
-    Mutex::Autolock _l(lock);
-    state = CLOSED;
-}
-
-void SurfaceFlingerSynchro::Barrier::waitAndClose() 
-{
-    Mutex::Autolock _l(lock);
-    while (state == CLOSED) {
-        // we're about to wait, flush the binder command buffer
-        IPCThreadState::self()->flushCommands();
-        cv.wait(lock);
-    }
-    state = CLOSED;
-}
-
-status_t SurfaceFlingerSynchro::Barrier::waitAndClose(nsecs_t timeout) 
-{
-    Mutex::Autolock _l(lock);
-    while (state == CLOSED) {
-        // we're about to wait, flush the binder command buffer
-        IPCThreadState::self()->flushCommands();
-        int err = cv.waitRelative(lock, timeout);
-        if (err != 0)
-            return err;
-    }
-    state = CLOSED;
-    return NO_ERROR;
-}
-
-// ---------------------------------------------------------------------------
-
 SurfaceFlingerSynchro::SurfaceFlingerSynchro(const sp<ISurfaceComposer>& flinger)
     : mSurfaceComposer(flinger)
 {
 }
-
-SurfaceFlingerSynchro::SurfaceFlingerSynchro()
-{
-}
-
 SurfaceFlingerSynchro::~SurfaceFlingerSynchro()
 {
 }
@@ -99,24 +36,6 @@
     return NO_ERROR;
 }
 
-status_t SurfaceFlingerSynchro::wait()
-{
-    mBarrier.waitAndClose();
-    return NO_ERROR;
-}
-
-status_t SurfaceFlingerSynchro::wait(nsecs_t timeout)
-{
-    if (timeout == 0)
-        return SurfaceFlingerSynchro::wait();
-    return mBarrier.waitAndClose(timeout);
-}
-
-void SurfaceFlingerSynchro::open()
-{
-    mBarrier.open();
-}
-
 // ---------------------------------------------------------------------------
 
 }; // namespace android
diff --git a/libs/ui/tests/Android.mk b/libs/ui/tests/Android.mk
new file mode 100644
index 0000000..6cc4a5a
--- /dev/null
+++ b/libs/ui/tests/Android.mk
@@ -0,0 +1,16 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+	region.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+	libcutils \
+	libutils \
+    libui
+
+LOCAL_MODULE:= test-region
+
+LOCAL_MODULE_TAGS := tests
+
+include $(BUILD_EXECUTABLE)
diff --git a/libs/ui/tests/region.cpp b/libs/ui/tests/region.cpp
new file mode 100644
index 0000000..0deb2ba
--- /dev/null
+++ b/libs/ui/tests/region.cpp
@@ -0,0 +1,62 @@
+/*
+ * 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 "Region"
+
+#include <stdio.h>
+#include <utils/Debug.h>
+#include <ui/Rect.h>
+#include <ui/Region.h>
+
+using namespace android;
+
+int main()
+{
+    Region reg0( Rect(  0, 0,  100, 100 ) );
+    Region reg1 = reg0;
+    Region reg2, reg3;
+    
+    reg0.dump("reg0");
+    reg1.dump("reg1");
+
+    reg0 = reg0 | reg0.translate(150, 0);
+    reg0.dump("reg0");
+    reg1.dump("reg1");
+
+    reg0 = reg0 | reg0.translate(300, 0);
+    reg0.dump("reg0");
+    reg1.dump("reg1");
+
+    //reg2 = reg0 | reg0.translate(0, 100);
+    //reg0.dump("reg0");
+    //reg1.dump("reg1");
+    //reg2.dump("reg2");
+
+    //reg3 = reg0 | reg0.translate(0, 150);
+    //reg0.dump("reg0");
+    //reg1.dump("reg1");
+    //reg2.dump("reg2");
+    //reg3.dump("reg3");
+
+    LOGD("---");
+    reg2 = reg0 | reg0.translate(100, 0);
+    reg0.dump("reg0");
+    reg1.dump("reg1");
+    reg2.dump("reg2");
+    
+    return 0;
+}
+
diff --git a/libs/utils/Android.mk b/libs/utils/Android.mk
index 9bdd64a..59409a2 100644
--- a/libs/utils/Android.mk
+++ b/libs/utils/Android.mk
@@ -32,52 +32,24 @@
 	StopWatch.cpp \
 	String8.cpp \
 	String16.cpp \
+	StringArray.cpp \
 	SystemClock.cpp \
 	TextOutput.cpp \
 	Threads.cpp \
-	TimerProbe.cpp \
 	Timers.cpp \
 	VectorImpl.cpp \
     ZipFileCRO.cpp \
 	ZipFileRO.cpp \
 	ZipUtils.cpp \
-	misc.cpp \
-	ported.cpp \
-	LogSocket.cpp
+	misc.cpp
 
-#
-# The cpp files listed here do not belong in the device
-# build.  Consult with the swetland before even thinking about
-# putting them in commonSources.
-#
-# They're used by the simulator runtime and by host-side tools like
-# aapt and the simulator front-end.
-#
-hostSources:= \
-	InetAddress.cpp \
-	Pipe.cpp \
-	Socket.cpp \
-	ZipEntry.cpp \
-	ZipFile.cpp
 
 # For the host
 # =====================================================
 
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:= $(commonSources) $(hostSources)
-
-ifeq ($(HOST_OS),linux)
-# Use the futex based mutex and condition variable
-# implementation from android-arm because it's shared mem safe
-	LOCAL_SRC_FILES += \
-		futex_synchro.c \
-		executablepath_linux.cpp
-endif
-ifeq ($(HOST_OS),darwin)
-	LOCAL_SRC_FILES += \
-		executablepath_darwin.cpp
-endif
+LOCAL_SRC_FILES:= $(commonSources)
 
 LOCAL_MODULE:= libutils
 
@@ -103,37 +75,18 @@
 # we have the common sources, plus some device-specific stuff
 LOCAL_SRC_FILES:= \
 	$(commonSources) \
-	Binder.cpp \
-	BpBinder.cpp \
-	IInterface.cpp \
-	IMemory.cpp \
-	IPCThreadState.cpp \
-	MemoryDealer.cpp \
-    MemoryBase.cpp \
-    MemoryHeapBase.cpp \
-    MemoryHeapPmem.cpp \
-	Parcel.cpp \
-	ProcessState.cpp \
-	IPermissionController.cpp \
-	IServiceManager.cpp \
 	Unicode.cpp \
     BackupData.cpp \
 	BackupHelpers.cpp
 
-ifeq ($(TARGET_SIMULATOR),true)
-LOCAL_SRC_FILES += $(hostSources)
-endif
-
 ifeq ($(TARGET_OS),linux)
-# Use the futex based mutex and condition variable
-# implementation from android-arm because it's shared mem safe
-LOCAL_SRC_FILES += futex_synchro.c
 LOCAL_LDLIBS += -lrt -ldl
 endif
 
 LOCAL_C_INCLUDES += \
 		external/zlib \
 		external/icu4c/common
+
 LOCAL_LDLIBS += -lpthread
 
 LOCAL_SHARED_LIBRARIES := \
@@ -144,15 +97,10 @@
 ifneq ($(TARGET_SIMULATOR),true)
 ifeq ($(TARGET_OS)-$(TARGET_ARCH),linux-x86)
 # This is needed on x86 to bring in dl_iterate_phdr for CallStack.cpp
-LOCAL_SHARED_LIBRARIES += \
-	libdl
+LOCAL_SHARED_LIBRARIES += libdl
 endif # linux-x86
 endif # sim
 
 LOCAL_MODULE:= libutils
-
-#LOCAL_CFLAGS+=
-#LOCAL_LDFLAGS:=
-
 include $(BUILD_SHARED_LIBRARY)
 
diff --git a/libs/utils/BackupData.cpp b/libs/utils/BackupData.cpp
index cce754a..be04777 100644
--- a/libs/utils/BackupData.cpp
+++ b/libs/utils/BackupData.cpp
@@ -298,10 +298,12 @@
     }
     if (m_header.entity.dataSize > 0) {
         int pos = lseek(m_fd, m_dataEndPos, SEEK_SET);
-        return pos == -1 ? (int)errno : (int)NO_ERROR;
-    } else {
-        return NO_ERROR;
+        if (pos == -1) {
+            return errno;
+        }
     }
+    SKIP_PADDING();
+    return NO_ERROR;
 }
 
 ssize_t
diff --git a/libs/utils/CallStack.cpp b/libs/utils/CallStack.cpp
index 2fdaa71..55b6024 100644
--- a/libs/utils/CallStack.cpp
+++ b/libs/utils/CallStack.cpp
@@ -311,7 +311,8 @@
     } else { 
         void const* start = 0;
         name = MapInfo::mapAddressToName(ip, "<unknown>", &start);
-        snprintf(tmp, 256, "pc %08lx  %s", uintptr_t(ip)-uintptr_t(start), name);
+        snprintf(tmp, 256, "pc %08lx  %s", 
+                long(uintptr_t(ip)-uintptr_t(start)), name);
         res.append(tmp);
     }
     res.append("\n");
diff --git a/libs/utils/IDataConnection.cpp b/libs/utils/IDataConnection.cpp
deleted file mode 100644
index c6d49aa..0000000
--- a/libs/utils/IDataConnection.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Parcel.h>
-
-#include <utils/IDataConnection.h>
-
-namespace android {
-
-// ---------------------------------------------------------------------------
-
-enum
-{
-    CONNECT_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
-    DISCONNECT_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION + 1
-};
-
-class BpDataConnection : public BpInterface<IDataConnection>
-{
-public:
-    BpDataConnection::BpDataConnection(const sp<IBinder>& impl)
-        : BpInterface<IDataConnection>(impl)
-    {
-    }
-
-	virtual void connect()
-	{
-		Parcel data, reply;
-        data.writeInterfaceToken(IDataConnection::descriptor());
-		remote()->transact(CONNECT_TRANSACTION, data, &reply);
-	}
-	
-	virtual void disconnect()
-	{
-		Parcel data, reply;
-		remote()->transact(DISCONNECT_TRANSACTION, data, &reply);
-	}
-};
-
-IMPLEMENT_META_INTERFACE(DataConnection, "android.utils.IDataConnection");
-
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
-status_t BnDataConnection::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch(code)
-    {
-		case CONNECT_TRANSACTION:
-		{                   
-            CHECK_INTERFACE(IDataConnection, data, reply);
-			connect();
-			return NO_ERROR;
-		}    
-		
-		case DISCONNECT_TRANSACTION:
-		{                   
-            CHECK_INTERFACE(IDataConnection, data, reply);
-			disconnect();
-			return NO_ERROR;
-		}
-       
-		default:
-			return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-// ----------------------------------------------------------------------------
-
-}; // namespace android
diff --git a/libs/utils/InetAddress.cpp b/libs/utils/InetAddress.cpp
deleted file mode 100644
index 39a0a68..0000000
--- a/libs/utils/InetAddress.cpp
+++ /dev/null
@@ -1,236 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Internet address class.
-//
-#ifdef HAVE_WINSOCK
-# include <winsock2.h>
-#else
-# include <sys/types.h>
-# include <sys/socket.h>
-# include <netinet/in.h>
-//# include <arpa/inet.h>
-# include <netdb.h>
-#endif
-
-#include <utils/inet_address.h>
-#include <utils/threads.h>
-#include <utils/Log.h>
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <assert.h>
-
-using namespace android;
-
-
-/*
- * ===========================================================================
- *      InetAddress
- * ===========================================================================
- */
-
-// lock for the next couple of functions; could tuck into InetAddress
-static Mutex*   gGHBNLock;
-
-/*
- * Lock/unlock access to the hostent struct returned by gethostbyname().
- */
-static inline void lock_gethostbyname(void)
-{
-    if (gGHBNLock == NULL)
-        gGHBNLock = new Mutex;
-    gGHBNLock->lock();
-}
-static inline void unlock_gethostbyname(void)
-{
-    assert(gGHBNLock != NULL);
-    gGHBNLock->unlock();
-}
-
-
-/*
- * Constructor -- just init members.  This is private so that callers
- * are required to use getByName().
- */
-InetAddress::InetAddress(void)
-    : mAddress(NULL), mLength(-1), mName(NULL)
-{
-}
-
-/*
- * Destructor -- free address storage.
- */
-InetAddress::~InetAddress(void)
-{
-    delete[] (char*) mAddress;
-    delete[] mName;
-}
-
-/*
- * Copy constructor.
- */
-InetAddress::InetAddress(const InetAddress& orig)
-{
-    *this = orig;   // use assignment code
-}
-
-/*
- * Assignment operator.
- */
-InetAddress& InetAddress::operator=(const InetAddress& addr)
-{
-    // handle self-assignment
-    if (this == &addr)
-        return *this;
-    // copy mLength and mAddress
-    mLength = addr.mLength;
-    if (mLength > 0) {
-        mAddress = new char[mLength];
-        memcpy(mAddress, addr.mAddress, mLength);
-        LOG(LOG_DEBUG, "socket",
-            "HEY: copied %d bytes in assignment operator\n", mLength);
-    } else {
-        mAddress = NULL;
-    }
-    // copy mName
-    mName = new char[strlen(addr.mName)+1];
-    strcpy(mName, addr.mName);
-
-    return *this;
-}
-
-/*
- * Create a new object from a name or a dotted-number IP notation.
- *
- * Returns NULL on failure.
- */
-InetAddress*
-InetAddress::getByName(const char* host)
-{
-    InetAddress* newAddr = NULL;
-    struct sockaddr_in addr;
-    struct hostent* he;
-    DurationTimer hostTimer, lockTimer;
-
-    // gethostbyname() isn't reentrant, so we need to lock things until
-    // we can copy the data out.
-    lockTimer.start();
-    lock_gethostbyname();
-    hostTimer.start();
-
-    he = gethostbyname(host);
-    if (he == NULL) {
-        LOG(LOG_WARN, "socket", "WARNING: cannot resolve host %s\n", host);
-        unlock_gethostbyname();
-        return NULL;
-    }
-
-    memcpy(&addr.sin_addr, he->h_addr, he->h_length);
-    addr.sin_family = he->h_addrtype;
-    addr.sin_port = 0;
-
-    // got it, unlock us
-    hostTimer.stop();
-    he = NULL;
-    unlock_gethostbyname();
-
-    lockTimer.stop();
-    if ((long) lockTimer.durationUsecs() > 100000) {
-        long lockTime = (long) lockTimer.durationUsecs();
-        long hostTime = (long) hostTimer.durationUsecs();
-        LOG(LOG_DEBUG, "socket",
-            "Lookup of %s took %.3fs (gethostbyname=%.3fs lock=%.3fs)\n",
-            host, lockTime / 1000000.0, hostTime / 1000000.0,
-            (lockTime - hostTime) / 1000000.0);
-    }
-
-    // Alloc storage and copy it over.
-    newAddr = new InetAddress();
-    if (newAddr == NULL)
-        return NULL;
-
-    newAddr->mLength = sizeof(struct sockaddr_in);
-    newAddr->mAddress = new char[sizeof(struct sockaddr_in)];
-    if (newAddr->mAddress == NULL) {
-        delete newAddr;
-        return NULL;
-    }
-    memcpy(newAddr->mAddress, &addr, newAddr->mLength);
-
-    // Keep this for debug messages.
-    newAddr->mName = new char[strlen(host)+1];
-    if (newAddr->mName == NULL) {
-        delete newAddr;
-        return NULL;
-    }
-    strcpy(newAddr->mName, host);
-
-    return newAddr;
-}
-
-
-/*
- * ===========================================================================
- *      InetSocketAddress
- * ===========================================================================
- */
-
-/*
- * Create an address with the host wildcard (INADDR_ANY).
- */
-bool InetSocketAddress::create(int port)
-{
-    assert(mAddress == NULL);
-
-    mAddress = InetAddress::getByName("0.0.0.0");
-    if (mAddress == NULL)
-        return false;
-    mPort = port;
-    return true;
-}
-
-/*
- * Create address with host and port specified.
- */
-bool InetSocketAddress::create(const InetAddress* addr, int port)
-{
-    assert(mAddress == NULL);
-
-    mAddress = new InetAddress(*addr);  // make a copy
-    if (mAddress == NULL)
-        return false;
-    mPort = port;
-    return true;
-}
-
-/*
- * Create address with host and port specified.
- */
-bool InetSocketAddress::create(const char* host, int port)
-{
-    assert(mAddress == NULL);
-
-    mAddress = InetAddress::getByName(host);
-    if (mAddress == NULL)
-        return false;
-    mPort = port;
-    return true;
-}
-
diff --git a/libs/utils/LogSocket.cpp b/libs/utils/LogSocket.cpp
deleted file mode 100644
index 55c1b99..0000000
--- a/libs/utils/LogSocket.cpp
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2008 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 HAVE_WINSOCK
-//#define SOCKETLOG
-#endif
-
-#ifdef SOCKETLOG
-
-#define LOG_TAG "SOCKETLOG"
-
-#include <string.h>
-#include <cutils/log.h>
-#include "utils/LogSocket.h"
-#include "utils/logger.h"
-#include "cutils/hashmap.h"
-
-// defined in //device/data/etc/event-log-tags
-#define SOCKET_CLOSE_LOG 51000
-
-static Hashmap* statsMap = NULL;
-
-#define LOG_LIST_NUMBER 5
-
-typedef struct SocketStats {
-    int fd;
-    unsigned int send;
-    unsigned int recv;
-    unsigned int ip;
-    unsigned short port;
-    short reason;
-}SocketStats;
-
-SocketStats *get_socket_stats(int fd) {
-    if (statsMap == NULL) {
-        statsMap = hashmapCreate(8, &hashmapIntHash, &hashmapIntEquals);
-    }
-
-    SocketStats *s = (SocketStats*) hashmapGet(statsMap, &fd);
-    if (s == NULL) {
-        // LOGD("create SocketStats for fd %d", fd);
-        s = (SocketStats*) malloc(sizeof(SocketStats));
-        memset(s, 0, sizeof(SocketStats));
-        s->fd = fd;
-        hashmapPut(statsMap, &s->fd, s);
-    }
-    return s;
-}
-
-void log_socket_connect(int fd, unsigned int ip, unsigned short port) {
-    // LOGD("log_socket_connect for fd %d ip %d port%d", fd, ip, port);
-    SocketStats *s = get_socket_stats(fd);
-    s->ip = ip;
-    s->port = port;
-}
-
-void add_send_stats(int fd, int send) {
-    if (send <=0) {
-        LOGE("add_send_stats send %d", send);
-        return;
-    }
-    SocketStats *s = get_socket_stats(fd);
-    s->send += send;
-    // LOGD("add_send_stats for fd %d ip %d port%d", fd, s->ip, s->port);
-}
-
-void add_recv_stats(int fd, int recv) {
-    if (recv <=0) {
-        LOGE("add_recv_stats recv %d", recv);
-        return;
-    }
-    SocketStats *s = get_socket_stats(fd);
-    s->recv += recv;
-    // LOGD("add_recv_stats for fd %d ip %d port%d", fd, s->ip, s->port);
-}
-
-char* put_int(char* buf, int value) {
-    *buf = EVENT_TYPE_INT;
-    buf++;
-    memcpy(buf, &value, sizeof(int));
-    return buf + sizeof(int);
-}
-
-void log_socket_close(int fd, short reason) {
-    if (statsMap) {
-        SocketStats *s = (SocketStats*) hashmapGet(statsMap, &fd);
-        if (s != NULL) {
-            if (s->send != 0 || s->recv != 0) {
-                s->reason = reason;
-                // 5 int + list type need 2 bytes
-                char buf[LOG_LIST_NUMBER * 5 + 2];
-                buf[0] = EVENT_TYPE_LIST;
-                buf[1] = LOG_LIST_NUMBER;
-                char* writePos = buf + 2;
-                writePos = put_int(writePos, s->send);
-                writePos = put_int(writePos, s->recv);
-                writePos = put_int(writePos, s->ip);
-                writePos = put_int(writePos, s->port);
-                writePos = put_int(writePos, s->reason);
-                
-                android_bWriteLog(SOCKET_CLOSE_LOG, buf, sizeof(buf));
-                // LOGD("send %d recv %d reason %d", s->send, s->recv, s->reason);
-            }
-            hashmapRemove(statsMap, &s->fd);
-            free(s);
-        }
-    }
-}
-
-#else
-void add_send_stats(int fd, int send) {} 
-void add_recv_stats(int fd, int recv) {}
-void log_socket_close(int fd, short reason) {}
-void log_socket_connect(int fd, unsigned int ip, unsigned short port) {}
-#endif
diff --git a/libs/utils/Pipe.cpp b/libs/utils/Pipe.cpp
deleted file mode 100644
index 613906b..0000000
--- a/libs/utils/Pipe.cpp
+++ /dev/null
@@ -1,465 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Unidirectional pipe.
-//
-
-#include <utils/Pipe.h>
-#include <utils/Log.h>
-
-#if defined(HAVE_WIN32_IPC)
-# include <windows.h>
-#else
-# include <fcntl.h>
-# include <unistd.h>
-# include <errno.h>
-#endif
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <assert.h>
-#include <string.h>
-
-using namespace android;
-
-const unsigned long kInvalidHandle = (unsigned long) -1;
-
-
-/*
- * Constructor.  Do little.
- */
-Pipe::Pipe(void)
-    : mReadNonBlocking(false), mReadHandle(kInvalidHandle),
-      mWriteHandle(kInvalidHandle)
-{
-}
-
-/*
- * Destructor.  Use the system-appropriate close call.
- */
-Pipe::~Pipe(void)
-{
-#if defined(HAVE_WIN32_IPC)
-    if (mReadHandle != kInvalidHandle) {
-        if (!CloseHandle((HANDLE)mReadHandle))
-            LOG(LOG_WARN, "pipe", "failed closing read handle (%ld)\n",
-                mReadHandle);
-    }
-    if (mWriteHandle != kInvalidHandle) {
-        FlushFileBuffers((HANDLE)mWriteHandle);
-        if (!CloseHandle((HANDLE)mWriteHandle))
-            LOG(LOG_WARN, "pipe", "failed closing write handle (%ld)\n",
-                mWriteHandle);
-    }
-#else
-    if (mReadHandle != kInvalidHandle) {
-        if (close((int) mReadHandle) != 0)
-            LOG(LOG_WARN, "pipe", "failed closing read fd (%d)\n",
-                (int) mReadHandle);
-    }
-    if (mWriteHandle != kInvalidHandle) {
-        if (close((int) mWriteHandle) != 0)
-            LOG(LOG_WARN, "pipe", "failed closing write fd (%d)\n",
-                (int) mWriteHandle);
-    }
-#endif
-}
-
-/*
- * Create the pipe.
- *
- * Use the POSIX stuff for everything but Windows.
- */
-bool Pipe::create(void)
-{
-    assert(mReadHandle == kInvalidHandle);
-    assert(mWriteHandle == kInvalidHandle);
-
-#if defined(HAVE_WIN32_IPC)
-    /* we use this across processes, so they need to be inheritable */
-    HANDLE handles[2];
-    SECURITY_ATTRIBUTES saAttr;
-
-    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
-    saAttr.bInheritHandle = TRUE;
-    saAttr.lpSecurityDescriptor = NULL;
-
-    if (!CreatePipe(&handles[0], &handles[1], &saAttr, 0)) {
-        LOG(LOG_ERROR, "pipe", "unable to create pipe\n");
-        return false;
-    }
-    mReadHandle = (unsigned long) handles[0];
-    mWriteHandle = (unsigned long) handles[1];
-    return true;
-#else
-    int fds[2];
-
-    if (pipe(fds) != 0) {
-        LOG(LOG_ERROR, "pipe", "unable to create pipe\n");
-        return false;
-    }
-    mReadHandle = fds[0];
-    mWriteHandle = fds[1];
-    return true;
-#endif
-}
-
-/*
- * Create a "half pipe".  Please, no Segway riding.
- */
-bool Pipe::createReader(unsigned long handle)
-{
-    mReadHandle = handle;
-    assert(mWriteHandle == kInvalidHandle);
-    return true;
-}
-
-/*
- * Create a "half pipe" for writing.
- */
-bool Pipe::createWriter(unsigned long handle)
-{
-    mWriteHandle = handle;
-    assert(mReadHandle == kInvalidHandle);
-    return true;
-}
-
-/*
- * Return "true" if create() has been called successfully.
- */
-bool Pipe::isCreated(void)
-{
-    // one or the other should be open
-    return (mReadHandle != kInvalidHandle || mWriteHandle != kInvalidHandle);
-}
-
-
-/*
- * Read data from the pipe.
- *
- * For Linux and Darwin, just call read().  For Windows, implement
- * non-blocking reads by calling PeekNamedPipe first.
- */
-int Pipe::read(void* buf, int count)
-{
-    assert(mReadHandle != kInvalidHandle);
-
-#if defined(HAVE_WIN32_IPC)
-    DWORD totalBytesAvail = count;
-    DWORD bytesRead;
-
-    if (mReadNonBlocking) {
-        // use PeekNamedPipe to adjust read count expectations
-        if (!PeekNamedPipe((HANDLE) mReadHandle, NULL, 0, NULL,
-                &totalBytesAvail, NULL))
-        {
-            LOG(LOG_ERROR, "pipe", "PeekNamedPipe failed\n");
-            return -1;
-        }
-
-        if (totalBytesAvail == 0)
-            return 0;
-    }
-
-    if (!ReadFile((HANDLE) mReadHandle, buf, totalBytesAvail, &bytesRead,
-            NULL))
-    {
-        DWORD err = GetLastError();
-        if (err == ERROR_HANDLE_EOF || err == ERROR_BROKEN_PIPE)
-            return 0;
-        LOG(LOG_ERROR, "pipe", "ReadFile failed (err=%ld)\n", err);
-        return -1;
-    }
-
-    return (int) bytesRead;
-#else
-    int cc;
-    cc = ::read(mReadHandle, buf, count);
-    if (cc < 0 && errno == EAGAIN)
-        return 0;
-    return cc;
-#endif
-}
-
-/*
- * Write data to the pipe.
- *
- * POSIX systems are trivial, Windows uses a different call and doesn't
- * handle non-blocking writes.
- *
- * If we add non-blocking support here, we probably want to make it an
- * all-or-nothing write.
- *
- * DO NOT use LOG() here, we could be writing a log message.
- */
-int Pipe::write(const void* buf, int count)
-{
-    assert(mWriteHandle != kInvalidHandle);
-
-#if defined(HAVE_WIN32_IPC)
-    DWORD bytesWritten;
-
-    if (mWriteNonBlocking) {
-        // BUG: can't use PeekNamedPipe() to get the amount of space
-        // left.  Looks like we need to use "overlapped I/O" functions.
-        // I just don't care that much.
-    }
-
-    if (!WriteFile((HANDLE) mWriteHandle, buf, count, &bytesWritten, NULL)) {
-        // can't LOG, use stderr
-        fprintf(stderr, "WriteFile failed (err=%ld)\n", GetLastError());
-        return -1;
-    }
-
-    return (int) bytesWritten;
-#else
-    int cc;
-    cc = ::write(mWriteHandle, buf, count);
-    if (cc < 0 && errno == EAGAIN)
-        return 0;
-    return cc;
-#endif
-}
-
-/*
- * Figure out if there is data available on the read fd.
- *
- * We return "true" on error because we want the caller to try to read
- * from the pipe.  They'll notice the read failure and do something
- * appropriate.
- */
-bool Pipe::readReady(void)
-{
-    assert(mReadHandle != kInvalidHandle);
-
-#if defined(HAVE_WIN32_IPC)
-    DWORD totalBytesAvail;
-
-    if (!PeekNamedPipe((HANDLE) mReadHandle, NULL, 0, NULL,
-            &totalBytesAvail, NULL))
-    {
-        LOG(LOG_ERROR, "pipe", "PeekNamedPipe failed\n");
-        return true;
-    }
-
-    return (totalBytesAvail != 0);
-#else
-    errno = 0;
-    fd_set readfds;
-    struct timeval tv = { 0, 0 };
-    int cc;
-
-    FD_ZERO(&readfds);
-    FD_SET(mReadHandle, &readfds);
-
-    cc = select(mReadHandle+1, &readfds, NULL, NULL, &tv);
-    if (cc < 0) {
-        LOG(LOG_ERROR, "pipe", "select() failed\n");
-        return true;
-    } else if (cc == 0) {
-        /* timed out, nothing available */
-        return false;
-    } else if (cc == 1) {
-        /* our fd is ready */
-        return true;
-    } else {
-        LOG(LOG_ERROR, "pipe", "HUH? select() returned > 1\n");
-        return true;
-    }
-#endif
-}
-
-/*
- * Enable or disable non-blocking mode for the read descriptor.
- *
- * NOTE: the calls succeed under Mac OS X, but the pipe doesn't appear to
- * actually be in non-blocking mode.  If this matters -- i.e. you're not
- * using a select() call -- put a call to readReady() in front of the
- * ::read() call, with a PIPE_NONBLOCK_BROKEN #ifdef in the Makefile for
- * Darwin.
- */
-bool Pipe::setReadNonBlocking(bool val)
-{
-    assert(mReadHandle != kInvalidHandle);
-
-#if defined(HAVE_WIN32_IPC)
-    // nothing to do
-#else
-    int flags;
-
-    if (fcntl(mReadHandle, F_GETFL, &flags) == -1) {
-        LOG(LOG_ERROR, "pipe", "couldn't get flags for pipe read fd\n");
-        return false;
-    }
-    if (val)
-        flags |= O_NONBLOCK;
-    else
-        flags &= ~(O_NONBLOCK);
-    if (fcntl(mReadHandle, F_SETFL, &flags) == -1) {
-        LOG(LOG_ERROR, "pipe", "couldn't set flags for pipe read fd\n");
-        return false;
-    }
-#endif
-
-    mReadNonBlocking = val;
-    return true;
-}
-
-/*
- * Enable or disable non-blocking mode for the write descriptor.
- *
- * As with setReadNonBlocking(), this does not work on the Mac.
- */
-bool Pipe::setWriteNonBlocking(bool val)
-{
-    assert(mWriteHandle != kInvalidHandle);
-
-#if defined(HAVE_WIN32_IPC)
-    // nothing to do
-#else
-    int flags;
-
-    if (fcntl(mWriteHandle, F_GETFL, &flags) == -1) {
-        LOG(LOG_WARN, "pipe",
-            "Warning: couldn't get flags for pipe write fd (errno=%d)\n",
-            errno);
-        return false;
-    }
-    if (val)
-        flags |= O_NONBLOCK;
-    else
-        flags &= ~(O_NONBLOCK);
-    if (fcntl(mWriteHandle, F_SETFL, &flags) == -1) {
-        LOG(LOG_WARN, "pipe",
-            "Warning: couldn't set flags for pipe write fd (errno=%d)\n",
-            errno);
-        return false;
-    }
-#endif
-
-    mWriteNonBlocking = val;
-    return true;
-}
-
-/*
- * Specify whether a file descriptor can be inherited by a child process.
- * Under Linux this means setting the close-on-exec flag, under Windows
- * this is SetHandleInformation(HANDLE_FLAG_INHERIT).
- */
-bool Pipe::disallowReadInherit(void)
-{
-    if (mReadHandle == kInvalidHandle)
-        return false;
-
-#if defined(HAVE_WIN32_IPC)
-    if (SetHandleInformation((HANDLE) mReadHandle, HANDLE_FLAG_INHERIT, 0) == 0)
-        return false;
-#else
-    if (fcntl((int) mReadHandle, F_SETFD, FD_CLOEXEC) != 0)
-        return false;
-#endif
-    return true;
-}
-bool Pipe::disallowWriteInherit(void)
-{
-    if (mWriteHandle == kInvalidHandle)
-        return false;
-
-#if defined(HAVE_WIN32_IPC)
-    if (SetHandleInformation((HANDLE) mWriteHandle, HANDLE_FLAG_INHERIT, 0) == 0)
-        return false;
-#else
-    if (fcntl((int) mWriteHandle, F_SETFD, FD_CLOEXEC) != 0)
-        return false;
-#endif
-    return true;
-}
-
-/*
- * Close read descriptor.
- */
-bool Pipe::closeRead(void)
-{
-    if (mReadHandle == kInvalidHandle)
-        return false;
-
-#if defined(HAVE_WIN32_IPC)
-    if (mReadHandle != kInvalidHandle) {
-        if (!CloseHandle((HANDLE)mReadHandle)) {
-            LOG(LOG_WARN, "pipe", "failed closing read handle\n");
-            return false;
-        }
-    }
-#else
-    if (mReadHandle != kInvalidHandle) {
-        if (close((int) mReadHandle) != 0) {
-            LOG(LOG_WARN, "pipe", "failed closing read fd\n");
-            return false;
-        }
-    }
-#endif
-    mReadHandle = kInvalidHandle;
-    return true;
-}
-
-/*
- * Close write descriptor.
- */
-bool Pipe::closeWrite(void)
-{
-    if (mWriteHandle == kInvalidHandle)
-        return false;
-
-#if defined(HAVE_WIN32_IPC)
-    if (mWriteHandle != kInvalidHandle) {
-        if (!CloseHandle((HANDLE)mWriteHandle)) {
-            LOG(LOG_WARN, "pipe", "failed closing write handle\n");
-            return false;
-        }
-    }
-#else
-    if (mWriteHandle != kInvalidHandle) {
-        if (close((int) mWriteHandle) != 0) {
-            LOG(LOG_WARN, "pipe", "failed closing write fd\n");
-            return false;
-        }
-    }
-#endif
-    mWriteHandle = kInvalidHandle;
-    return true;
-}
-
-/*
- * Get the read handle.
- */
-unsigned long Pipe::getReadHandle(void)
-{
-    assert(mReadHandle != kInvalidHandle);
-
-    return mReadHandle;
-}
-
-/*
- * Get the write handle.
- */
-unsigned long Pipe::getWriteHandle(void)
-{
-    assert(mWriteHandle != kInvalidHandle);
-
-    return mWriteHandle;
-}
-
diff --git a/libs/utils/Socket.cpp b/libs/utils/Socket.cpp
deleted file mode 100644
index 51509a3..0000000
--- a/libs/utils/Socket.cpp
+++ /dev/null
@@ -1,388 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Internet address class.
-//
-
-#ifdef HAVE_WINSOCK
-// This needs to come first, or Cygwin gets concerned about a potential
-// clash between WinSock and <sys/types.h>.
-# include <winsock2.h>
-#endif
-
-#include <utils/Socket.h>
-#include <utils/inet_address.h>
-#include <utils/Log.h>
-#include <utils/Timers.h>
-
-#ifndef HAVE_WINSOCK
-# include <sys/types.h>
-# include <sys/socket.h>
-# include <netinet/in.h>
-# include <arpa/inet.h>
-#endif
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <errno.h>
-#include <assert.h>
-
-using namespace android;
-
-
-/*
- * ===========================================================================
- *      Socket
- * ===========================================================================
- */
-
-#ifndef INVALID_SOCKET
-# define INVALID_SOCKET (-1)
-#endif
-#define UNDEF_SOCKET   ((unsigned long) INVALID_SOCKET)
-
-/*static*/ bool Socket::mBootInitialized = false;
-
-/*
- * Extract system-dependent error code.
- */
-static inline int getSocketError(void) {
-#ifdef HAVE_WINSOCK
-    return WSAGetLastError();
-#else
-    return errno;
-#endif
-}
-
-/*
- * One-time initialization for socket code.
- */
-/*static*/ bool Socket::bootInit(void)
-{
-#ifdef HAVE_WINSOCK
-    WSADATA wsaData;
-    int err;
-
-    err = WSAStartup(MAKEWORD(2, 0), &wsaData);
-    if (err != 0) {
-        LOG(LOG_ERROR, "socket", "Unable to start WinSock\n");
-        return false;
-    }
-
-    LOG(LOG_INFO, "socket", "Using WinSock v%d.%d\n",
-        LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion));
-#endif
-
-    mBootInitialized = true;
-    return true;
-}
-
-/*
- * One-time shutdown for socket code.
- */
-/*static*/ void Socket::finalShutdown(void)
-{
-#ifdef HAVE_WINSOCK
-    WSACleanup();
-#endif
-    mBootInitialized = false;
-}
-
-
-/*
- * Simple constructor.  Allow the application to create us and then make
- * bind/connect calls.
- */
-Socket::Socket(void)
-    : mSock(UNDEF_SOCKET)
-{
-    if (!mBootInitialized)
-        LOG(LOG_WARN, "socket", "WARNING: sockets not initialized\n");
-}
-
-/*
- * Destructor.  Closes the socket and resets our storage.
- */
-Socket::~Socket(void)
-{
-    close();
-}
-
-
-/*
- * Create a socket and connect to the specified host and port.
- */
-int Socket::connect(const char* host, int port)
-{
-    if (mSock != UNDEF_SOCKET) {
-        LOG(LOG_WARN, "socket", "Socket already connected\n");
-        return -1;
-    }
-
-    InetSocketAddress sockAddr;
-    if (!sockAddr.create(host, port))
-        return -1;
-
-    //return doConnect(sockAddr);
-    int foo;
-    foo = doConnect(sockAddr);
-    return foo;
-}
-
-/*
- * Create a socket and connect to the specified host and port.
- */
-int Socket::connect(const InetAddress* addr, int port)
-{
-    if (mSock != UNDEF_SOCKET) {
-        LOG(LOG_WARN, "socket", "Socket already connected\n");
-        return -1;
-    }
-
-    InetSocketAddress sockAddr;
-    if (!sockAddr.create(addr, port))
-        return -1;
-
-    return doConnect(sockAddr);
-}
-
-/*
- * Finish creating a socket by connecting to the remote host.
- *
- * Returns 0 on success.
- */
-int Socket::doConnect(const InetSocketAddress& sockAddr)
-{
-#ifdef HAVE_WINSOCK
-    SOCKET sock;
-#else
-    int sock;
-#endif
-    const InetAddress* addr = sockAddr.getAddress();
-    int port = sockAddr.getPort();
-    struct sockaddr_in inaddr;
-    DurationTimer connectTimer;
-
-    assert(sizeof(struct sockaddr_in) == addr->getAddressLength());
-    memcpy(&inaddr, addr->getAddress(), addr->getAddressLength());
-    inaddr.sin_port = htons(port);
-
-    //fprintf(stderr, "--- connecting to %s:%d\n",
-    //    sockAddr.getHostName(), port);
-
-    sock = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
-    if (sock == INVALID_SOCKET) {
-        int err = getSocketError();
-        LOG(LOG_ERROR, "socket", "Unable to create socket (err=%d)\n", err);
-        return (err != 0) ? err : -1;
-    }
-
-    connectTimer.start();
-
-    if (::connect(sock, (struct sockaddr*) &inaddr, sizeof(inaddr)) != 0) {
-        int err = getSocketError();
-        LOG(LOG_WARN, "socket", "Connect to %s:%d failed: %d\n",
-            sockAddr.getHostName(), port, err);
-        return (err != 0) ? err : -1;
-    }
-
-    connectTimer.stop();
-    if ((long) connectTimer.durationUsecs() > 100000) {
-        LOG(LOG_INFO, "socket",
-            "Connect to %s:%d took %.3fs\n", sockAddr.getHostName(),
-            port, ((long) connectTimer.durationUsecs()) / 1000000.0);
-    }
-
-    mSock = (unsigned long) sock;
-    LOG(LOG_VERBOSE, "socket",
-        "--- connected to %s:%d\n", sockAddr.getHostName(), port);
-    return 0;
-}
-
-
-/*
- * Close the socket if it needs closing.
- */
-bool Socket::close(void)
-{
-    if (mSock != UNDEF_SOCKET) {
-        //fprintf(stderr, "--- closing socket %lu\n", mSock);
-#ifdef HAVE_WINSOCK
-        if (::closesocket((SOCKET) mSock) != 0)
-            return false;
-#else
-        if (::close((int) mSock) != 0)
-            return false;
-#endif
-    }
-
-    mSock = UNDEF_SOCKET;
-
-    return true;
-}
-
-/*
- * Read data from socket.
- *
- * Standard semantics: read up to "len" bytes into "buf".  Returns the
- * number of bytes read, or less than zero on error.
- */
-int Socket::read(void* buf, ssize_t len) const
-{
-    if (mSock == UNDEF_SOCKET) {
-        LOG(LOG_ERROR, "socket", "ERROR: read on invalid socket\n");
-        return -500;
-    }
-
-#ifdef HAVE_WINSOCK
-    SOCKET sock = (SOCKET) mSock;
-#else
-    int sock = (int) mSock;
-#endif
-    int cc;
-
-    cc = recv(sock, (char*)buf, len, 0);
-    if (cc < 0) {
-        int err = getSocketError();
-        return (err > 0) ? -err : -1;
-    }
-
-    return cc;
-}
-
-/*
- * Write data to a socket.
- *
- * Standard semantics: write up to "len" bytes into "buf".  Returns the
- * number of bytes written, or less than zero on error.
- */
-int Socket::write(const void* buf, ssize_t len) const
-{
-    if (mSock == UNDEF_SOCKET) {
-        LOG(LOG_ERROR, "socket", "ERROR: write on invalid socket\n");
-        return -500;
-    }
-
-#ifdef HAVE_WINSOCK
-    SOCKET sock = (SOCKET) mSock;
-#else
-    int sock = (int) mSock;
-#endif
-    int cc;
-
-    cc = send(sock, (const char*)buf, len, 0);
-    if (cc < 0) {
-        int err = getSocketError();
-        return (err > 0) ? -err : -1;
-    }
-
-    return cc;
-}
-
-
-/*
- * ===========================================================================
- *      Socket tests
- * ===========================================================================
- */
-
-/*
- * Read all data from the socket.  The data is read into a buffer that
- * expands as needed.
- *
- * On exit, the buffer is returned, and the length of the data is stored
- * in "*sz".  A null byte is added to the end, but is not included in
- * the length.
- */
-static char* socketReadAll(const Socket& s, int *sz)
-{
-    int max, r;
-    char *data, *ptr, *tmp;
-
-    data = (char*) malloc(max = 32768);
-    if (data == NULL)
-        return NULL;
-
-    ptr = data;
-    
-    for (;;) {
-        if ((ptr - data) == max) {
-            tmp = (char*) realloc(data, max *= 2);
-            if(tmp == 0) {
-                free(data);
-                return 0;
-            }
-        }
-        r = s.read(ptr, max - (ptr - data));
-        if (r == 0)
-            break;
-        if (r < 0) {
-            LOG(LOG_WARN, "socket", "WARNING: socket read failed (res=%d)\n",r);
-            break;
-        }
-        ptr += r;
-    }
-
-    if ((ptr - data) == max) {
-        tmp = (char*) realloc(data, max + 1);
-        if (tmp == NULL) {
-            free(data);
-            return NULL;
-        }
-    }
-    *ptr = '\0';
-    *sz = (ptr - data);
-    return data;
-}
-
-/*
- * Exercise the Socket class.
- */
-void android::TestSockets(void)
-{
-    printf("----- SOCKET TEST ------\n");
-    Socket::bootInit();
-
-    char* buf = NULL;
-    int len, cc;
-    const char* kTestStr =
-        "GET / HTTP/1.0\n"
-        "Connection: close\n"
-        "\n";
-
-    Socket sock;
-    if (sock.connect("www.google.com", 80) != 0) {
-        fprintf(stderr, "socket connected failed\n");
-        goto bail;
-    }
-
-    cc = sock.write(kTestStr, strlen(kTestStr));
-    if (cc != (int) strlen(kTestStr)) {
-        fprintf(stderr, "write failed, res=%d\n", cc);
-        goto bail;
-    }
-    buf = socketReadAll(sock, &len);
-
-    printf("GOT '%s'\n", buf);
-
-bail:
-    sock.close();
-    free(buf);
-}
-
diff --git a/libs/utils/Static.cpp b/libs/utils/Static.cpp
index 93f7e4f..4dfa578 100644
--- a/libs/utils/Static.cpp
+++ b/libs/utils/Static.cpp
@@ -20,7 +20,6 @@
 #include <private/utils/Static.h>
 
 #include <utils/BufferedTextOutput.h>
-#include <utils/IPCThreadState.h>
 #include <utils/Log.h>
 
 namespace android {
@@ -87,34 +86,4 @@
 TextOutput& aout(gStdoutTextOutput);
 TextOutput& aerr(gStderrTextOutput);
 
-#ifndef LIBUTILS_NATIVE
-
-// ------------ ProcessState.cpp
-
-Mutex gProcessMutex;
-sp<ProcessState> gProcess;
-
-class LibUtilsIPCtStatics
-{
-public:
-    LibUtilsIPCtStatics()
-    {
-    }
-    
-    ~LibUtilsIPCtStatics()
-    {
-        IPCThreadState::shutdown();
-    }
-};
-
-static LibUtilsIPCtStatics gIPCStatics;
-
-// ------------ ServiceManager.cpp
-
-Mutex gDefaultServiceManagerLock;
-sp<IServiceManager> gDefaultServiceManager;
-sp<IPermissionController> gPermissionController;
-
-#endif
-
 }   // namespace android
diff --git a/libs/utils/StringArray.cpp b/libs/utils/StringArray.cpp
new file mode 100644
index 0000000..aa42d68
--- /dev/null
+++ b/libs/utils/StringArray.cpp
@@ -0,0 +1,113 @@
+/*
+ * 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.
+ */
+
+//
+// Sortable array of strings.  STL-ish, but STL-free.
+//  
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <utils/StringArray.h>
+
+namespace android {
+
+//
+// An expanding array of strings.  Add, get, sort, delete.
+//
+StringArray::StringArray()
+    : mMax(0), mCurrent(0), mArray(NULL)
+{
+}
+
+StringArray:: ~StringArray() {
+    for (int i = 0; i < mCurrent; i++)
+        delete[] mArray[i];
+    delete[] mArray;
+}
+
+//
+// Add a string.  A copy of the string is made.
+//
+bool StringArray::push_back(const char* str) {
+    if (mCurrent >= mMax) {
+        char** tmp;
+
+        if (mMax == 0)
+            mMax = 16;      // initial storage
+        else
+            mMax *= 2;
+
+        tmp = new char*[mMax];
+        if (tmp == NULL)
+            return false;
+
+        memcpy(tmp, mArray, mCurrent * sizeof(char*));
+        delete[] mArray;
+        mArray = tmp;
+    }
+
+    int len = strlen(str);
+    mArray[mCurrent] = new char[len+1];
+    memcpy(mArray[mCurrent], str, len+1);
+    mCurrent++;
+
+    return true;
+}
+
+//
+// Delete an entry.
+//
+void StringArray::erase(int idx) {
+    if (idx < 0 || idx >= mCurrent)
+        return;
+    delete[] mArray[idx];
+    if (idx < mCurrent-1) {
+        memmove(&mArray[idx], &mArray[idx+1],
+                (mCurrent-1 - idx) * sizeof(char*));
+    }
+    mCurrent--;
+}
+
+//
+// Sort the array.
+//
+void StringArray::sort(int (*compare)(const void*, const void*)) {
+    qsort(mArray, mCurrent, sizeof(char*), compare);
+}
+
+//
+// Pass this to the sort routine to do an ascending alphabetical sort.
+//
+int StringArray::cmpAscendingAlpha(const void* pstr1, const void* pstr2) {
+    return strcmp(*(const char**)pstr1, *(const char**)pstr2);
+}
+
+//
+// Set entry N to specified string.
+// [should use operator[] here]
+//
+void StringArray::setEntry(int idx, const char* str) {
+    if (idx < 0 || idx >= mCurrent)
+        return;
+    delete[] mArray[idx];
+    int len = strlen(str);
+    mArray[idx] = new char[len+1];
+    memcpy(mArray[idx], str, len+1);
+}
+
+
+}; // namespace android
diff --git a/libs/utils/TextOutput.cpp b/libs/utils/TextOutput.cpp
index cebee99..e04823d 100644
--- a/libs/utils/TextOutput.cpp
+++ b/libs/utils/TextOutput.cpp
@@ -22,9 +22,17 @@
 #include <stdlib.h>
 #include <string.h>
 
+namespace android {
+
 // ---------------------------------------------------------------------------
 
-namespace android {
+TextOutput::TextOutput() { 
+}
+
+TextOutput::~TextOutput() { 
+}
+
+// ---------------------------------------------------------------------------
 
 TextOutput& operator<<(TextOutput& to, bool val)
 {
diff --git a/libs/utils/Threads.cpp b/libs/utils/Threads.cpp
index 9287c0b..4036c49 100644
--- a/libs/utils/Threads.cpp
+++ b/libs/utils/Threads.cpp
@@ -38,10 +38,6 @@
 # define HAVE_CREATETHREAD  // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
 #endif
 
-#if defined(HAVE_FUTEX)
-#include <private/utils/futex_synchro.h>
-#endif
-
 #if defined(HAVE_PRCTL)
 #include <sys/prctl.h>
 #endif
@@ -56,10 +52,6 @@
 
 // ----------------------------------------------------------------------------
 #if defined(HAVE_PTHREADS)
-#if 0
-#pragma mark -
-#pragma mark PTHREAD
-#endif
 // ----------------------------------------------------------------------------
 
 /*
@@ -163,10 +155,6 @@
 
 // ----------------------------------------------------------------------------
 #elif defined(HAVE_WIN32_THREADS)
-#if 0
-#pragma mark -
-#pragma mark WIN32_THREADS
-#endif
 // ----------------------------------------------------------------------------
 
 /*
@@ -252,11 +240,6 @@
 
 // ----------------------------------------------------------------------------
 
-#if 0
-#pragma mark -
-#pragma mark Common Thread functions
-#endif
-
 int androidCreateThread(android_thread_func_t fn, void* arg)
 {
     return createThreadEtc(fn, arg);
@@ -294,109 +277,9 @@
  * ===========================================================================
  */
 
-#if 0
-#pragma mark -
-#pragma mark Mutex
-#endif
-
-#if defined(HAVE_PTHREADS) && !defined(HAVE_FUTEX)
-/*
- * Simple pthread wrapper.
- */
-
-Mutex::Mutex()
-{
-    _init();
-}
-
-Mutex::Mutex(const char* name)
-{
-    // XXX: name not used for now
-    _init();
-}
-
-void Mutex::_init()
-{
-    pthread_mutex_t* pMutex = new pthread_mutex_t;
-    pthread_mutex_init(pMutex, NULL);
-    mState = pMutex;
-}
-
-Mutex::~Mutex()
-{
-    delete (pthread_mutex_t*) mState;
-}
-
-status_t Mutex::lock()
-{
-    int res;
-    while ((res=pthread_mutex_lock((pthread_mutex_t*) mState)) == EINTR) ;
-    return -res;
-}
-
-void Mutex::unlock()
-{
-    pthread_mutex_unlock((pthread_mutex_t*) mState);
-}
-
-status_t Mutex::tryLock()
-{
-    int res;
-    while ((res=pthread_mutex_trylock((pthread_mutex_t*) mState)) == EINTR) ;
-    return -res;
-}
-
-#elif defined(HAVE_FUTEX)
-#if 0
-#pragma mark -
-#endif
-
-#define STATE ((futex_mutex_t*) (&mState))
-
-Mutex::Mutex()
-{
-    _init();
-}
-
-Mutex::Mutex(const char* name)
-{
-    _init();
-}
-
-void
-Mutex::_init()
-{
-    futex_mutex_init(STATE);
-}
-
-Mutex::~Mutex()
-{
-}
-
-status_t Mutex::lock()
-{
-    int res;
-    while ((res=futex_mutex_lock(STATE, FUTEX_WAIT_INFINITE)) == EINTR) ;
-    return -res;
-}
-
-void Mutex::unlock()
-{
-    futex_mutex_unlock(STATE);
-}
-
-status_t Mutex::tryLock()
-{
-    int res;
-    while ((res=futex_mutex_trylock(STATE)) == EINTR) ;
-    return -res;
-}
-#undef STATE
-
+#if defined(HAVE_PTHREADS)
+// implemented as inlines in threads.h
 #elif defined(HAVE_WIN32_THREADS)
-#if 0
-#pragma mark -
-#endif
 
 Mutex::Mutex()
 {
@@ -456,161 +339,9 @@
  * ===========================================================================
  */
 
-#if 0
-#pragma mark -
-#pragma mark Condition
-#endif
-
-#if defined(HAVE_PTHREADS) && !defined(HAVE_FUTEX)
-
-/*
- * Constructor.  This is a simple pthread wrapper.
- */
-Condition::Condition()
-{
-    pthread_cond_t* pCond = new pthread_cond_t;
-
-    pthread_cond_init(pCond, NULL);
-    mState = pCond;
-}
-
-/*
- * Destructor.
- */
-Condition::~Condition()
-{
-    pthread_cond_destroy((pthread_cond_t*) mState);
-    delete (pthread_cond_t*) mState;
-}
-
-/*
- * Wait on a condition variable.  Lock the mutex before calling.
- */
-
-status_t Condition::wait(Mutex& mutex)
-{
-    assert(mutex.mState != NULL);
-
-    int cc;
-    while ((cc = pthread_cond_wait((pthread_cond_t*)mState,
-                (pthread_mutex_t*) mutex.mState)) == EINTR) ;
-    return -cc;
-}
-
-status_t Condition::wait(Mutex& mutex, nsecs_t abstime)
-{
-    assert(mutex.mState != NULL);
-
-    struct timespec ts;
-    ts.tv_sec = abstime/1000000000;
-    ts.tv_nsec = abstime-(ts.tv_sec*1000000000);
-    
-    int cc;
-    while ((cc = pthread_cond_timedwait((pthread_cond_t*)mState,
-            (pthread_mutex_t*) mutex.mState, &ts)) == EINTR) ;
-    return -cc;
-}
-
-status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
-{
-    return wait(mutex, systemTime()+reltime);
-}
-
-/*
- * Signal the condition variable, allowing one thread to continue.
- */
-void Condition::signal()
-{
-    pthread_cond_signal((pthread_cond_t*) mState);
-}
-
-/*
- * Signal the condition variable, allowing all threads to continue.
- */
-void Condition::broadcast()
-{
-    pthread_cond_broadcast((pthread_cond_t*) mState);
-}
-
-#elif defined(HAVE_FUTEX)
-#if 0
-#pragma mark -
-#endif
-
-#define STATE ((futex_cond_t*) (&mState))
-
-/*
- * Constructor.  This is a simple pthread wrapper.
- */
-Condition::Condition()
-{
-    futex_cond_init(STATE);
-}
-
-/*
- * Destructor.
- */
-Condition::~Condition()
-{
-}
-
-/*
- * Wait on a condition variable.  Lock the mutex before calling.
- */
-
-status_t Condition::wait(Mutex& mutex)
-{
-    assert(mutex.mState != NULL);
-
-    int res;
-    while ((res = futex_cond_wait(STATE,
-        (futex_mutex_t*)(&mutex.mState), FUTEX_WAIT_INFINITE)) == -EINTR) ;
-
-    return -res;
-}
-
-status_t Condition::wait(Mutex& mutex, nsecs_t abstime)
-{
-    nsecs_t reltime = abstime - systemTime();
-    if (reltime <= 0) return true;
-    return waitRelative(mutex, reltime);
-}
-
-status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
-{
-    assert(mutex.mState != NULL);
-    int res;
-    unsigned msec = ns2ms(reltime);
-    if(msec == 0)
-        return true;
-    // This code will not time out at the correct time if interrupted by signals
-    while ((res = futex_cond_wait(STATE,
-        (futex_mutex_t*)(&mutex.mState), msec)) == -EINTR) ;
-    return res;
-}
-
-/*
- * Signal the condition variable, allowing one thread to continue.
- */
-void Condition::signal()
-{
-    futex_cond_signal(STATE);
-}
-
-/*
- * Signal the condition variable, allowing all threads to continue.
- */
-void Condition::broadcast()
-{
-    futex_cond_broadcast(STATE);
-}
-
-#undef STATE
-
+#if defined(HAVE_PTHREADS)
+// implemented as inlines in threads.h
 #elif defined(HAVE_WIN32_THREADS)
-#if 0
-#pragma mark -
-#endif
 
 /*
  * Windows doesn't have a condition variable solution.  It's possible
@@ -753,14 +484,6 @@
     return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
 }
 
-status_t Condition::wait(Mutex& mutex, nsecs_t abstime)
-{
-    WinCondition* condState = (WinCondition*) mState;
-    HANDLE hMutex = (HANDLE) mutex.mState;
-
-    return ((WinCondition*)mState)->wait(condState, hMutex, &abstime);
-}
-
 status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
 {
     return wait(mutex, systemTime()+reltime);
@@ -841,11 +564,6 @@
 
 // ----------------------------------------------------------------------------
 
-#if 0
-#pragma mark -
-#pragma mark Thread::Thread
-#endif
-
 /*
  * This is our thread object!
  */
diff --git a/libs/utils/TimerProbe.cpp b/libs/utils/TimerProbe.cpp
deleted file mode 100644
index 835480d..0000000
--- a/libs/utils/TimerProbe.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <utils/TimerProbe.h>
- 
-#if ENABLE_TIMER_PROBE
-
-#ifdef LOG_TAG
-#undef LOG_TAG
-#endif
-#define LOG_TAG "time"
-
-namespace android {
-
-Vector<TimerProbe::Bucket> TimerProbe::gBuckets;
-TimerProbe* TimerProbe::gExecuteChain;
-int TimerProbe::gIndent;
-timespec TimerProbe::gRealBase;
-
-TimerProbe::TimerProbe(const char tag[], int* slot) : mTag(tag)
-{
-    mNext = gExecuteChain;
-    gExecuteChain = this;
-    mIndent = gIndent;
-    gIndent += 1;
-    if (mIndent > 0) {
-        if (*slot == 0) {
-            int count = gBuckets.add();
-            *slot = count;
-            Bucket& bucket = gBuckets.editItemAt(count);
-            memset(&bucket, 0, sizeof(Bucket));
-            bucket.mTag = tag;
-            bucket.mSlotPtr = slot;
-            bucket.mIndent = mIndent;
-        }
-        mBucket = *slot;
-    }
-    clock_gettime(CLOCK_REALTIME, &mRealStart);
-    if (gRealBase.tv_sec == 0)
-        gRealBase = mRealStart;
-    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mPStart);
-    clock_gettime(CLOCK_THREAD_CPUTIME_ID, &mTStart);
-}
-
-void TimerProbe::end()
-{
-    timespec realEnd, pEnd, tEnd;
-    clock_gettime(CLOCK_REALTIME, &realEnd);
-    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &pEnd);
-    clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tEnd);
-    print(realEnd, pEnd, tEnd);
-    mTag = NULL;
-}
-
-TimerProbe::~TimerProbe()
-{
-    if (mTag != NULL)
-        end();
-    gExecuteChain = mNext;
-    gIndent--;
-}
-
-
-uint32_t TimerProbe::ElapsedTime(const timespec& start, const timespec& end)
-{
-    int sec = end.tv_sec - start.tv_sec;
-    int nsec = end.tv_nsec - start.tv_nsec;
-    if (nsec < 0) {
-        sec--;
-        nsec += 1000000000;
-    }
-    return sec * 1000000 + nsec / 1000;
-}
-
-void TimerProbe::print(const timespec& r, const timespec& p,
-        const timespec& t) const
-{
-    uint32_t es = ElapsedTime(gRealBase, mRealStart);
-    uint32_t er = ElapsedTime(mRealStart, r);
-    uint32_t ep = ElapsedTime(mPStart, p);
-    uint32_t et = ElapsedTime(mTStart, t);
-    if (mIndent > 0) {
-        Bucket& bucket = gBuckets.editItemAt(mBucket);
-        if (bucket.mStart == 0)
-            bucket.mStart = es;
-        bucket.mReal += er;
-        bucket.mProcess += ep;
-        bucket.mThread += et;
-        bucket.mCount++;
-        return;
-    }
-    int index = 0;
-    int buckets = gBuckets.size();
-    int count = 1;
-    const char* tag = mTag;
-    int indent = mIndent;
-    do {
-        LOGD("%-30.30s: (%3d) %-5.*s time=%-10.3f real=%7dus process=%7dus (%3d%%) thread=%7dus (%3d%%)\n", 
-            tag, count, indent > 5 ? 5 : indent, "+++++", es / 1000000.0,
-            er, ep, ep * 100 / er, et, et * 100 / er);
-        if (index >= buckets)
-            break;
-        Bucket& bucket = gBuckets.editItemAt(index);
-        count = bucket.mCount;
-        es = bucket.mStart;
-        er = bucket.mReal;
-        ep = bucket.mProcess;
-        et = bucket.mThread;
-        tag = bucket.mTag;
-        indent = bucket.mIndent;
-        *bucket.mSlotPtr = 0;
-    } while (++index); // always true
-    gBuckets.clear();
-}
-
-}; // namespace android
-
-#endif
diff --git a/libs/utils/Timers.cpp b/libs/utils/Timers.cpp
index 2abc811..784f035 100644
--- a/libs/utils/Timers.cpp
+++ b/libs/utils/Timers.cpp
@@ -18,7 +18,6 @@
 // Timer functions.
 //
 #include <utils/Timers.h>
-#include <utils/ported.h>     // may need usleep
 #include <utils/Log.h>
 
 #include <stdlib.h>
@@ -54,130 +53,6 @@
 #endif
 }
 
-//#define MONITOR_USLEEP
-
-/*
- * Sleep long enough that we'll wake up "interval" milliseconds after
- * the previous snooze.
- *
- * The "nextTick" argument is updated on each call, and should be passed
- * in every time.  Set its fields to zero on the first call.
- *
- * Returns the #of intervals we have overslept, which will be zero if we're
- * on time.  [Currently just returns 0 or 1.]
- */
-int sleepForInterval(long interval, struct timeval* pNextTick)
-{
-    struct timeval now;
-    long long timeBeforeNext;
-    long sleepTime = 0;
-    bool overSlept = false;
-    //int usleepBias = 0;
-
-#ifdef USLEEP_BIAS
-    /*
-     * Linux likes to add 9000ms or so.
-     * [not using this for now]
-     */
-    //usleepBias = USLEEP_BIAS;
-#endif
-
-    gettimeofday(&now, NULL);
-
-    if (pNextTick->tv_sec == 0) {
-        /* special-case for first time through */
-        *pNextTick = now;
-        sleepTime = interval;
-        android::DurationTimer::addToTimeval(pNextTick, interval);
-    } else {
-        /*
-         * Compute how much time there is before the next tick.  If this
-         * value is negative, we've run over.  If we've run over a little
-         * bit we can shorten the next frame to keep the pace steady, but
-         * if we've dramatically overshot we need to re-sync.
-         */
-        timeBeforeNext = android::DurationTimer::subtractTimevals(pNextTick, &now);
-        //printf("TOP: now=%ld.%ld next=%ld.%ld diff=%ld\n",
-        //    now.tv_sec, now.tv_usec, pNextTick->tv_sec, pNextTick->tv_usec,
-        //    (long) timeBeforeNext);
-        if (timeBeforeNext < -interval) {
-            /* way over */
-            overSlept = true;
-            sleepTime = 0;
-            *pNextTick = now;
-        } else if (timeBeforeNext <= 0) {
-            /* slightly over, keep the pace steady */
-            overSlept = true;
-            sleepTime = 0;
-        } else if (timeBeforeNext <= interval) {
-            /* right on schedule */
-            sleepTime = timeBeforeNext;
-        } else if (timeBeforeNext > interval && timeBeforeNext <= 2*interval) {
-            /* sleep call returned early; do a longer sleep this time */
-            sleepTime = timeBeforeNext;
-        } else if (timeBeforeNext > interval) {
-            /* we went back in time -- somebody updated system clock? */
-            /* (could also be a *seriously* broken usleep()) */
-            LOG(LOG_DEBUG, "",
-                " Impossible: timeBeforeNext = %ld\n", (long)timeBeforeNext);
-            sleepTime = 0;
-            *pNextTick = now;
-        }
-        android::DurationTimer::addToTimeval(pNextTick, interval);
-    }
-    //printf(" Before sleep: now=%ld.%ld next=%ld.%ld sleepTime=%ld\n",
-    //    now.tv_sec, now.tv_usec, pNextTick->tv_sec, pNextTick->tv_usec,
-    //    sleepTime);
-
-    /*
-     * Sleep for the designated period of time.
-     *
-     * Linux tends to sleep for longer than requested, often by 17-18ms.
-     * MinGW tends to sleep for less than requested, by as much as 14ms,
-     * but occasionally oversleeps for 40+ms (looks like some external
-     * factors plus round-off on a 64Hz clock).  Cygwin is pretty steady.
-     *
-     * If you start the MinGW version, and then launch the Cygwin version,
-     * the MinGW clock becomes more erratic.  Not entirely sure why.
-     *
-     * (There's a lot of stuff here; it's really just a usleep() call with
-     * a bunch of instrumentation.)
-     */
-    if (sleepTime > 0) {
-#if defined(MONITOR_USLEEP)
-        struct timeval before, after;
-        long long actual;
-
-        gettimeofday(&before, NULL);
-        usleep((long) sleepTime);
-        gettimeofday(&after, NULL);
-
-        /* check usleep() accuracy; default Linux threads are pretty sloppy */
-        actual = android::DurationTimer::subtractTimevals(&after, &before);
-        if ((long) actual < sleepTime - 14000 /*(sleepTime/10)*/ ||
-            (long) actual > sleepTime + 20000 /*(sleepTime/10)*/)
-        {
-            LOG(LOG_DEBUG, "", " Odd usleep: req=%ld, actual=%ld\n", sleepTime,
-                (long) actual);
-        }
-#else
-#ifdef HAVE_WIN32_THREADS
-        Sleep( sleepTime/1000 );
-#else        
-        usleep((long) sleepTime);
-#endif        
-#endif
-    }
-
-    //printf("slept %d\n", sleepTime);
-
-    if (overSlept)
-        return 1;       // close enough
-    else
-        return 0;
-}
-
-
 /*
  * ===========================================================================
  *      DurationTimer
diff --git a/libs/utils/executablepath_darwin.cpp b/libs/utils/executablepath_darwin.cpp
deleted file mode 100644
index 2e3c3a0..0000000
--- a/libs/utils/executablepath_darwin.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <utils/executablepath.h>
-#import <Carbon/Carbon.h>
-#include <unistd.h>
-
-void executablepath(char s[PATH_MAX])
-{
-    ProcessSerialNumber psn;
-    GetCurrentProcess(&psn);
-    CFDictionaryRef dict;
-    dict = ProcessInformationCopyDictionary(&psn, 0xffffffff);
-    CFStringRef value = (CFStringRef)CFDictionaryGetValue(dict,
-                CFSTR("CFBundleExecutable"));
-    CFStringGetCString(value, s, PATH_MAX+1, kCFStringEncodingUTF8);
-}
-
diff --git a/libs/utils/futex_synchro.c b/libs/utils/futex_synchro.c
deleted file mode 100644
index ab48c69..0000000
--- a/libs/utils/futex_synchro.c
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <limits.h>
-
-#include <sys/time.h>
-#include <sched.h>
-
-#include <errno.h>
-
-#include <private/utils/futex_synchro.h>
-
-
-// This futex glue code is need on desktop linux, but is already part of bionic.
-#if !defined(HAVE_FUTEX_WRAPPERS)
-
-#include <unistd.h>
-#include <sys/syscall.h>
-typedef unsigned int u32;
-#define asmlinkage
-#define __user
-#include <linux/futex.h>
-#include <utils/Atomic.h>
-
-
-int futex (int *uaddr, int op, int val, const struct timespec *timeout, int *uaddr2, int val3)
-{
-    int err = syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
-    return err == 0 ? 0 : -errno;
-}
-
-int __futex_wait(volatile void *ftx, int val, const struct timespec *timeout)
-{
-    return futex((int*)ftx, FUTEX_WAIT, val, timeout, NULL, 0);
-}
-
-int __futex_wake(volatile void *ftx, int count)
-{
-    return futex((int*)ftx, FUTEX_WAKE, count, NULL, NULL, 0);
-}
-
-int __atomic_cmpxchg(int old, int _new, volatile int *ptr)
-{
-    return android_atomic_cmpxchg(old, _new, ptr);
-}
-
-int __atomic_swap(int _new, volatile int *ptr)
-{
-    return android_atomic_swap(_new, ptr);
-}
-
-int __atomic_dec(volatile int *ptr)
-{
-    return android_atomic_dec(ptr);
-}
-
-#else // !defined(__arm__)
-
-int __futex_wait(volatile void *ftx, int val, const struct timespec *timeout);
-int __futex_wake(volatile void *ftx, int count);
-
-int __atomic_cmpxchg(int old, int _new, volatile int *ptr);
-int __atomic_swap(int _new, volatile int *ptr);
-int __atomic_dec(volatile int *ptr);
-
-#endif // !defined(HAVE_FUTEX_WRAPPERS)
-
-
-// lock states
-//
-// 0: unlocked
-// 1: locked, no waiters
-// 2: locked, maybe waiters
-
-void futex_mutex_init(futex_mutex_t *m)
-{
-    m->value = 0;
-}
-
-int futex_mutex_lock(futex_mutex_t *m, unsigned msec)
-{
-    if(__atomic_cmpxchg(0, 1, &m->value) == 0) {
-        return 0;
-    }
-    if(msec == FUTEX_WAIT_INFINITE) {
-        while(__atomic_swap(2, &m->value) != 0) {
-            __futex_wait(&m->value, 2, 0);
-        }
-    } else {
-        struct timespec ts;
-        ts.tv_sec = msec / 1000;
-        ts.tv_nsec = (msec % 1000) * 1000000;
-        while(__atomic_swap(2, &m->value) != 0) {
-            if(__futex_wait(&m->value, 2, &ts) == -ETIMEDOUT) {
-                return -1;
-            }
-        }
-    }
-    return 0;
-}
-
-int futex_mutex_trylock(futex_mutex_t *m)
-{
-    if(__atomic_cmpxchg(0, 1, &m->value) == 0) {
-        return 0;
-    }
-    return -1;
-}
-
-void futex_mutex_unlock(futex_mutex_t *m)
-{
-    if(__atomic_dec(&m->value) != 1) {
-        m->value = 0;
-        __futex_wake(&m->value, 1);
-    }
-}
-
-/* XXX *technically* there is a race condition that could allow
- * XXX a signal to be missed.  If thread A is preempted in _wait()
- * XXX after unlocking the mutex and before waiting, and if other
- * XXX threads call signal or broadcast UINT_MAX times (exactly),
- * XXX before thread A is scheduled again and calls futex_wait(),
- * XXX then the signal will be lost.
- */
-
-void futex_cond_init(futex_cond_t *c)
-{
-    c->value = 0;
-}
-
-int futex_cond_wait(futex_cond_t *c, futex_mutex_t *m, unsigned msec)
-{
-    if(msec == FUTEX_WAIT_INFINITE){
-        int oldvalue = c->value;
-        futex_mutex_unlock(m);
-        __futex_wait(&c->value, oldvalue, 0);
-        futex_mutex_lock(m, FUTEX_WAIT_INFINITE);
-        return 0;
-    } else {
-        int oldvalue = c->value;
-        struct timespec ts;        
-        ts.tv_sec = msec / 1000;
-        ts.tv_nsec = (msec % 1000) * 1000000;
-        futex_mutex_unlock(m);
-        const int err = __futex_wait(&c->value, oldvalue, &ts);
-        futex_mutex_lock(m, FUTEX_WAIT_INFINITE);
-        return err;
-    }
-}
-
-void futex_cond_signal(futex_cond_t *c)
-{
-    __atomic_dec(&c->value);
-    __futex_wake(&c->value, 1);
-}
-
-void futex_cond_broadcast(futex_cond_t *c)
-{
-    __atomic_dec(&c->value);
-    __futex_wake(&c->value, INT_MAX);
-}
-
diff --git a/libs/utils/ported.cpp b/libs/utils/ported.cpp
deleted file mode 100644
index 656e46f..0000000
--- a/libs/utils/ported.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Ports of standard functions that don't exist on a specific platform.
-//
-// Note these are NOT in the "android" namespace.
-//
-#include <utils/ported.h>
-
-#if defined(NEED_GETTIMEOFDAY) || defined(NEED_USLEEP)
-# include <sys/time.h>
-# include <windows.h>
-#endif
-
-
-#if defined(NEED_GETTIMEOFDAY)
-/*
- * Replacement gettimeofday() for Windows environments (primarily MinGW).
- *
- * Ignores "tz".
- */
-int gettimeofday(struct timeval* ptv, struct timezone* tz)
-{
-    long long nsTime;   // time in 100ns units since Jan 1 1601
-    FILETIME ft;
-
-    if (tz != NULL) {
-        // oh well
-    }
-
-    ::GetSystemTimeAsFileTime(&ft);
-    nsTime = (long long) ft.dwHighDateTime << 32 |
-             (long long) ft.dwLowDateTime;
-    // convert to time in usec since Jan 1 1970
-    ptv->tv_usec = (long) ((nsTime / 10LL) % 1000000LL);
-    ptv->tv_sec = (long) ((nsTime - 116444736000000000LL) / 10000000LL);
-
-    return 0;
-}
-#endif
-
-#if defined(NEED_USLEEP)
-//
-// Replacement usleep for Windows environments (primarily MinGW).
-//
-void usleep(unsigned long usec)
-{
-    // Win32 API function Sleep() takes milliseconds
-    ::Sleep((usec + 500) / 1000);
-}
-#endif
-
-#if 0 //defined(NEED_PIPE)
-//
-// Replacement pipe() command for MinGW
-//
-// The _O_NOINHERIT flag sets bInheritHandle to FALSE in the
-// SecurityAttributes argument to CreatePipe().  This means the handles
-// aren't inherited when a new process is created.  The examples I've seen
-// use it, possibly because there's a lot of junk going on behind the
-// scenes.  (I'm assuming "process" and "thread" are different here, so
-// we should be okay spinning up a thread.)  The recommended practice is
-// to dup() the descriptor you want the child to have.
-//
-// It appears that unnamed pipes can't do non-blocking ("overlapped") I/O.
-// You can't use select() either, since that only works on sockets.  The
-// Windows API calls that are useful here all operate on a HANDLE, not
-// an integer file descriptor, and I don't think you can get there from
-// here.  The "named pipe" stuff is insane.
-//
-int pipe(int filedes[2])
-{
-    return _pipe(filedes, 0, _O_BINARY | _O_NOINHERIT);
-}
-#endif
-
-#if defined(NEED_SETENV)
-/*
- * MinGW lacks these.  For now, just stub them out so the code compiles.
- */
-int setenv(const char* name, const char* value, int overwrite)
-{
-    return 0;
-}
-void unsetenv(const char* name)
-{
-}
-char* getenv(const char* name)
-{
-    return NULL;
-}
-#endif
diff --git a/location/java/android/location/Geocoder.java b/location/java/android/location/Geocoder.java
index 53e46b7..2ce1273 100644
--- a/location/java/android/location/Geocoder.java
+++ b/location/java/android/location/Geocoder.java
@@ -36,11 +36,11 @@
  * coordinate into a (partial) address.  The amount of detail in a
  * reverse geocoded location description may vary, for example one
  * might contain the full street address of the closest building, while
- * another might contain only a city name and postal code. 
+ * another might contain only a city name and postal code.
  *
  * The Geocoder class requires a backend service that is not included in
- * the core android framework. The Geocoder query methods will return an
- * empty list if there no backend service in the platform. 
+ * the core android framework.  The Geocoder query methods will return an
+ * empty list if there no backend service in the platform.
  */
 public final class Geocoder {
     private static final String TAG = "Geocoder";
diff --git a/location/java/android/location/LocationManager.java b/location/java/android/location/LocationManager.java
index 86ea66f..ca16f19 100644
--- a/location/java/android/location/LocationManager.java
+++ b/location/java/android/location/LocationManager.java
@@ -68,7 +68,7 @@
      * satellites. Depending on conditions, this provider may take a while to return
      * a location fix.
      *
-     * Requires the permission android.permissions.ACCESS_FINE_LOCATION.
+     * Requires the permission android.permission.ACCESS_FINE_LOCATION.
      *
      * <p> The extras Bundle for the GPS location provider can contain the
      * following key/value pairs:
diff --git a/location/java/com/android/internal/location/GpsLocationProvider.java b/location/java/com/android/internal/location/GpsLocationProvider.java
index 4a51e31..9e1a72c 100755
--- a/location/java/com/android/internal/location/GpsLocationProvider.java
+++ b/location/java/com/android/internal/location/GpsLocationProvider.java
@@ -38,6 +38,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.SystemClock;
+import android.provider.Settings;
 import android.util.Config;
 import android.util.Log;
 import android.util.SparseIntArray;
@@ -183,8 +184,6 @@
     // number of fixes we have received since we started navigating
     private int mFixCount;
 
-    private int mPositionMode = GPS_POSITION_MODE_STANDALONE;
-
     // true if we started navigation
     private boolean mStarted;
 
@@ -355,8 +354,6 @@
                 try {
                     int port = Integer.parseInt(portString);
                     native_set_agps_server(AGPS_TYPE_SUPL, host, port);
-                    // use MS-Based position mode if SUPL support is enabled
-                    mPositionMode = GPS_POSITION_MODE_MS_BASED;
                 } catch (NumberFormatException e) {
                     Log.e(TAG, "unable to parse SUPL_PORT: " + portString);
                 }
@@ -368,8 +365,6 @@
                 try {
                     int port = Integer.parseInt(portString);
                     native_set_agps_server(AGPS_TYPE_C2K, host, port);
-                    // use MS-Based position mode if SUPL support is enabled
-                    mPositionMode = GPS_POSITION_MODE_MS_BASED;
                 } catch (NumberFormatException e) {
                     Log.e(TAG, "unable to parse C2K_PORT: " + portString);
                 }
@@ -722,7 +717,15 @@
         if (!mStarted) {
             if (DEBUG) Log.d(TAG, "startNavigating");
             mStarted = true;
-            if (!native_start(mPositionMode, false, mFixInterval)) {
+            int positionMode;
+            if (Settings.Secure.getInt(mContext.getContentResolver(),
+                    Settings.Secure.ASSISTED_GPS_ENABLED, 0) != 0) {
+                positionMode = GPS_POSITION_MODE_MS_BASED;
+            } else {
+                positionMode = GPS_POSITION_MODE_STANDALONE;
+            }
+
+            if (!native_start(positionMode, false, mFixInterval)) {
                 mStarted = false;
                 Log.e(TAG, "native_start failed in startNavigating()");
                 return;
diff --git a/location/java/com/android/internal/location/GpsXtraDownloader.java b/location/java/com/android/internal/location/GpsXtraDownloader.java
index 2a8be57..33ebce7 100644
--- a/location/java/com/android/internal/location/GpsXtraDownloader.java
+++ b/location/java/com/android/internal/location/GpsXtraDownloader.java
@@ -64,6 +64,7 @@
         
         if (count == 0) {
             Log.e(TAG, "No XTRA servers were specified in the GPS configuration");
+            return;
         } else {
             mXtraServers = new String[count];
             count = 0;
diff --git a/media/java/android/media/AudioFormat.java b/media/java/android/media/AudioFormat.java
index 0732b61..500f6a4 100644
--- a/media/java/android/media/AudioFormat.java
+++ b/media/java/android/media/AudioFormat.java
@@ -37,15 +37,58 @@
     public static final int ENCODING_PCM_8BIT = 3;  // accessed by native code
 
     /** Invalid audio channel configuration */
-    public static final int CHANNEL_CONFIGURATION_INVALID   = 0;
+    /** @deprecated use CHANNEL_INVALID instead  */
+    @Deprecated    public static final int CHANNEL_CONFIGURATION_INVALID   = 0;
     /** Default audio channel configuration */
-    public static final int CHANNEL_CONFIGURATION_DEFAULT   = 1;
+    /** @deprecated use CHANNEL_OUT_DEFAULT or CHANNEL_IN_DEFAULT instead  */
+    @Deprecated    public static final int CHANNEL_CONFIGURATION_DEFAULT   = 1;
     /** Mono audio configuration */
-    public static final int CHANNEL_CONFIGURATION_MONO      = 2;
+    /** @deprecated use CHANNEL_OUT_MONO or CHANNEL_IN_MONO instead  */
+    @Deprecated    public static final int CHANNEL_CONFIGURATION_MONO      = 2;
     /** Stereo (2 channel) audio configuration */
-    public static final int CHANNEL_CONFIGURATION_STEREO    = 3;
+    /** @deprecated use CHANNEL_OUT_STEREO or CHANNEL_IN_STEREO instead  */
+    @Deprecated    public static final int CHANNEL_CONFIGURATION_STEREO    = 3;
+
+    /** Invalid audio channel mask */
+    public static final int CHANNEL_INVALID   = -1;
+    /** Default audio channel mask */
+    // Channel mask definitions must be kept in sync with native values in include/media/AudioSystem.h
+    public static final int CHANNEL_OUT_DEFAULT = 0;
+    public static final int CHANNEL_OUT_FRONT_LEFT = 0x1;
+    public static final int CHANNEL_OUT_FRONT_RIGHT = 0x2;
+    public static final int CHANNEL_OUT_FRONT_CENTER = 0x4;
+    public static final int CHANNEL_OUT_LOW_FREQUENCY = 0x8;
+    public static final int CHANNEL_OUT_BACK_LEFT = 0x10;
+    public static final int CHANNEL_OUT_BACK_RIGHT = 0x20;
+    public static final int CHANNEL_OUT_FRONT_LEFT_OF_CENTER = 0x40;
+    public static final int CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x80;
+    public static final int CHANNEL_OUT_BACK_CENTER = 0x100;
+    public static final int CHANNEL_OUT_MONO = CHANNEL_OUT_FRONT_LEFT;
+    public static final int CHANNEL_OUT_STEREO = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT);
+    public static final int CHANNEL_OUT_QUAD = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
+            CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT);
+    public static final int CHANNEL_OUT_SURROUND = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
+            CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_BACK_CENTER);
+    public static final int CHANNEL_OUT_5POINT1 = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
+            CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT);
+    public static final int CHANNEL_OUT_7POINT1 = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
+            CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT |
+            CHANNEL_OUT_FRONT_LEFT_OF_CENTER | CHANNEL_OUT_FRONT_RIGHT_OF_CENTER);
+
+    public static final int CHANNEL_IN_DEFAULT = 0;
+    public static final int CHANNEL_IN_LEFT = 0x10000;
+    public static final int CHANNEL_IN_RIGHT = 0x20000;
+    public static final int CHANNEL_IN_FRONT = 0x40000;
+    public static final int CHANNEL_IN_BACK = 0x80000;
+    public static final int CHANNEL_IN_LEFT_PROCESSED = 0x100000;
+    public static final int CHANNEL_IN_RIGHT_PROCESSED = 0x200000;
+    public static final int CHANNEL_IN_FRONT_PROCESSED = 0x400000;
+    public static final int CHANNEL_IN_BACK_PROCESSED = 0x800000;
+    public static final int CHANNEL_IN_PRESSURE = 0x1000000;
+    public static final int CHANNEL_IN_X_AXIS = 0x2000000;
+    public static final int CHANNEL_IN_Y_AXIS = 0x4000000;
+    public static final int CHANNEL_IN_Z_AXIS = 0x8000000;
+    public static final int CHANNEL_IN_MONO = CHANNEL_IN_FRONT;
+    public static final int CHANNEL_IN_STEREO = (CHANNEL_IN_LEFT | CHANNEL_IN_RIGHT);
 
 }
-
-
-
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index a65a417..040d4bc 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -140,11 +140,17 @@
     public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
     /** @hide The audio stream for phone calls when connected to bluetooth */
     public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
+    /** @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
+    public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
+    /** The audio stream for DTMF Tones */
+    public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
+    /** @hide The audio stream for text to speech (TTS) */
+    public static final int STREAM_TTS = AudioSystem.STREAM_TTS;
     /** Number of audio streams */
     /**
      * @deprecated Use AudioSystem.getNumStreamTypes() instead
      */
-    public static final int NUM_STREAMS = AudioSystem.NUM_STREAMS;
+    @Deprecated public static final int NUM_STREAMS = AudioSystem.NUM_STREAMS;
 
 
     /** @hide Maximum volume index values for audio streams */
@@ -156,6 +162,9 @@
         8,  // STREAM_ALARM
         8,  // STREAM_NOTIFICATION
         16, // STREAM_BLUETOOTH_SCO
+        8,  // STREAM_SYSTEM_ENFORCED
+        16, // STREAM_DTMF
+        16  // STREAM_TTS
     };
 
     /**  @hide Default volume index values for audio streams */
@@ -166,7 +175,10 @@
         11, // STREAM_MUSIC
         6,  // STREAM_ALARM
         5,  // STREAM_NOTIFICATION
-        7   // STREAM_BLUETOOTH_SCO
+        7,  // STREAM_BLUETOOTH_SCO
+        5,  // STREAM_SYSTEM_ENFORCED
+        11, // STREAM_DTMF
+        11  // STREAM_TTS
     };
 
     /**
@@ -637,9 +649,11 @@
      *           <var>false</var> to turn it off
      */
     public void setSpeakerphoneOn(boolean on){
-        // Temporary fix for issue #1713090 until audio routing is refactored in eclair release.
-        // MODE_INVALID indicates to AudioService that setRouting() was initiated by AudioManager
-        setRoutingP(MODE_INVALID, on ? ROUTE_SPEAKER: 0, ROUTE_SPEAKER);
+        if (on) {
+            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_SPEAKER);
+        } else {
+            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE);
+        }
     }
 
     /**
@@ -648,41 +662,47 @@
      * @return true if speakerphone is on, false if it's off
      */
     public boolean isSpeakerphoneOn() {
-        return (getRoutingP(MODE_IN_CALL) & ROUTE_SPEAKER) == 0 ? false : true;
+        if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) == AudioSystem.FORCE_SPEAKER) {
+            return true;
+        } else {
+            return false;
+        }
      }
 
     /**
-     * Sets audio routing to the Bluetooth headset on or off.
+     * Request use of Bluetooth SCO headset for communications.
      *
-     * @param on set <var>true</var> to route SCO (voice) audio to/from Bluetooth
-     *           headset; <var>false</var> to route audio to/from phone earpiece
+     * @param on set <var>true</var> to use bluetooth SCO for communications;
+     *               <var>false</var> to not use bluetooth SCO for communications
      */
     public void setBluetoothScoOn(boolean on){
-        // Temporary fix for issue #1713090 until audio routing is refactored in eclair release.
-        // MODE_INVALID indicates to AudioService that setRouting() was initiated by AudioManager
-        setRoutingP(MODE_INVALID, on ? ROUTE_BLUETOOTH_SCO: 0, ROUTE_BLUETOOTH_SCO);
+        if (on) {
+            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_BT_SCO);
+        } else {
+            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE);
+        }
     }
 
     /**
-     * Checks whether audio routing to the Bluetooth headset is on or off.
+     * Checks whether communications use Bluetooth SCO.
      *
-     * @return true if SCO audio is being routed to/from Bluetooth headset;
+     * @return true if SCO is used for communications;
      *         false if otherwise
      */
     public boolean isBluetoothScoOn() {
-        return (getRoutingP(MODE_IN_CALL) & ROUTE_BLUETOOTH_SCO) == 0 ? false : true;
+        if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) == AudioSystem.FORCE_BT_SCO) {
+            return true;
+        } else {
+            return false;
+        }
     }
 
     /**
-     * Sets A2DP audio routing to the Bluetooth headset on or off.
-     *
      * @param on set <var>true</var> to route A2DP audio to/from Bluetooth
      *           headset; <var>false</var> disable A2DP audio
+     * @deprecated Do not use.
      */
-    public void setBluetoothA2dpOn(boolean on){
-        // Temporary fix for issue #1713090 until audio routing is refactored in eclair release.
-        // MODE_INVALID indicates to AudioService that setRouting() was initiated by AudioManager
-        setRoutingP(MODE_INVALID, on ? ROUTE_BLUETOOTH_A2DP: 0, ROUTE_BLUETOOTH_A2DP);
+    @Deprecated public void setBluetoothA2dpOn(boolean on){
     }
 
     /**
@@ -692,7 +712,12 @@
      *         false if otherwise
      */
     public boolean isBluetoothA2dpOn() {
-        return (getRoutingP(MODE_NORMAL) & ROUTE_BLUETOOTH_A2DP) == 0 ? false : true;
+        if (AudioSystem.getDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,"") 
+            == AudioSystem.DEVICE_STATE_UNAVAILABLE) {
+            return false;
+        } else {
+            return true;
+        }
     }
 
     /**
@@ -700,12 +725,9 @@
      *
      * @param on set <var>true</var> to route audio to/from wired
      *           headset; <var>false</var> disable wired headset audio
-     * @hide
+     * @deprecated Do not use.
      */
-    public void setWiredHeadsetOn(boolean on){
-        // Temporary fix for issue #1713090 until audio routing is refactored in eclair release.
-        // MODE_INVALID indicates to AudioService that setRouting() was initiated by AudioManager
-        setRoutingP(MODE_INVALID, on ? ROUTE_HEADSET: 0, ROUTE_HEADSET);
+    @Deprecated public void setWiredHeadsetOn(boolean on){
     }
 
     /**
@@ -713,10 +735,14 @@
      *
      * @return true if audio is being routed to/from wired headset;
      *         false if otherwise
-     * @hide
      */
     public boolean isWiredHeadsetOn() {
-        return (getRoutingP(MODE_NORMAL) & ROUTE_HEADSET) == 0 ? false : true;
+        if (AudioSystem.getDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,"") 
+                == AudioSystem.DEVICE_STATE_UNAVAILABLE) {
+            return false;
+        } else {
+            return true;
+        }
     }
 
     /**
@@ -726,12 +752,7 @@
      *           <var>false</var> to turn mute off
      */
     public void setMicrophoneMute(boolean on){
-        IAudioService service = getService();
-        try {
-            service.setMicrophoneMute(on);
-        } catch (RemoteException e) {
-            Log.e(TAG, "Dead object in setMicrophoneMute", e);
-        }
+        AudioSystem.muteMicrophone(on);
     }
 
     /**
@@ -740,13 +761,7 @@
      * @return true if microphone is muted, false if it's not
      */
     public boolean isMicrophoneMute() {
-        IAudioService service = getService();
-        try {
-            return service.isMicrophoneMute();
-        } catch (RemoteException e) {
-            Log.e(TAG, "Dead object in isMicrophoneMute", e);
-            return false;
-        }
+        return AudioSystem.isMicrophoneMuted();
     }
 
     /**
@@ -809,32 +824,39 @@
     /* Routing bits for setRouting/getRouting API */
     /**
      * Routing audio output to earpiece
+     * @deprecated
      */
-    public static final int ROUTE_EARPIECE          = AudioSystem.ROUTE_EARPIECE;
+    @Deprecated public static final int ROUTE_EARPIECE          = AudioSystem.ROUTE_EARPIECE;
     /**
      * Routing audio output to spaker
+     * @deprecated
      */
-    public static final int ROUTE_SPEAKER           = AudioSystem.ROUTE_SPEAKER;
+    @Deprecated public static final int ROUTE_SPEAKER           = AudioSystem.ROUTE_SPEAKER;
     /**
      * @deprecated use {@link #ROUTE_BLUETOOTH_SCO}
+     * @deprecated
      */
     @Deprecated public static final int ROUTE_BLUETOOTH = AudioSystem.ROUTE_BLUETOOTH_SCO;
     /**
      * Routing audio output to bluetooth SCO
+     * @deprecated
      */
-    public static final int ROUTE_BLUETOOTH_SCO     = AudioSystem.ROUTE_BLUETOOTH_SCO;
+    @Deprecated public static final int ROUTE_BLUETOOTH_SCO     = AudioSystem.ROUTE_BLUETOOTH_SCO;
     /**
      * Routing audio output to headset
+     * @deprecated
      */
-    public static final int ROUTE_HEADSET           = AudioSystem.ROUTE_HEADSET;
+    @Deprecated public static final int ROUTE_HEADSET           = AudioSystem.ROUTE_HEADSET;
     /**
      * Routing audio output to bluetooth A2DP
+     * @deprecated
      */
-    public static final int ROUTE_BLUETOOTH_A2DP    = AudioSystem.ROUTE_BLUETOOTH_A2DP;
+    @Deprecated public static final int ROUTE_BLUETOOTH_A2DP    = AudioSystem.ROUTE_BLUETOOTH_A2DP;
     /**
      * Used for mask parameter of {@link #setRouting(int,int,int)}.
+     * @deprecated
      */
-    public static final int ROUTE_ALL               = AudioSystem.ROUTE_ALL;
+    @Deprecated public static final int ROUTE_ALL               = AudioSystem.ROUTE_ALL;
 
     /**
      * Sets the audio routing for a specified mode
@@ -846,16 +868,10 @@
      * ROUTE_xxx types. Unset bits indicate the route should be left unchanged
      *
      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
-     * setBluetoothScoOn(), setBluetoothA2dpOn() and setWiredHeadsetOn() methods instead.
+     * setBluetoothScoOn() methods instead.
      */
-
+    @Deprecated
     public void setRouting(int mode, int routes, int mask) {
-        IAudioService service = getService();
-        try {
-            service.setRouting(mode, routes, mask);
-        } catch (RemoteException e) {
-            Log.e(TAG, "Dead object in setRouting", e);
-        }
     }
 
     /**
@@ -869,13 +885,7 @@
      */
     @Deprecated
     public int getRouting(int mode) {
-        IAudioService service = getService();
-        try {
-            return service.getRouting(mode);
-        } catch (RemoteException e) {
-            Log.e(TAG, "Dead object in getRouting", e);
-            return -1;
-        }
+        return -1;
     }
 
     /**
@@ -884,13 +894,7 @@
      * @return true if any music tracks are active.
      */
     public boolean isMusicActive() {
-        IAudioService service = getService();
-        try {
-            return service.isMusicActive();
-        } catch (RemoteException e) {
-            Log.e(TAG, "Dead object in isMusicActive", e);
-            return false;
-        }
+        return AudioSystem.isMusicActive();
     }
 
     /*
@@ -906,14 +910,32 @@
      */
     /**
      * @hide
+     * @deprecated Use {@link #setPrameters(String)} instead
      */
-    public void setParameter(String key, String value) {
-        IAudioService service = getService();
-        try {
-            service.setParameter(key, value);
-        } catch (RemoteException e) {
-            Log.e(TAG, "Dead object in setParameter", e);
-        }
+    @Deprecated public void setParameter(String key, String value) {
+        setParameters(key+"="+value);
+    }
+
+    /**
+     * Sets a variable number of parameter values to audio hardware.
+     *
+     * @param keyValuePairs list of parameters key value pairs in the form:
+     *    key1=value1;key2=value2;...
+     *
+     */
+    public void setParameters(String keyValuePairs) {
+        AudioSystem.setParameters(keyValuePairs);
+    }
+
+    /**
+     * Sets a varaible number of parameter values to audio hardware.
+     *
+     * @param keys list of parameters
+     * @return list of parameters key value pairs in the form:
+     *    key1=value1;key2=value2;...
+     */
+    public String getParameters(String keys) {
+        return AudioSystem.getParameters(keys);
     }
 
     /* Sound effect identifiers */
@@ -1082,31 +1104,4 @@
       * {@hide}
       */
      private IBinder mICallBack = new Binder();
-
-     /**
-      * {@hide}
-      */
-     private void setRoutingP(int mode, int routes, int mask) {
-         IAudioService service = getService();
-         try {
-             service.setRouting(mode, routes, mask);
-         } catch (RemoteException e) {
-             Log.e(TAG, "Dead object in setRouting", e);
-         }
-     }
-
-
-     /**
-      * {@hide}
-      */
-     private int getRoutingP(int mode) {
-         IAudioService service = getService();
-         try {
-             return service.getRouting(mode);
-         } catch (RemoteException e) {
-             Log.e(TAG, "Dead object in getRouting", e);
-             return -1;
-         }
-     }
-
 }
diff --git a/media/java/android/media/AudioRecord.java b/media/java/android/media/AudioRecord.java
index 4d1535f9..d96331f 100644
--- a/media/java/android/media/AudioRecord.java
+++ b/media/java/android/media/AudioRecord.java
@@ -86,7 +86,7 @@
     public static final int ERROR_INVALID_OPERATION = -3;
     
     private static final int AUDIORECORD_ERROR_SETUP_ZEROFRAMECOUNT      = -16;
-    private static final int AUDIORECORD_ERROR_SETUP_INVALIDCHANNELCOUNT = -17;
+    private static final int AUDIORECORD_ERROR_SETUP_INVALIDCHANNELMASK  = -17;
     private static final int AUDIORECORD_ERROR_SETUP_INVALIDFORMAT       = -18;
     private static final int AUDIORECORD_ERROR_SETUP_INVALIDSOURCE       = -19;
     private static final int AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED    = -20;
@@ -135,7 +135,7 @@
     /**
      * The current audio channel configuration
      */
-    private int mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+    private int mChannelConfiguration = AudioFormat.CHANNEL_IN_MONO;
     /**
      * The encoding of the audio samples.
      * @see AudioFormat#ENCODING_PCM_8BIT
@@ -193,8 +193,8 @@
      * @param sampleRateInHz the sample rate expressed in Hertz. Examples of rates are (but
      *   not limited to) 44100, 22050 and 11025.
      * @param channelConfig describes the configuration of the audio channels. 
-     *   See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO} and
-     *   {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO}
+     *   See {@link AudioFormat#CHANNEL_IN_MONO} and
+     *   {@link AudioFormat#CHANNEL_IN_STEREO}
      * @param audioFormat the format in which the audio data is represented. 
      *   See {@link AudioFormat#ENCODING_PCM_16BIT} and 
      *   {@link AudioFormat#ENCODING_PCM_8BIT}
@@ -265,18 +265,18 @@
         //--------------
         // channel config
         switch (channelConfig) {
-        case AudioFormat.CHANNEL_CONFIGURATION_DEFAULT:
-        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
+        case AudioFormat.CHANNEL_IN_DEFAULT:
+        case AudioFormat.CHANNEL_IN_MONO:
             mChannelCount = 1;
-            mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+            mChannelConfiguration = AudioFormat.CHANNEL_IN_MONO;
             break;
-        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
+        case AudioFormat.CHANNEL_IN_STEREO:
             mChannelCount = 2;
-            mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+            mChannelConfiguration = AudioFormat.CHANNEL_IN_STEREO;
             break;
         default:
             mChannelCount = 0;
-        mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_INVALID;
+        mChannelConfiguration = AudioFormat.CHANNEL_INVALID;
         throw (new IllegalArgumentException("Unsupported channel configuration."));
         }
 
@@ -368,8 +368,8 @@
 
     /**
      * Returns the configured channel configuration. 
-     * See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO}
-     * and {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO}.
+     * See {@link AudioFormat#CHANNEL_IN_MONO}
+     * and {@link AudioFormat#CHANNEL_IN_STEREO}.
      */
     public int getChannelConfiguration() {
         return mChannelConfiguration;
@@ -425,8 +425,8 @@
      * will be polled for new data.
      * @param sampleRateInHz the sample rate expressed in Hertz.
      * @param channelConfig describes the configuration of the audio channels. 
-     *   See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO} and
-     *   {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO}
+     *   See {@link AudioFormat#CHANNEL_IN_MONO} and
+     *   {@link AudioFormat#CHANNEL_IN_STEREO}
      * @param audioFormat the format in which the audio data is represented. 
      *   See {@link AudioFormat#ENCODING_PCM_16BIT}.
      * @return {@link #ERROR_BAD_VALUE} if the recording parameters are not supported by the 
@@ -438,14 +438,14 @@
     static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) {
         int channelCount = 0;
         switch(channelConfig) {
-        case AudioFormat.CHANNEL_CONFIGURATION_DEFAULT:
-        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
+        case AudioFormat.CHANNEL_IN_DEFAULT:
+        case AudioFormat.CHANNEL_IN_MONO:
             channelCount = 1;
             break;
-        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
+        case AudioFormat.CHANNEL_IN_STEREO:
             channelCount = 2;
             break;
-        case AudioFormat.CHANNEL_CONFIGURATION_INVALID:
+        case AudioFormat.CHANNEL_INVALID:
         default:
             loge("getMinBufferSize(): Invalid channel configuration.");
             return AudioRecord.ERROR_BAD_VALUE;
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java
index 58c04f3..177a7cf 100644
--- a/media/java/android/media/AudioService.java
+++ b/media/java/android/media/AudioService.java
@@ -20,6 +20,12 @@
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
+import android.bluetooth.BluetoothIntent;
+import android.content.BroadcastReceiver;
+import android.bluetooth.BluetoothHeadset;
+import android.bluetooth.BluetoothA2dp;
+
 import android.content.pm.PackageManager;
 import android.database.ContentObserver;
 import android.media.MediaPlayer.OnCompletionListener;
@@ -94,16 +100,10 @@
     /** @see VolumeStreamState */
     private VolumeStreamState[] mStreamStates;
     private SettingsObserver mSettingsObserver;
-    
-    private boolean mMicMute;
+
     private int mMode;
-    private int[] mRoutes = new int[AudioSystem.NUM_MODES];
     private Object mSettingsLock = new Object();
     private boolean mMediaServerOk;
-    private boolean mSpeakerIsOn;
-    private boolean mBluetoothScoIsConnected;
-    private boolean mHeadsetIsConnected;
-    private boolean mBluetoothA2dpIsConnected;
 
     private SoundPool mSoundPool;
     private Object mSoundEffectsLock = new Object();
@@ -135,6 +135,23 @@
         {4, -1}   // FX_FOCUS_RETURN
     };
 
+    /* STREAM_VOLUME_ALIAS[] indicates for each stream if it uses the volume settings
+     * of another stream: This avoids multiplying the volume settings for hidden
+     * stream types that follow other stream behavior for volume settings
+     * NOTE: do not create loops in aliases! */
+    private int[] STREAM_VOLUME_ALIAS = new int[] {
+        AudioSystem.STREAM_VOICE_CALL,  // STREAM_VOICE_CALL
+        AudioSystem.STREAM_SYSTEM,  // STREAM_SYSTEM
+        AudioSystem.STREAM_RING,  // STREAM_RING
+        AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
+        AudioSystem.STREAM_ALARM,  // STREAM_ALARM
+        AudioSystem.STREAM_NOTIFICATION,  // STREAM_NOTIFICATION
+        AudioSystem.STREAM_VOICE_CALL, // STREAM_BLUETOOTH_SCO
+        AudioSystem.STREAM_SYSTEM,  // STREAM_SYSTEM_ENFORCED
+        AudioSystem.STREAM_VOICE_CALL, // STREAM_DTMF
+        AudioSystem.STREAM_MUSIC  // STREAM_TTS
+    };
+
     private AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() {
         public void onError(int error) {
             switch (error) {
@@ -178,6 +195,21 @@
      */
     private int mVibrateSetting;
 
+    /** @see System#NOTIFICATIONS_USE_RING_VOLUME */
+    private int mNotificationsUseRingVolume;
+
+    // Broadcast receiver for device connections intent broadcasts
+    private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver();
+
+    //TODO: use common definitions with HeadsetObserver
+    private static final int BIT_HEADSET = (1 << 0);
+    private static final int BIT_HEADSET_NO_MIC = (1 << 1);
+    private static final int BIT_TTY = (1 << 2);
+    private static final int BIT_FM_HEADSET = (1 << 3);
+    private static final int BIT_FM_SPEAKER = (1 << 4);
+
+    private int mHeadsetState;
+
     ///////////////////////////////////////////////////////////////////////////
     // Construction
     ///////////////////////////////////////////////////////////////////////////
@@ -188,18 +220,20 @@
         mContentResolver = context.getContentResolver();
         mVolumePanel = new VolumePanel(context, this);
         mSettingsObserver = new SettingsObserver();
-        
+
         createAudioSystemThread();
-        createStreamStates();
         readPersistedSettings();
-        readAudioSettings();
+        createStreamStates();
         mMediaServerOk = true;
         AudioSystem.setErrorCallback(mAudioSystemCallback);
         loadSoundEffects();
-        mSpeakerIsOn = false;
-        mBluetoothScoIsConnected = false;
-        mHeadsetIsConnected = false;
-        mBluetoothA2dpIsConnected = false;
+
+        // Register for device connection intent broadcasts.
+        IntentFilter intentFilter =
+                new IntentFilter(Intent.ACTION_HEADSET_PLUG);
+        intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
+        intentFilter.addAction(BluetoothIntent.HEADSET_AUDIO_STATE_CHANGED_ACTION);
+        context.registerReceiver(mReceiver, intentFilter);
     }
 
     private void createAudioSystemThread() {
@@ -223,65 +257,25 @@
     }
 
     private void createStreamStates() {
-        final int[] volumeLevelsPhone =
-            createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_VOICE_CALL]);
-        final int[] volumeLevelsCoarse =
-            createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_SYSTEM]);
-        final int[] volumeLevelsFine =
-            createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_MUSIC]);
-        final int[] volumeLevelsBtPhone =
-            createVolumeLevels(0,
-                    AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_BLUETOOTH_SCO]);
-
         int numStreamTypes = AudioSystem.getNumStreamTypes();
         VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes];
 
         for (int i = 0; i < numStreamTypes; i++) {
-            final int[] levels;
+            streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[i]], i);
+        }
 
-            switch (i) {
-
-                case AudioSystem.STREAM_MUSIC:
-                    levels = volumeLevelsFine;
-                    break;
-
-                case AudioSystem.STREAM_VOICE_CALL:
-                    levels = volumeLevelsPhone;
-                    break;
-
-                case AudioSystem.STREAM_BLUETOOTH_SCO:
-                    levels = volumeLevelsBtPhone;
-                    break;
-
-                default:
-                    levels = volumeLevelsCoarse;
-                    break;
-            }
-
-            if (i == AudioSystem.STREAM_BLUETOOTH_SCO) {
-                streams[i] = new VolumeStreamState(AudioManager.DEFAULT_STREAM_VOLUME[i], i,levels);
-            } else {
-                streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[i], i, levels);
+        // Correct stream index values for streams with aliases
+        for (int i = 0; i < numStreamTypes; i++) {
+            if (STREAM_VOLUME_ALIAS[i] != i) {
+                int index = rescaleIndex(streams[i].mIndex, STREAM_VOLUME_ALIAS[i], i);
+                streams[i].mIndex = streams[i].getValidIndex(index);
+                setStreamVolumeIndex(i, index);
+                index = rescaleIndex(streams[i].mLastAudibleIndex, STREAM_VOLUME_ALIAS[i], i);
+                streams[i].mLastAudibleIndex = streams[i].getValidIndex(index);
             }
         }
     }
 
-    private static int[] createVolumeLevels(int offset, int numlevels) {
-        double curve = 1.0f; // 1.4f
-        int [] volumes = new int[numlevels + offset];
-        for (int i = 0; i < offset; i++) {
-            volumes[i] = 0;
-        }
-
-        double val = 0;
-        double max = Math.pow(numlevels - 1, curve);
-        for (int i = 0; i < numlevels; i++) {
-            val = Math.pow(i, curve) / max;
-            volumes[offset + i] = (int) (val * 100.0f);
-        }
-        return volumes;
-    }
-
     private void readPersistedSettings() {
         final ContentResolver cr = mContentResolver;
 
@@ -291,12 +285,19 @@
 
         mRingerModeAffectedStreams = Settings.System.getInt(cr,
                 Settings.System.MODE_RINGER_STREAMS_AFFECTED,
-                ((1 << AudioManager.STREAM_RING)|(1 << AudioManager.STREAM_NOTIFICATION)|(1 << AudioManager.STREAM_SYSTEM)));
+                ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
+                 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)));
 
         mMuteAffectedStreams = System.getInt(cr,
                 System.MUTE_STREAMS_AFFECTED,
                 ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM)));
 
+        mNotificationsUseRingVolume = System.getInt(cr,
+                Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1);
+
+        if (mNotificationsUseRingVolume == 1) {
+            STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
+        }
         // Each stream will read its own persisted settings
 
         // Broadcast the sticky intent
@@ -307,25 +308,13 @@
         broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION);
     }
 
-    private void readAudioSettings() {
-        synchronized (mSettingsLock) {
-            mMicMute = AudioSystem.isMicrophoneMuted();
-            mMode = AudioSystem.getMode();
-            for (int mode = 0; mode < AudioSystem.NUM_MODES; mode++) {
-                mRoutes[mode] = AudioSystem.getRouting(mode);
-            }
-        }
+    private void setStreamVolumeIndex(int stream, int index) {
+        AudioSystem.setStreamVolumeIndex(stream, (index + 5)/10);
     }
 
-    private void applyAudioSettings() {
-        synchronized (mSettingsLock) {
-            AudioSystem.muteMicrophone(mMicMute);
-            AudioSystem.setMode(mMode);
-            for (int mode = 0; mode < AudioSystem.NUM_MODES; mode++) {
-                AudioSystem.setRouting(mode, mRoutes[mode], AudioSystem.ROUTE_ALL);
-            }
-        }
-   }
+    private int rescaleIndex(int index, int srcStream, int dstStream) {
+        return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex();
+    }
 
     ///////////////////////////////////////////////////////////////////////////
     // IPC methods
@@ -354,44 +343,26 @@
         ensureValidDirection(direction);
         ensureValidStreamType(streamType);
 
-        boolean notificationsUseRingVolume = Settings.System.getInt(mContentResolver,
-                Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1) == 1;
-        if (notificationsUseRingVolume && streamType == AudioManager.STREAM_NOTIFICATION) {
-            // Redirect the volume change to the ring stream
-            streamType = AudioManager.STREAM_RING;
-        }
 
-        VolumeStreamState streamState = mStreamStates[streamType];
+        VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]];
         final int oldIndex = streamState.mIndex;
         boolean adjustVolume = true;
 
         // If either the client forces allowing ringer modes for this adjustment,
         // or the stream type is one that is affected by ringer modes
         if ((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0
-                || streamType == AudioManager.STREAM_RING) {
+                || streamType == AudioSystem.STREAM_RING) {
             // Check if the ringer mode changes with this volume adjustment. If
             // it does, it will handle adjusting the volume, so we won't below
             adjustVolume = checkForRingerModeChange(oldIndex, direction);
         }
 
         if (adjustVolume && streamState.adjustIndex(direction)) {
-
-            boolean alsoUpdateNotificationVolume =  notificationsUseRingVolume &&
-                    streamType == AudioManager.STREAM_RING;
-            if (alsoUpdateNotificationVolume) {
-                mStreamStates[AudioManager.STREAM_NOTIFICATION].adjustIndex(direction);
-            }
-
             // Post message to set system volume (it in turn will post a message
             // to persist). Do not change volume if stream is muted.
             if (streamState.muteCount() == 0) {
-                sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0,
+                sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, STREAM_VOLUME_ALIAS[streamType], SENDMSG_NOOP, 0, 0,
                         streamState, 0);
-
-                if (alsoUpdateNotificationVolume) {
-                    sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, AudioManager.STREAM_NOTIFICATION,
-                            SENDMSG_NOOP, 0, 0, mStreamStates[AudioManager.STREAM_NOTIFICATION], 0);
-                }
             }
         }
 
@@ -404,9 +375,8 @@
     /** @see AudioManager#setStreamVolume(int, int, int) */
     public void setStreamVolume(int streamType, int index, int flags) {
         ensureValidStreamType(streamType);
-        syncRingerAndNotificationStreamVolume(streamType, index, false);
-
-        setStreamVolumeInt(streamType, index, false, true);
+        index = rescaleIndex(index * 10, streamType, STREAM_VOLUME_ALIAS[streamType]);
+        setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, false, true);
 
         // UI, etc.
         mVolumePanel.postVolumeChanged(streamType, flags);
@@ -420,37 +390,12 @@
         intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, getStreamVolume(streamType));
 
         // Currently, sending the intent only when the stream is BLUETOOTH_SCO
-        if (streamType == AudioManager.STREAM_BLUETOOTH_SCO) {
+        if (streamType == AudioSystem.STREAM_BLUETOOTH_SCO) {
             mContext.sendBroadcast(intent);
         }
     }
 
     /**
-     * Sync the STREAM_RING and STREAM_NOTIFICATION volumes if mandated by the
-     * value in Settings.
-     *
-     * @param streamType Type of the stream
-     * @param index Volume index for the stream
-     * @param force If true, set the volume even if the current and desired
-     * volume as same
-     */
-    private void syncRingerAndNotificationStreamVolume(int streamType, int index, boolean force) {
-        boolean notificationsUseRingVolume = Settings.System.getInt(mContentResolver,
-                Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1) == 1;
-        if (notificationsUseRingVolume) {
-            if (streamType == AudioManager.STREAM_NOTIFICATION) {
-                // Redirect the volume change to the ring stream
-                streamType = AudioManager.STREAM_RING;
-            }
-            if (streamType == AudioManager.STREAM_RING) {
-                // One-off to sync notification volume to ringer volume
-                setStreamVolumeInt(AudioManager.STREAM_NOTIFICATION, index, force, true);
-            }
-        }
-    }
-
-
-    /**
      * Sets the stream state's index, and posts a message to set system volume.
      * This will not call out to the UI. Assumes a valid stream type.
      *
@@ -491,13 +436,13 @@
     /** @see AudioManager#getStreamVolume(int) */
     public int getStreamVolume(int streamType) {
         ensureValidStreamType(streamType);
-        return mStreamStates[streamType].mIndex;
+        return (mStreamStates[streamType].mIndex + 5) / 10;
     }
 
     /** @see AudioManager#getStreamMaxVolume(int) */
     public int getStreamMaxVolume(int streamType) {
         ensureValidStreamType(streamType);
-        return mStreamStates[streamType].getMaxIndex();
+        return (mStreamStates[streamType].getMaxIndex() + 5) / 10;
     }
 
     /** @see AudioManager#getRingerMode() */
@@ -507,11 +452,12 @@
 
     /** @see AudioManager#setRingerMode(int) */
     public void setRingerMode(int ringerMode) {
-        if (ringerMode != mRingerMode) {
-            setRingerModeInt(ringerMode, true);
-
-            // Send sticky broadcast
-            broadcastRingerMode();
+        synchronized (mSettingsLock) {
+            if (ringerMode != mRingerMode) {
+                setRingerModeInt(ringerMode, true);
+                // Send sticky broadcast
+                broadcastRingerMode();
+            }
         }
     }
 
@@ -541,7 +487,7 @@
                 }
             }
         }
-        
+
         // Post a persist ringer mode msg
         if (persist) {
             sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SHARED_MSG,
@@ -606,39 +552,28 @@
         return existingValue;
     }
 
-    /** @see AudioManager#setMicrophoneMute(boolean) */
-    public void setMicrophoneMute(boolean on) {
-        if (!checkAudioSettingsPermission("setMicrophoneMute()")) {
-            return;
-        }
-        synchronized (mSettingsLock) {
-            if (on != mMicMute) {
-                AudioSystem.muteMicrophone(on);
-                mMicMute = on;
-            }
-        }
-    }
-
-    /** @see AudioManager#isMicrophoneMute() */
-    public boolean isMicrophoneMute() {
-        return mMicMute;
-    }
-
     /** @see AudioManager#setMode(int) */
     public void setMode(int mode) {
         if (!checkAudioSettingsPermission("setMode()")) {
             return;
         }
+
+        if (mode < AudioSystem.MODE_CURRENT || mode > AudioSystem.MODE_IN_CALL) {
+            return;
+        }
+
         synchronized (mSettingsLock) {
+            if (mode == AudioSystem.MODE_CURRENT) {
+                mode = mMode;
+            }
             if (mode != mMode) {
-                if (AudioSystem.setMode(mode) == AudioSystem.AUDIO_STATUS_OK) {
+                if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) {
                     mMode = mode;
                 }
             }
             int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
-            int index = mStreamStates[streamType].mIndex;
-            syncRingerAndNotificationStreamVolume(streamType, index, true);
-            setStreamVolumeInt(streamType, index, true, true);
+            int index = mStreamStates[STREAM_VOLUME_ALIAS[streamType]].mIndex;
+            setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, true, true);
         }
     }
 
@@ -647,187 +582,6 @@
         return mMode;
     }
 
-    /** @see AudioManager#setRouting(int, int, int) */
-    public void setRouting(int mode, int routes, int mask) {
-        int incallMask = 0;
-        int ringtoneMask = 0;
-        int normalMask = 0;
-
-        if (!checkAudioSettingsPermission("setRouting()")) {
-            return;
-        }
-        synchronized (mSettingsLock) {
-            // Temporary fix for issue #1713090 until audio routing is refactored in eclair release.
-            // mode AudioSystem.MODE_INVALID is used only by the following AudioManager methods:
-            // setWiredHeadsetOn(), setBluetoothA2dpOn(), setBluetoothScoOn() and setSpeakerphoneOn().
-            // If applications are using AudioManager.setRouting() that is now deprecated, the routing
-            // command will be ignored.
-            if (mode == AudioSystem.MODE_INVALID) {
-                switch (mask) {
-                case AudioSystem.ROUTE_SPEAKER:
-                    // handle setSpeakerphoneOn()
-                    if (routes != 0 && !mSpeakerIsOn) {
-                        mSpeakerIsOn = true;
-                        mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER;
-                        incallMask = AudioSystem.ROUTE_ALL;
-                    } else if (routes == 0 && mSpeakerIsOn) {
-                        mSpeakerIsOn = false;
-                        if (mBluetoothScoIsConnected) {
-                            mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_BLUETOOTH_SCO;
-                        } else if (mHeadsetIsConnected) {
-                            mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET;
-                        } else {
-                            mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE;
-                        }
-                        incallMask = AudioSystem.ROUTE_ALL;
-                    }
-                    break;
-
-                case AudioSystem.ROUTE_BLUETOOTH_SCO:
-                    // handle setBluetoothScoOn()
-                    if (routes != 0 && !mBluetoothScoIsConnected) {
-                        mBluetoothScoIsConnected = true;
-                        mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_BLUETOOTH_SCO;
-                        mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) |
-                                                              AudioSystem.ROUTE_BLUETOOTH_SCO;
-                        mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) |
-                                                            AudioSystem.ROUTE_BLUETOOTH_SCO;
-                        incallMask = AudioSystem.ROUTE_ALL;
-                        // A2DP has higher priority than SCO headset, so headset connect/disconnect events
-                        // should not affect A2DP routing
-                        ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                        normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                    } else if (routes == 0 && mBluetoothScoIsConnected) {
-                        mBluetoothScoIsConnected = false;
-                        if (mHeadsetIsConnected) {
-                            mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET;
-                            mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) |
-                                                                 (AudioSystem.ROUTE_HEADSET|AudioSystem.ROUTE_SPEAKER);
-                            mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) |
-                                                               AudioSystem.ROUTE_HEADSET;
-                        } else {
-                            if (mSpeakerIsOn) {
-                                mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER;
-                            } else {
-                                mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE;
-                            }
-                            mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) |
-                                                                 AudioSystem.ROUTE_SPEAKER;
-                            mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) |
-                                                               AudioSystem.ROUTE_SPEAKER;
-                        }
-                        incallMask = AudioSystem.ROUTE_ALL;
-                        // A2DP has higher priority than SCO headset, so headset connect/disconnect events
-                        // should not affect A2DP routing
-                        ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                        normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                    }
-                    break;
-
-                case AudioSystem.ROUTE_HEADSET:
-                    // handle setWiredHeadsetOn()
-                    if (routes != 0 && !mHeadsetIsConnected) {
-                        mHeadsetIsConnected = true;
-                        // do not act upon headset connection if bluetooth SCO is connected to match phone app behavior
-                        if (!mBluetoothScoIsConnected) {
-                            mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET;
-                            mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) |
-                                                                 (AudioSystem.ROUTE_HEADSET|AudioSystem.ROUTE_SPEAKER);
-                            mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) |
-                                                               AudioSystem.ROUTE_HEADSET;
-                            incallMask = AudioSystem.ROUTE_ALL;
-                            // A2DP has higher priority than wired headset, so headset connect/disconnect events
-                            // should not affect A2DP routing
-                            ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                            normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                        }
-                    } else if (routes == 0 && mHeadsetIsConnected) {
-                        mHeadsetIsConnected = false;
-                        // do not act upon headset disconnection if bluetooth SCO is connected to match phone app behavior
-                        if (!mBluetoothScoIsConnected) {
-                            if (mSpeakerIsOn) {
-                                mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER;
-                            } else {
-                                mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE;
-                            }
-                            mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) |
-                                                                 AudioSystem.ROUTE_SPEAKER;
-                            mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) |
-                                                               AudioSystem.ROUTE_SPEAKER;
-
-                            incallMask = AudioSystem.ROUTE_ALL;
-                            // A2DP has higher priority than wired headset, so headset connect/disconnect events
-                            // should not affect A2DP routing
-                            ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                            normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                        }
-                    }
-                    break;
-
-                case AudioSystem.ROUTE_BLUETOOTH_A2DP:
-                    // handle setBluetoothA2dpOn()
-                    if (routes != 0 && !mBluetoothA2dpIsConnected) {
-                        mBluetoothA2dpIsConnected = true;
-                        mRoutes[AudioSystem.MODE_RINGTONE] |= AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                        mRoutes[AudioSystem.MODE_NORMAL] |= AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                        // the audio flinger chooses A2DP as a higher priority,
-                        // so there is no need to disable other routes.
-                        ringtoneMask = AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                        normalMask = AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                    } else if (routes == 0 && mBluetoothA2dpIsConnected) {
-                        mBluetoothA2dpIsConnected = false;
-                        mRoutes[AudioSystem.MODE_RINGTONE] &= ~AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                        mRoutes[AudioSystem.MODE_NORMAL] &= ~AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                        // the audio flinger chooses A2DP as a higher priority,
-                        // so there is no need to disable other routes.
-                        ringtoneMask = AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                        normalMask = AudioSystem.ROUTE_BLUETOOTH_A2DP;
-                    }
-                    break;
-                }
-                
-                // incallMask is != 0 means we must apply ne routing to MODE_IN_CALL mode
-                if (incallMask != 0) {
-                    AudioSystem.setRouting(AudioSystem.MODE_IN_CALL,
-                                           mRoutes[AudioSystem.MODE_IN_CALL],
-                                           incallMask);
-                }
-                // ringtoneMask is != 0 means we must apply ne routing to MODE_RINGTONE mode
-                if (ringtoneMask != 0) {
-                    AudioSystem.setRouting(AudioSystem.MODE_RINGTONE,
-                                           mRoutes[AudioSystem.MODE_RINGTONE],
-                                           ringtoneMask);
-                }
-                // normalMask is != 0 means we must apply ne routing to MODE_NORMAL mode
-                if (normalMask != 0) {
-                    AudioSystem.setRouting(AudioSystem.MODE_NORMAL,
-                                           mRoutes[AudioSystem.MODE_NORMAL],
-                                           normalMask);
-                }
-
-                int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
-                int index = mStreamStates[streamType].mIndex;
-                syncRingerAndNotificationStreamVolume(streamType, index, true);
-                setStreamVolumeInt(streamType, index, true, true);
-            }
-        }
-    }
-
-    /** @see AudioManager#getRouting(int) */
-    public int getRouting(int mode) {
-        return mRoutes[mode];
-    }
-
-    /** @see AudioManager#isMusicActive() */
-    public boolean isMusicActive() {
-        return AudioSystem.isMusicActive();
-    }
-
-    /** @see AudioManager#setParameter(String, String) */
-    public void setParameter(String key, String value) {
-        AudioSystem.setParameter(key, value);
-    }
-
     /** @see AudioManager#playSoundEffect(int) */
     public void playSoundEffect(int effectType) {
         sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
@@ -930,14 +684,28 @@
             if (streamType != AudioSystem.STREAM_BLUETOOTH_SCO) {
                 String settingName = System.VOLUME_SETTINGS[streamType];
                 String lastAudibleSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
+                int index = Settings.System.getInt(mContentResolver,
+                                               settingName,
+                                               AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
+                if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
+                    index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
+                } else {
+                    index *= 10;
+                }
+                streamState.mIndex = streamState.getValidIndex(index);
 
-                streamState.mIndex = streamState.getValidIndex(Settings.System.getInt(mContentResolver,
-                        settingName,
-                        AudioManager.DEFAULT_STREAM_VOLUME[streamType]));
-                streamState.mLastAudibleIndex = streamState.getValidIndex(Settings.System.getInt(mContentResolver,
-                        lastAudibleSettingName,
-                        streamState.mIndex > 0 ? streamState.mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]));
+                index = (index + 5) / 10;
+                index = Settings.System.getInt(mContentResolver,
+                                                lastAudibleSettingName,
+                                                (index > 0) ? index : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
+                if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
+                    index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
+                } else {
+                    index *= 10;
+                }
+                streamState.mLastAudibleIndex = streamState.getValidIndex(index);
             }
+
             // unmute stream that whas muted but is not affect by mute anymore
             if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) {
                 int size = streamState.mDeathHandlers.size();
@@ -948,7 +716,7 @@
             }
             // apply stream volume
             if (streamState.muteCount() == 0) {
-                AudioSystem.setVolume(streamType, streamState.mVolumes[streamState.mIndex]);
+                setStreamVolumeIndex(streamType, streamState.mIndex);
             }
         }
 
@@ -969,7 +737,7 @@
         boolean adjustVolumeIndex = true;
         int newRingerMode = mRingerMode;
 
-        if (mRingerMode == AudioManager.RINGER_MODE_NORMAL && oldIndex == 1
+        if (mRingerMode == AudioManager.RINGER_MODE_NORMAL && (oldIndex + 5) / 10 == 1
                 && direction == AudioManager.ADJUST_LOWER) {
             newRingerMode = AudioManager.RINGER_MODE_VIBRATE;
         } else if (mRingerMode == AudioManager.RINGER_MODE_VIBRATE) {
@@ -1026,7 +794,7 @@
             Log.w(TAG, "Couldn't connect to phone service", e);
         }
 
-        if ((getRouting(AudioSystem.MODE_IN_CALL) & AudioSystem.ROUTE_BLUETOOTH_SCO) != 0) {
+        if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) == AudioSystem.FORCE_BT_SCO) {
             // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
             return AudioSystem.STREAM_BLUETOOTH_SCO;
         } else if (isOffhook) {
@@ -1110,47 +878,36 @@
         private final String mLastAudibleVolumeIndexSettingName;
         private final int mStreamType;
 
-        private final int[] mVolumes;
+        private int mIndexMax;
         private int mIndex;
         private int mLastAudibleIndex;
         private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo requests client death
 
-        private VolumeStreamState(String settingName, int streamType, int[] volumes) {
+        private VolumeStreamState(String settingName, int streamType) {
 
             mVolumeIndexSettingName = settingName;
             mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
 
             mStreamType = streamType;
-            mVolumes = volumes;
 
             final ContentResolver cr = mContentResolver;
-            mIndex = getValidIndex(Settings.System.getInt(cr, mVolumeIndexSettingName, AudioManager.DEFAULT_STREAM_VOLUME[streamType]));
-            mLastAudibleIndex = getValidIndex(Settings.System.getInt(cr,
-                    mLastAudibleVolumeIndexSettingName, mIndex > 0 ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]));
-
-            AudioSystem.setVolume(streamType, volumes[mIndex]);
-            mDeathHandlers = new ArrayList<VolumeDeathHandler>();
-        }
-
-        /**
-         * Constructor to be used when there is no setting associated with the VolumeStreamState.
-         *
-         * @param defaultVolume Default volume of the stream to use.
-         * @param streamType Type of the stream.
-         * @param volumes Volumes levels associated with this stream.
-         */
-        private VolumeStreamState(int defaultVolume, int streamType, int[] volumes) {
-            mVolumeIndexSettingName = null;
-            mLastAudibleVolumeIndexSettingName = null;
-            mIndex = mLastAudibleIndex = defaultVolume;
-            mStreamType = streamType;
-            mVolumes = volumes;
-            AudioSystem.setVolume(mStreamType, defaultVolume);
+            mIndexMax = AudioManager.MAX_STREAM_VOLUME[streamType];
+            mIndex = Settings.System.getInt(cr,
+                                            mVolumeIndexSettingName,
+                                            AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
+            mLastAudibleIndex = Settings.System.getInt(cr,
+                                                       mLastAudibleVolumeIndexSettingName,
+                                                       (mIndex > 0) ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
+            AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
+            mIndexMax *= 10;
+            mIndex = getValidIndex(10 * mIndex);
+            mLastAudibleIndex = getValidIndex(10 * mLastAudibleIndex);
+            setStreamVolumeIndex(streamType, mIndex);
             mDeathHandlers = new ArrayList<VolumeDeathHandler>();
         }
 
         public boolean adjustIndex(int deltaIndex) {
-            return setIndex(mIndex + deltaIndex, true);
+            return setIndex(mIndex + deltaIndex * 10, true);
         }
 
         public boolean setIndex(int index, boolean lastAudible) {
@@ -1161,6 +918,13 @@
                 if (lastAudible) {
                     mLastAudibleIndex = mIndex;
                 }
+                // Apply change to all streams using this one as alias
+                int numStreamTypes = AudioSystem.getNumStreamTypes();
+                for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
+                    if (streamType != mStreamType && STREAM_VOLUME_ALIAS[streamType] == mStreamType) {
+                        mStreamStates[streamType].setIndex(rescaleIndex(mIndex, mStreamType, streamType), lastAudible);
+                    }
+                }
                 return true;
             } else {
                 return false;
@@ -1168,7 +932,7 @@
         }
 
         public int getMaxIndex() {
-            return mVolumes.length - 1;
+            return mIndexMax;
         }
 
         public void mute(IBinder cb, boolean state) {
@@ -1183,8 +947,8 @@
         private int getValidIndex(int index) {
             if (index < 0) {
                 return 0;
-            } else if (index >= mVolumes.length) {
-                return mVolumes.length - 1;
+            } else if (index > mIndexMax) {
+                return mIndexMax;
             }
 
             return index;
@@ -1318,8 +1082,16 @@
         private void setSystemVolume(VolumeStreamState streamState) {
 
             // Adjust volume
-            AudioSystem
-                    .setVolume(streamState.mStreamType, streamState.mVolumes[streamState.mIndex]);
+            setStreamVolumeIndex(streamState.mStreamType, streamState.mIndex);
+
+            // Apply change to all streams using this one as alias
+            int numStreamTypes = AudioSystem.getNumStreamTypes();
+            for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
+                if (streamType != streamState.mStreamType &&
+                    STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) {
+                    setStreamVolumeIndex(streamType, mStreamStates[streamType].mIndex);
+                }
+            }
 
             // Post a persist volume msg
             sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType,
@@ -1327,12 +1099,10 @@
         }
 
         private void persistVolume(VolumeStreamState streamState) {
-            if (streamState.mStreamType != AudioManager.STREAM_BLUETOOTH_SCO) {
-                System.putInt(mContentResolver, streamState.mVolumeIndexSettingName,
-                        streamState.mIndex);
-                System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName,
-                        streamState.mLastAudibleIndex);
-            }
+            System.putInt(mContentResolver, streamState.mVolumeIndexSettingName,
+                    (streamState.mIndex + 5)/ 10);
+            System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName,
+                    (streamState.mLastAudibleIndex + 5) / 10);
         }
 
         private void persistRingerMode() {
@@ -1426,18 +1196,17 @@
 
                 case MSG_MEDIA_SERVER_STARTED:
                     Log.e(TAG, "Media server started.");
-                    // Restore audio routing and stream volumes
-                    applyAudioSettings();
+                    // Restore stream volumes
                     int numStreamTypes = AudioSystem.getNumStreamTypes();
                     for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
-                        int volume;
+                        int index;
                         VolumeStreamState streamState = mStreamStates[streamType];
                         if (streamState.muteCount() == 0) {
-                            volume = streamState.mVolumes[streamState.mIndex];
+                            index = streamState.mIndex;
                         } else {
-                            volume = streamState.mVolumes[0];
+                            index = 0;
                         }
-                        AudioSystem.setVolume(streamType, volume);
+                        setStreamVolumeIndex(streamType, index);
                     }
                     setRingerMode(mRingerMode);
                     mMediaServerOk = true;
@@ -1451,28 +1220,144 @@
     }
 
     private class SettingsObserver extends ContentObserver {
-        
+
         SettingsObserver() {
             super(new Handler());
             mContentResolver.registerContentObserver(Settings.System.getUriFor(
                 Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
+            mContentResolver.registerContentObserver(Settings.System.getUriFor(
+                    Settings.System.NOTIFICATIONS_USE_RING_VOLUME), false, this);
         }
 
         @Override
         public void onChange(boolean selfChange) {
             super.onChange(selfChange);
-            
-            mRingerModeAffectedStreams = Settings.System.getInt(mContentResolver,
-                    Settings.System.MODE_RINGER_STREAMS_AFFECTED,
-                    0);
+            synchronized (mSettingsLock) {
+                int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver,
+                        Settings.System.MODE_RINGER_STREAMS_AFFECTED,
+                        0);
+                if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
+                    /*
+                     * Ensure all stream types that should be affected by ringer mode
+                     * are in the proper state.
+                     */
+                    mRingerModeAffectedStreams = ringerModeAffectedStreams;
+                    setRingerModeInt(getRingerMode(), false);
+                }
 
-            /*
-             * Ensure all stream types that should be affected by ringer mode
-             * are in the proper state.
-             */
-            setRingerModeInt(getRingerMode(), false);
+                int notificationsUseRingVolume = Settings.System.getInt(mContentResolver,
+                        Settings.System.NOTIFICATIONS_USE_RING_VOLUME,
+                        1);
+                if (notificationsUseRingVolume != mNotificationsUseRingVolume) {
+                    mNotificationsUseRingVolume = notificationsUseRingVolume;
+                    if (mNotificationsUseRingVolume == 1) {
+                        STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
+                    } else {
+                        STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION;
+                        // Persist notification volume volume as it was not persisted while aliased to ring volume
+                        sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, AudioSystem.STREAM_NOTIFICATION,
+                                SENDMSG_REPLACE, 0, 0, mStreamStates[AudioSystem.STREAM_NOTIFICATION], PERSIST_DELAY);
+                    }
+                }
+            }
         }
-        
     }
-    
+
+    /**
+     * Receiver for misc intent broadcasts the Phone app cares about.
+     */
+    private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            String action = intent.getAction();
+
+            if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) {
+                int state = intent.getIntExtra(BluetoothA2dp.SINK_STATE,
+                                               BluetoothA2dp.STATE_DISCONNECTED);
+                String address = intent.getStringExtra(BluetoothIntent.ADDRESS);
+                if (state == BluetoothA2dp.STATE_DISCONNECTED) {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
+                            AudioSystem.DEVICE_STATE_UNAVAILABLE,
+                            address);
+                } else if (state == BluetoothA2dp.STATE_CONNECTED){
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
+                                                         AudioSystem.DEVICE_STATE_AVAILABLE,
+                                                         address);
+                }
+            } else if (action.equals(BluetoothIntent.HEADSET_AUDIO_STATE_CHANGED_ACTION)) {
+                int state = intent.getIntExtra(BluetoothIntent.HEADSET_AUDIO_STATE,
+                                               BluetoothHeadset.STATE_ERROR);
+                String address = intent.getStringExtra(BluetoothIntent.ADDRESS);
+                if (state == BluetoothHeadset.AUDIO_STATE_DISCONNECTED) {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_SCO,
+                                                         AudioSystem.DEVICE_STATE_UNAVAILABLE,
+                                                         address);
+                } else if (state == BluetoothHeadset.AUDIO_STATE_CONNECTED) {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_SCO,
+                                                         AudioSystem.DEVICE_STATE_AVAILABLE,
+                                                         address);
+                }
+            } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
+                int state = intent.getIntExtra("state", 0);
+                if ((state & BIT_HEADSET) == 0 &&
+                    (mHeadsetState & BIT_HEADSET) != 0) {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
+                            AudioSystem.DEVICE_STATE_UNAVAILABLE,
+                            "");
+                } else if ((state & BIT_HEADSET) != 0 &&
+                    (mHeadsetState & BIT_HEADSET) == 0)  {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
+                            AudioSystem.DEVICE_STATE_AVAILABLE,
+                            "");
+                }
+                if ((state & BIT_HEADSET_NO_MIC) == 0 &&
+                    (mHeadsetState & BIT_HEADSET_NO_MIC) != 0) {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
+                            AudioSystem.DEVICE_STATE_UNAVAILABLE,
+                            "");
+                } else if ((state & BIT_HEADSET_NO_MIC) != 0 &&
+                    (mHeadsetState & BIT_HEADSET_NO_MIC) == 0)  {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
+                            AudioSystem.DEVICE_STATE_AVAILABLE,
+                            "");
+                }
+                if ((state & BIT_TTY) == 0 &&
+                    (mHeadsetState & BIT_TTY) != 0) {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_TTY,
+                            AudioSystem.DEVICE_STATE_UNAVAILABLE,
+                            "");
+                } else if ((state & BIT_TTY) != 0 &&
+                    (mHeadsetState & BIT_TTY) == 0)  {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_TTY,
+                            AudioSystem.DEVICE_STATE_AVAILABLE,
+                            "");
+                }
+                if ((state & BIT_FM_HEADSET) == 0 &&
+                    (mHeadsetState & BIT_FM_HEADSET) != 0) {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_FM_HEADPHONE,
+                            AudioSystem.DEVICE_STATE_UNAVAILABLE,
+                            "");
+                } else if ((state & BIT_FM_HEADSET) != 0 &&
+                    (mHeadsetState & BIT_FM_HEADSET) == 0)  {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_FM_HEADPHONE,
+                            AudioSystem.DEVICE_STATE_AVAILABLE,
+                            "");
+                }
+                if ((state & BIT_FM_SPEAKER) == 0 &&
+                    (mHeadsetState & BIT_FM_SPEAKER) != 0) {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_FM_SPEAKER,
+                            AudioSystem.DEVICE_STATE_UNAVAILABLE,
+                            "");
+                } else if ((state & BIT_FM_SPEAKER) != 0 &&
+                    (mHeadsetState & BIT_FM_SPEAKER) == 0)  {
+                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_FM_SPEAKER,
+                            AudioSystem.DEVICE_STATE_AVAILABLE,
+                            "");
+                }
+                mHeadsetState = state;
+            }
+        }
+    }
+
+
 }
diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java
index 5917ab90..d587f65 100644
--- a/media/java/android/media/AudioSystem.java
+++ b/media/java/android/media/AudioSystem.java
@@ -45,38 +45,21 @@
     public static final int STREAM_NOTIFICATION = 5;
     /* @hide The audio stream for phone calls when connected on bluetooth */
     public static final int STREAM_BLUETOOTH_SCO = 6;
+    /* @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
+    public static final int STREAM_SYSTEM_ENFORCED = 7;
+    /* @hide The audio stream for DTMF tones */
+    public static final int STREAM_DTMF = 8;
+    /* @hide The audio stream for text to speech (TTS) */
+    public static final int STREAM_TTS = 9;
     /**
      * @deprecated Use {@link #numStreamTypes() instead}
      */
     public static final int NUM_STREAMS = 5;
 
     // Expose only the getter method publicly so we can change it in the future
-    private static final int NUM_STREAM_TYPES = 7;
+    private static final int NUM_STREAM_TYPES = 10;
     public static final int getNumStreamTypes() { return NUM_STREAM_TYPES; }
 
-    /* max and min volume levels */
-    /* Maximum volume setting, for use with setVolume(int,int) */
-    public static final int MAX_VOLUME = 100;
-    /* Minimum volume setting, for use with setVolume(int,int) */
-    public static final int MIN_VOLUME = 0;
-
-    /*
-     * Sets the volume of a specified audio stream.
-     *
-     * param type   the stream type to set the volume of (e.g. STREAM_MUSIC)
-     * param volume the volume level to set (0-100)
-     * return command completion status see AUDIO_STATUS_OK, see AUDIO_STATUS_ERROR
-     */
-    public static native int setVolume(int type, int volume);
-
-    /*
-     * Returns the volume of a specified audio stream.
-     *
-     * param type the stream type to get the volume of (e.g. STREAM_MUSIC)
-     * return the current volume (0-100)
-     */
-    public static native int getVolume(int type);
-
     /*
      * Sets the microphone mute on or off.
      *
@@ -101,17 +84,22 @@
      *              it can route the audio appropriately.
      * return command completion status see AUDIO_STATUS_OK, see AUDIO_STATUS_ERROR
      */
-    public static native int setMode(int mode);
-
+    /** @deprecated use {@link #setPhoneState(int)} */
+    public static int setMode(int mode) {
+        return AUDIO_STATUS_ERROR;
+    }
     /*
      * Returns the current audio mode.
      *
      * return      the current audio mode (NORMAL, RINGTONE, or IN_CALL).
      *              Returns the current current audio state from the HAL.
      */
-    public static native int getMode();
+    /** @deprecated */
+    public static int getMode() {
+        return MODE_INVALID;
+    }
 
-    /* modes for setMode/getMode/setRoute/getRoute */
+    /* modes for setPhoneState */
     public static final int MODE_INVALID            = -2;
     public static final int MODE_CURRENT            = -1;
     public static final int MODE_NORMAL             = 0;
@@ -121,15 +109,20 @@
 
 
     /* Routing bits for setRouting/getRouting API */
-    public static final int ROUTE_EARPIECE          = (1 << 0);
-    public static final int ROUTE_SPEAKER           = (1 << 1);
-
+    /** @deprecated */
+    @Deprecated public static final int ROUTE_EARPIECE          = (1 << 0);
+    /** @deprecated */
+    @Deprecated public static final int ROUTE_SPEAKER           = (1 << 1);
     /** @deprecated use {@link #ROUTE_BLUETOOTH_SCO} */
     @Deprecated public static final int ROUTE_BLUETOOTH = (1 << 2);
-    public static final int ROUTE_BLUETOOTH_SCO     = (1 << 2);
-    public static final int ROUTE_HEADSET           = (1 << 3);
-    public static final int ROUTE_BLUETOOTH_A2DP    = (1 << 4);
-    public static final int ROUTE_ALL               = 0xFFFFFFFF;
+    /** @deprecated */
+    @Deprecated public static final int ROUTE_BLUETOOTH_SCO     = (1 << 2);
+    /** @deprecated */
+    @Deprecated public static final int ROUTE_HEADSET           = (1 << 3);
+    /** @deprecated */
+    @Deprecated public static final int ROUTE_BLUETOOTH_A2DP    = (1 << 4);
+    /** @deprecated */
+    @Deprecated public static final int ROUTE_ALL               = 0xFFFFFFFF;
 
     /*
      * Sets the audio routing for a specified mode
@@ -141,7 +134,10 @@
      * ROUTE_xxx types. Unset bits indicate the route should be left unchanged
      * return command completion status see AUDIO_STATUS_OK, see AUDIO_STATUS_ERROR
      */
-    public static native int setRouting(int mode, int routes, int mask);
+    /** @deprecated use {@link #setDeviceConnectionState(int,int,String)} */
+    public static int setRouting(int mode, int routes, int mask) {
+        return AUDIO_STATUS_ERROR;
+    }
 
     /*
      * Returns the current audio routing bit vector for a specified mode.
@@ -150,7 +146,10 @@
      * return an audio route bit vector that can be compared with ROUTE_xxx
      * bits
      */
-    public static native int getRouting(int mode);
+    /** @deprecated use {@link #getDeviceConnectionState(int,String)} */
+    public static int getRouting(int mode) {
+        return 0;
+    }
 
     /*
      * Checks whether any music is active.
@@ -160,17 +159,23 @@
     public static native boolean isMusicActive();
 
     /*
-     * Sets a generic audio configuration parameter. The use of these parameters
+     * Sets a group generic audio configuration parameters. The use of these parameters
      * are platform dependant, see libaudio
      *
-     * ** Temporary interface - DO NOT USE
-     *
-     * TODO: Replace with a more generic key:value get/set mechanism
-     *
-     * param key   name of parameter to set. Must not be null.
-     * param value value of parameter. Must not be null.
+     * param keyValuePairs  list of parameters key value pairs in the form:
+     *    key1=value1;key2=value2;...
      */
-    public static native void setParameter(String key, String value);
+    public static native int setParameters(String keyValuePairs);
+
+    /*
+     * Gets a group generic audio configuration parameters. The use of these parameters
+     * are platform dependant, see libaudio
+     *
+     * param keys  list of parameters
+     * return value: list of parameters key value pairs in the form:
+     *    key1=value1;key2=value2;...
+     */
+    public static native String getParameters(String keys);
 
     /*
     private final static String TAG = "audio";
@@ -220,4 +225,68 @@
             mErrorCallback.onError(error);
         }
     }
+
+    /*
+     * AudioPolicyService methods
+     */
+
+    // output devices
+    public static final int DEVICE_OUT_EARPIECE = 0x1;
+    public static final int DEVICE_OUT_SPEAKER = 0x2;
+    public static final int DEVICE_OUT_WIRED_HEADSET = 0x4;
+    public static final int DEVICE_OUT_WIRED_HEADPHONE = 0x8;
+    public static final int DEVICE_OUT_BLUETOOTH_SCO = 0x10;
+    public static final int DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 0x20;
+    public static final int DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 0x40;
+    public static final int DEVICE_OUT_BLUETOOTH_A2DP = 0x80;
+    public static final int DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100;
+    public static final int DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 0x200;
+    public static final int DEVICE_OUT_AUX_DIGITAL = 0x400;
+    public static final int DEVICE_OUT_FM_HEADPHONE = 0x800;
+    public static final int DEVICE_OUT_FM_SPEAKER = 0x1000;
+    public static final int DEVICE_OUT_TTY = 0x2000;
+    public static final int DEVICE_OUT_DEFAULT = 0x8000;
+    // input devices
+    public static final int DEVICE_IN_COMMUNICATION = 0x10000;
+    public static final int DEVICE_IN_AMBIENT = 0x20000;
+    public static final int DEVICE_IN_BUILTIN_MIC1 = 0x40000;
+    public static final int DEVICE_IN_BUILTIN_MIC2 = 0x80000;
+    public static final int DEVICE_IN_MIC_ARRAY = 0x100000;
+    public static final int DEVICE_IN_BLUETOOTH_SCO_HEADSET = 0x200000;
+    public static final int DEVICE_IN_WIRED_HEADSET = 0x400000;
+    public static final int DEVICE_IN_AUX_DIGITAL = 0x800000;
+    public static final int DEVICE_IN_DEFAULT = 0x80000000;
+
+    // device states
+    public static final int DEVICE_STATE_UNAVAILABLE = 0;
+    public static final int DEVICE_STATE_AVAILABLE = 1;
+
+    // phone state
+    public static final int PHONE_STATE_OFFCALL = 0;
+    public static final int PHONE_STATE_RINGING = 1;
+    public static final int PHONE_STATE_INCALL = 2;
+
+    // config for setForceUse
+    public static final int FORCE_NONE = 0;
+    public static final int FORCE_SPEAKER = 1;
+    public static final int FORCE_HEADPHONES = 2;
+    public static final int FORCE_BT_SCO = 3;
+    public static final int FORCE_BT_A2DP = 4;
+    public static final int FORCE_WIRED_ACCESSORY = 5;
+    public static final int FORCE_DEFAULT = FORCE_NONE;
+
+    // usage for serForceUse
+    public static final int FOR_COMMUNICATION = 0;
+    public static final int FOR_MEDIA = 1;
+    public static final int FOR_RECORD = 2;
+
+    public static native int setDeviceConnectionState(int device, int state, String device_address);
+    public static native int getDeviceConnectionState(int device, String device_address);
+    public static native int setPhoneState(int state);
+    public static native int setRingerMode(int mode, int mask);
+    public static native int setForceUse(int usage, int config);
+    public static native int getForceUse(int usage);
+    public static native int initStreamVolume(int stream, int indexMin, int indexMax);
+    public static native int setStreamVolumeIndex(int stream, int index);
+    public static native int getStreamVolumeIndex(int stream);
 }
diff --git a/media/java/android/media/AudioTrack.java b/media/java/android/media/AudioTrack.java
index 5f1be9d..7fbe965 100644
--- a/media/java/android/media/AudioTrack.java
+++ b/media/java/android/media/AudioTrack.java
@@ -120,7 +120,7 @@
     public  static final int ERROR_INVALID_OPERATION               = -3;
 
     private static final int ERROR_NATIVESETUP_AUDIOSYSTEM         = -16;
-    private static final int ERROR_NATIVESETUP_INVALIDCHANNELCOUNT = -17;
+    private static final int ERROR_NATIVESETUP_INVALIDCHANNELMASK  = -17;
     private static final int ERROR_NATIVESETUP_INVALIDFORMAT       = -18;
     private static final int ERROR_NATIVESETUP_INVALIDSTREAMTYPE   = -19;
     private static final int ERROR_NATIVESETUP_NATIVEINITFAILED    = -20;
@@ -198,7 +198,7 @@
     /**
      * The current audio channel configuration.
      */
-    private int mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+    private int mChannelConfiguration = AudioFormat.CHANNEL_OUT_MONO;
     /**
      * The encoding of the audio samples.
      * @see AudioFormat#ENCODING_PCM_8BIT
@@ -235,8 +235,8 @@
      * @param sampleRateInHz the sample rate expressed in Hertz. Examples of rates are (but
      *   not limited to) 44100, 22050 and 11025.
      * @param channelConfig describes the configuration of the audio channels.
-     *   See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO} and
-     *   {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO}
+     *   See {@link AudioFormat#CHANNEL_OUT_MONO} and
+     *   {@link AudioFormat#CHANNEL_OUT_STEREO}
      * @param audioFormat the format in which the audio data is represented.
      *   See {@link AudioFormat#ENCODING_PCM_16BIT} and
      *   {@link AudioFormat#ENCODING_PCM_8BIT}
@@ -298,7 +298,8 @@
            && (streamType != AudioManager.STREAM_RING) && (streamType != AudioManager.STREAM_SYSTEM)
            && (streamType != AudioManager.STREAM_VOICE_CALL)
            && (streamType != AudioManager.STREAM_NOTIFICATION)
-           && (streamType != AudioManager.STREAM_BLUETOOTH_SCO)) {
+           && (streamType != AudioManager.STREAM_BLUETOOTH_SCO)
+           && (streamType != AudioManager.STREAM_DTMF)) {
             throw (new IllegalArgumentException("Invalid stream type."));
         } else {
             mStreamType = streamType;
@@ -316,18 +317,18 @@
         //--------------
         // channel config
         switch (channelConfig) {
-        case AudioFormat.CHANNEL_CONFIGURATION_DEFAULT:
-        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
+        case AudioFormat.CHANNEL_OUT_DEFAULT:
+        case AudioFormat.CHANNEL_OUT_MONO:
             mChannelCount = 1;
-            mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+            mChannelConfiguration = AudioFormat.CHANNEL_OUT_MONO;
             break;
-        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
+        case AudioFormat.CHANNEL_OUT_STEREO:
             mChannelCount = 2;
-            mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+            mChannelConfiguration = AudioFormat.CHANNEL_OUT_STEREO;
             break;
         default:
             mChannelCount = 0;
-            mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_INVALID;
+            mChannelConfiguration = AudioFormat.CHANNEL_INVALID;
             throw(new IllegalArgumentException("Unsupported channel configuration."));
         }
 
@@ -452,8 +453,8 @@
     /**
      * Returns the configured channel configuration.
 
-     * See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO}
-     * and {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO}.
+     * See {@link AudioFormat#CHANNEL_OUT_MONO}
+     * and {@link AudioFormat#CHANNEL_OUT_STEREO}.
      */
     public int getChannelConfiguration() {
         return mChannelConfiguration;
@@ -531,8 +532,8 @@
      * the expected frequency at which the buffer will be refilled with additional data to play. 
      * @param sampleRateInHz the sample rate expressed in Hertz.
      * @param channelConfig describes the configuration of the audio channels. 
-     *   See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO} and
-     *   {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO}
+     *   See {@link AudioFormat#CHANNEL_OUT_MONO} and
+     *   {@link AudioFormat#CHANNEL_OUT_STEREO}
      * @param audioFormat the format in which the audio data is represented. 
      *   See {@link AudioFormat#ENCODING_PCM_16BIT} and 
      *   {@link AudioFormat#ENCODING_PCM_8BIT}
@@ -544,10 +545,10 @@
     static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) {
         int channelCount = 0;
         switch(channelConfig) {
-        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
+        case AudioFormat.CHANNEL_OUT_MONO:
             channelCount = 1;
             break;
-        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
+        case AudioFormat.CHANNEL_OUT_STEREO:
             channelCount = 2;
             break;
         default:
diff --git a/media/java/android/media/IAudioService.aidl b/media/java/android/media/IAudioService.aidl
index 9a8264f..bb4252b 100644
--- a/media/java/android/media/IAudioService.aidl
+++ b/media/java/android/media/IAudioService.aidl
@@ -29,9 +29,9 @@
     
     void setStreamVolume(int streamType, int index, int flags);
     
-   	void setStreamSolo(int streamType, boolean state, IBinder cb);
+    void setStreamSolo(int streamType, boolean state, IBinder cb);
    	
-   	void setStreamMute(int streamType, boolean state, IBinder cb);
+    void setStreamMute(int streamType, boolean state, IBinder cb);
     
     int getStreamVolume(int streamType);
     
@@ -46,23 +46,11 @@
     int getVibrateSetting(int vibrateType);
     
     boolean shouldVibrate(int vibrateType);
-    
-    void setMicrophoneMute(boolean on);
-
-    boolean isMicrophoneMute();
 
     void setMode(int mode);
 
     int getMode();
 
-    void setRouting(int mode, int routes, int mask);
-
-    int getRouting(int mode);
-
-    boolean isMusicActive();
-
-    void setParameter(String key, String value);
-
     oneway void playSoundEffect(int effectType);
   
     oneway void playSoundEffectVolume(int effectType, float volume);
diff --git a/media/java/android/media/JetPlayer.java b/media/java/android/media/JetPlayer.java
index 4fb0ead..2263605 100644
--- a/media/java/android/media/JetPlayer.java
+++ b/media/java/android/media/JetPlayer.java
@@ -89,7 +89,7 @@
     // Jet rendering audio parameters
     private static final int JET_OUTPUT_RATE = 22050; // _SAMPLE_RATE_22050 in Android.mk
     private static final int JET_OUTPUT_CHANNEL_CONFIG =
-            AudioFormat.CHANNEL_CONFIGURATION_STEREO; // NUM_OUTPUT_CHANNELS=2 in Android.mk
+            AudioFormat.CHANNEL_OUT_STEREO; // NUM_OUTPUT_CHANNELS=2 in Android.mk
 
     
     //--------------------------------------------
diff --git a/media/java/android/media/MediaFile.java b/media/java/android/media/MediaFile.java
index 8be11df..03ffc67 100644
--- a/media/java/android/media/MediaFile.java
+++ b/media/java/android/media/MediaFile.java
@@ -41,8 +41,9 @@
     public static final int FILE_TYPE_AWB     = 5;
     public static final int FILE_TYPE_WMA     = 6;
     public static final int FILE_TYPE_OGG     = 7;
+    public static final int FILE_TYPE_AAC     = 8;
     private static final int FIRST_AUDIO_FILE_TYPE = FILE_TYPE_MP3;
-    private static final int LAST_AUDIO_FILE_TYPE = FILE_TYPE_OGG;
+    private static final int LAST_AUDIO_FILE_TYPE = FILE_TYPE_AAC;
 
     // MIDI file types
     public static final int FILE_TYPE_MID     = 11;
@@ -57,8 +58,9 @@
     public static final int FILE_TYPE_3GPP    = 23;
     public static final int FILE_TYPE_3GPP2   = 24;
     public static final int FILE_TYPE_WMV     = 25;
+    public static final int FILE_TYPE_ASF     = 26;
     private static final int FIRST_VIDEO_FILE_TYPE = FILE_TYPE_MP4;
-    private static final int LAST_VIDEO_FILE_TYPE = FILE_TYPE_WMV;
+    private static final int LAST_VIDEO_FILE_TYPE = FILE_TYPE_ASF;
     
     // Image file types
     public static final int FILE_TYPE_JPEG    = 31;
@@ -104,6 +106,7 @@
         addFileType("WMA", FILE_TYPE_WMA, "audio/x-ms-wma");    
         addFileType("OGG", FILE_TYPE_OGG, "application/ogg");
         addFileType("OGA", FILE_TYPE_OGG, "application/ogg");
+        addFileType("AAC", FILE_TYPE_AAC, "audio/aac");
  
         addFileType("MID", FILE_TYPE_MID, "audio/midi");
         addFileType("MIDI", FILE_TYPE_MID, "audio/midi");
@@ -121,6 +124,7 @@
         addFileType("3G2", FILE_TYPE_3GPP2, "video/3gpp2");
         addFileType("3GPP2", FILE_TYPE_3GPP2, "video/3gpp2");
         addFileType("WMV", FILE_TYPE_WMV, "video/x-ms-wmv");
+        addFileType("ASF", FILE_TYPE_ASF, "video/x-ms-asf");
 
         addFileType("JPG", FILE_TYPE_JPEG, "image/jpeg");
         addFileType("JPEG", FILE_TYPE_JPEG, "image/jpeg");
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index 3b46d69..a23f535 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -23,6 +23,7 @@
 import android.os.Handler;
 import android.os.Looper;
 import android.os.Message;
+import android.os.Parcel;
 import android.os.ParcelFileDescriptor;
 import android.os.PowerManager;
 import android.util.Log;
@@ -33,7 +34,7 @@
 
 import java.io.FileDescriptor;
 import java.io.IOException;
-
+import java.util.Set;
 import java.lang.ref.WeakReference;
 
 /**
@@ -430,11 +431,48 @@
  */
 public class MediaPlayer
 {
+    /**
+       Constant to retrieve only the new metadata since the last
+       call.
+       // FIXME: unhide.
+       // FIXME: add link to getMetadata(boolean, boolean)
+       {@hide}
+     */
+    public static final boolean METADATA_UPDATE_ONLY = true;
+
+    /**
+       Constant to retrieve all the metadata.
+       // FIXME: unhide.
+       // FIXME: add link to getMetadata(boolean, boolean)
+       {@hide}
+     */
+    public static final boolean METADATA_ALL = false;
+
+    /**
+       Constant to enable the metadata filter during retrieval.
+       // FIXME: unhide.
+       // FIXME: add link to getMetadata(boolean, boolean)
+       {@hide}
+     */
+    public static final boolean APPLY_METADATA_FILTER = true;
+
+    /**
+       Constant to disable the metadata filter during retrieval.
+       // FIXME: unhide.
+       // FIXME: add link to getMetadata(boolean, boolean)
+       {@hide}
+     */
+    public static final boolean BYPASS_METADATA_FILTER = false;
+
     static {
         System.loadLibrary("media_jni");
     }
 
     private final static String TAG = "MediaPlayer";
+    // Name of the remote interface for the media player. Must be kept
+    // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
+    // macro invocation in IMediaPlayer.cpp
+    private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
 
     private int mNativeContext; // accessed by native methods
     private int mListenerContext; // accessed by native methods
@@ -475,6 +513,43 @@
     private native void _setVideoSurface();
 
     /**
+     * Create a request parcel which can be routed to the native media
+     * player using {@link #invoke(Parcel, Parcel)}. The Parcel
+     * returned has the proper InterfaceToken set. The caller should
+     * not overwrite that token, i.e it can only append data to the
+     * Parcel.
+     *
+     * @return A parcel suitable to hold a request for the native
+     * player.
+     */
+    public Parcel newRequest() {
+        Parcel parcel = Parcel.obtain();
+        parcel.writeInterfaceToken(IMEDIA_PLAYER);
+        return parcel;
+    }
+
+    /**
+     * Invoke a generic method on the native player using opaque
+     * parcels for the request and reply. Both payloads' format is a
+     * convention between the java caller and the native player.
+     * Must be called after setDataSource to make sure a native player
+     * exists.
+     *
+     * @param request Parcel with the data for the extension. The
+     * caller must use {@link #newRequest()} to get one.
+     *
+     * @param[out] reply Parcel with the data returned by the
+     * native player.
+     *
+     * @return The status code see utils/Errors.h
+     */
+    public int invoke(Parcel request, Parcel reply) {
+        int retcode = native_invoke(request, reply);
+        reply.setDataPosition(0);
+        return retcode;
+    }
+
+    /**
      * Sets the SurfaceHolder to use for displaying the video portion of the media.
      * This call is optional. Not calling it when playing back a video will
      * result in only the audio track being played.
@@ -838,6 +913,89 @@
     public native int getDuration();
 
     /**
+     * Gets the media metadata.
+     *
+     * @param update_only controls whether the full set of available
+     * metadata is returned or just the set that changed since the
+     * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
+     * #METADATA_ALL}.
+     *
+     * @param apply_filter if true only metadata that matches the
+     * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
+     * #BYPASS_METADATA_FILTER}.
+     *
+     * @return The metadata, possibly empty. null if an error occured.
+     // FIXME: unhide.
+     * {@hide}
+     */
+    public Metadata getMetadata(final boolean update_only,
+                                final boolean apply_filter) {
+        Parcel reply = Parcel.obtain();
+        Metadata data = new Metadata();
+
+        if (!native_getMetadata(update_only, apply_filter, reply)) {
+            reply.recycle();
+            return null;
+        }
+
+        // Metadata takes over the parcel, don't recycle it unless
+        // there is an error.
+        if (!data.parse(reply)) {
+            reply.recycle();
+            return null;
+        }
+        return data;
+    }
+
+    /**
+     * Set a filter for the metadata update notification and update
+     * retrieval. The caller provides 2 set of metadata keys, allowed
+     * and blocked. The blocked set always takes precedence over the
+     * allowed one.
+     * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
+     * shorthands to allow/block all or no metadata.
+     *
+     * By default, there is no filter set.
+     *
+     * @param allow Is the set of metadata the client is interested
+     *              in receiving new notifications for.
+     * @param block Is the set of metadata the client is not interested
+     *              in receiving new notifications for.
+     * @return The call status code.
+     *
+     // FIXME: unhide.
+     * {@hide}
+     */
+    public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
+        // Do our serialization manually instead of calling
+        // Parcel.writeArray since the sets are made of the same type
+        // we avoid paying the price of calling writeValue (used by
+        // writeArray) which burns an extra int per element to encode
+        // the type.
+        Parcel request =  newRequest();
+
+        // The parcel starts already with an interface token. There
+        // are 2 filters. Each one starts with a 4bytes number to
+        // store the len followed by a number of int (4 bytes as well)
+        // representing the metadata type.
+        int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
+
+        if (request.dataCapacity() < capacity) {
+            request.setDataCapacity(capacity);
+        }
+
+        request.writeInt(allow.size());
+        for(Integer t: allow) {
+            request.writeInt(t);
+        }
+        request.writeInt(block.size());
+        for(Integer t: block) {
+            request.writeInt(t);
+        }
+        return native_setMetadataFilter(request);
+    }
+
+    /**
      * Releases resources associated with this MediaPlayer object.
      * It is considered good practice to call this method when you're
      * done using the MediaPlayer.
@@ -915,8 +1073,45 @@
      */
     public native Bitmap getFrameAt(int msec) throws IllegalStateException;
 
+    /**
+     * @param request Parcel destinated to the media player. The
+     *                Interface token must be set to the IMediaPlayer
+     *                one to be routed correctly through the system.
+     * @param reply[out] Parcel that will contain the reply.
+     * @return The status code.
+     */
+    private native final int native_invoke(Parcel request, Parcel reply);
+
+
+    /**
+     * @param update_only If true fetch only the set of metadata that have
+     *                    changed since the last invocation of getMetadata.
+     *                    The set is built using the unfiltered
+     *                    notifications the native player sent to the
+     *                    MediaPlayerService during that period of
+     *                    time. If false, all the metadatas are considered.
+     * @param apply_filter  If true, once the metadata set has been built based on
+     *                     the value update_only, the current filter is applied.
+     * @param reply[out] On return contains the serialized
+     *                   metadata. Valid only if the call was successful.
+     * @return The status code.
+     */
+    private native final boolean native_getMetadata(boolean update_only,
+                                                    boolean apply_filter,
+                                                    Parcel reply);
+
+    /**
+     * @param request Parcel with the 2 serialized lists of allowed
+     *                metadata types followed by the one to be
+     *                dropped. Each list starts with an integer
+     *                indicating the number of metadata type elements.
+     * @return The status code.
+     */
+    private native final int native_setMetadataFilter(Parcel request);
+
     private native final void native_setup(Object mediaplayer_this);
     private native final void native_finalize();
+
     @Override
     protected void finalize() { native_finalize(); }
 
@@ -1254,6 +1449,11 @@
      */
     public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
 
+    /** A new set of metadata is available.
+     * @see android.media.MediaPlayer.OnInfoListener
+     */
+    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
+
     /**
      * Interface definition of a callback to be invoked to communicate some
      * info and/or warning about the media or its playback.
@@ -1270,6 +1470,7 @@
          * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
          * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
          * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
+         * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
          * </ul>
          * @param extra an extra code, specific to the info. Typically
          * implementation dependant.
diff --git a/media/java/android/media/MediaScanner.java b/media/java/android/media/MediaScanner.java
index 95f3680..d5801f7 100644
--- a/media/java/android/media/MediaScanner.java
+++ b/media/java/android/media/MediaScanner.java
@@ -307,10 +307,14 @@
     private boolean mDefaultRingtoneSet;
     /** Whether the scanner has set a default sound for the notification ringtone. */
     private boolean mDefaultNotificationSet;
+    /** Whether the scanner has set a default sound for the alarm ringtone. */
+    private boolean mDefaultAlarmSet;
     /** The filename for the default sound for the ringer ringtone. */
     private String mDefaultRingtoneFilename;
     /** The filename for the default sound for the notification ringtone. */
     private String mDefaultNotificationFilename;
+    /** The filename for the default sound for the alarm ringtone. */
+    private String mDefaultAlarmAlertFilename;
     /**
      * The prefix for system properties that define the default sound for
      * ringtones. Concatenate the name of the setting from Settings
@@ -369,6 +373,8 @@
                 + Settings.System.RINGTONE);
         mDefaultNotificationFilename = SystemProperties.get(DEFAULT_RINGTONE_PROPERTY_PREFIX
                 + Settings.System.NOTIFICATION_SOUND);
+        mDefaultAlarmAlertFilename = SystemProperties.get(DEFAULT_RINGTONE_PROPERTY_PREFIX
+                + Settings.System.ALARM_ALERT);
     }
 
     private MyMediaScannerClient mClient = new MyMediaScannerClient();
@@ -759,6 +765,12 @@
                     setSettingIfNotSet(Settings.System.RINGTONE, tableUri, rowId);
                     mDefaultRingtoneSet = true;
                 }
+            } else if (alarms && !mDefaultAlarmSet) {
+                if (TextUtils.isEmpty(mDefaultAlarmAlertFilename) ||
+                        doesPathHaveFilename(entry.mPath, mDefaultAlarmAlertFilename)) {
+                    setSettingIfNotSet(Settings.System.ALARM_ALERT, tableUri, rowId);
+                    mDefaultAlarmSet = true;
+                }
             }
 
             return result;
diff --git a/media/java/android/media/Metadata.java b/media/java/android/media/Metadata.java
new file mode 100644
index 0000000..bd25da2
--- /dev/null
+++ b/media/java/android/media/Metadata.java
@@ -0,0 +1,418 @@
+/*
+ * 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.
+ */
+
+package android.media;
+
+import android.graphics.Bitmap;
+import android.os.Parcel;
+import android.util.Log;
+
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Set;
+import java.util.TimeZone;
+
+
+/**
+   Class to hold the media's metadata.  Metadata are used
+   for human consumption and can be embedded in the media (e.g
+   shoutcast) or available from an external source. The source can be
+   local (e.g thumbnail stored in the DB) or remote (e.g caption
+   server).
+
+   Metadata is like a Bundle. It is sparse and each key can occur at
+   most once. The key is an integer and the value is the actual metadata.
+
+   The caller is expected to know the type of the metadata and call
+   the right get* method to fetch its value.
+
+   // FIXME: unhide.
+   {@hide}
+ */
+public class Metadata
+{
+    // The metadata are keyed using integers rather than more heavy
+    // weight strings. We considered using Bundle to ship the metadata
+    // between the native layer and the java layer but dropped that
+    // option since keeping in sync a native implementation of Bundle
+    // and the java one would be too burdensome. Besides Bundle uses
+    // String for its keys.
+    // The key range [0 8192) is reserved for the system.
+    //
+    // We manually serialize the data in Parcels. For large memory
+    // blob (bitmaps, raw pictures) we use MemoryFile which allow the
+    // client to make the data purge-able once it is done with it.
+    //
+
+    public static final int ANY = 0;  // Never used for metadata returned, only for filtering.
+                                      // Keep in sync with kAny in MediaPlayerService.cpp
+
+    // TODO: Should we use numbers compatible with the metadata retriever?
+    public static final int TITLE = 1;           // String
+    public static final int COMMENT = 2;         // String
+    public static final int COPYRIGHT = 3;       // String
+    public static final int ALBUM = 4;           // String
+    public static final int ARTIST = 5;          // String
+    public static final int AUTHOR = 6;          // String
+    public static final int COMPOSER = 7;        // String
+    public static final int GENRE = 8;           // String
+    public static final int DATE = 9;            // Date
+    public static final int DURATION = 10;       // Integer(millisec)
+    public static final int CD_TRACK_NUM = 11;   // Integer 1-based
+    public static final int CD_TRACK_MAX = 12;   // Integer
+    public static final int RATING = 13;         // String
+    public static final int ALBUM_ART = 14;      // byte[]
+    public static final int VIDEO_FRAME = 15;    // Bitmap
+    public static final int CAPTION = 16;        // TimedText
+
+    public static final int BIT_RATE = 17;       // Integer, Aggregate rate of
+                                                 // all the streams in bps.
+
+    public static final int AUDIO_BIT_RATE = 18; // Integer, bps
+    public static final int VIDEO_BIT_RATE = 19; // Integer, bps
+    public static final int AUDIO_SAMPLE_RATE = 20; // Integer, Hz
+    public static final int VIDEO_FRAME_RATE = 21;  // Integer, Hz
+
+    // See RFC2046 and RFC4281.
+    public static final int MIME_TYPE = 22;      // String
+    public static final int AUDIO_CODEC = 23;    // String
+    public static final int VIDEO_CODEC = 24;    // String
+
+    public static final int VIDEO_HEIGHT = 25;   // Integer
+    public static final int VIDEO_WIDTH = 26;    // Integer
+    public static final int NUM_TRACKS = 27;     // Integer
+    public static final int DRM_CRIPPLED = 28;   // Boolean
+
+    // Playback capabilities.
+    public static final int PAUSE_AVAILABLE = 29;         // Boolean
+    public static final int SEEK_BACKWARD_AVAILABLE = 30; // Boolean
+    public static final int SEEK_FORWARD_AVAILABLE = 31;  // Boolean
+
+    private static final int LAST_SYSTEM = 31;
+    private static final int FIRST_CUSTOM = 8192;
+
+    // Shorthands to set the MediaPlayer's metadata filter.
+    public static final Set<Integer> MATCH_NONE = Collections.EMPTY_SET;
+    public static final Set<Integer> MATCH_ALL = Collections.singleton(ANY);
+
+    public static final int STRING_VAL     = 1;
+    public static final int INTEGER_VAL    = 2;
+    public static final int BOOLEAN_VAL    = 3;
+    public static final int LONG_VAL       = 4;
+    public static final int DOUBLE_VAL     = 5;
+    public static final int TIMED_TEXT_VAL = 6;
+    public static final int DATE_VAL       = 7;
+    public static final int BYTE_ARRAY_VAL = 8;
+    // FIXME: misses a type for shared heap is missing (MemoryFile).
+    // FIXME: misses a type for bitmaps.
+    private static final int LAST_TYPE = 8;
+
+    private static final String TAG = "media.Metadata";
+    private static final int kInt32Size = 4;
+    private static final int kMetaHeaderSize = 2 * kInt32Size; //  size + marker
+    private static final int kRecordHeaderSize = 3 * kInt32Size; // size + id + type
+
+    private static final int kMetaMarker = 0x4d455441;  // 'M' 'E' 'T' 'A'
+
+    // After a successful parsing, set the parcel with the serialized metadata.
+    private Parcel mParcel;
+
+    // Map to associate a Metadata key (e.g TITLE) with the offset of
+    // the record's payload in the parcel.
+    // Used to look up if a key was present too.
+    // Key: Metadata ID
+    // Value: Offset of the metadata type field in the record.
+    private final HashMap<Integer, Integer> mKeyToPosMap =
+            new HashMap<Integer, Integer>();
+
+    /**
+     * Helper class to hold a triple (time, duration, text). Can be used to
+     * implement caption.
+     */
+    public class TimedText {
+        private Date mTime;
+        private int mDuration;  // millisec
+        private String mText;
+
+        public TimedText(Date time, int duration, String text) {
+            mTime = time;
+            mDuration = duration;
+            mText = text;
+        }
+
+        public String toString() {
+            StringBuilder res = new StringBuilder(80);
+            res.append(mTime).append("-").append(mDuration)
+                    .append(":").append(mText);
+            return res.toString();
+        }
+    }
+
+    public Metadata() { }
+
+    /**
+     * Go over all the records, collecting metadata keys and records'
+     * type field offset in the Parcel. These are stored in
+     * mKeyToPosMap for latter retrieval.
+     * Format of a metadata record:
+     <pre>
+                         1                   2                   3
+      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+      |                     record size                               |
+      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+      |                     metadata key                              |  // TITLE
+      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+      |                     metadata type                             |  // STRING_VAL
+      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+      |                                                               |
+      |                .... metadata payload ....                     |
+      |                                                               |
+      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+     </pre>
+     * @param parcel With the serialized records.
+     * @param bytesLeft How many bytes in the parcel should be processed.
+     * @return false if an error occurred during parsing.
+     */
+    private boolean scanAllRecords(Parcel parcel, int bytesLeft) {
+        int recCount = 0;
+        boolean error = false;
+
+        mKeyToPosMap.clear();
+        while (bytesLeft > kRecordHeaderSize) {
+            final int start = parcel.dataPosition();
+            // Check the size.
+            final int size = parcel.readInt();
+
+            if (size <= kRecordHeaderSize) {  // at least 1 byte should be present.
+                Log.e(TAG, "Record is too short");
+                error = true;
+                break;
+            }
+
+            // Check the metadata key.
+            final int metadataId = parcel.readInt();
+            if (!checkMetadataId(metadataId)) {
+                error = true;
+                break;
+            }
+
+            // Store the record offset which points to the type
+            // field so we can later on read/unmarshall the record
+            // payload.
+            if (mKeyToPosMap.containsKey(metadataId)) {
+                Log.e(TAG, "Duplicate metadata ID found");
+                error = true;
+                break;
+            }
+
+            mKeyToPosMap.put(metadataId, parcel.dataPosition());
+
+            // Check the metadata type.
+            final int metadataType = parcel.readInt();
+            if (metadataType <= 0 || metadataType > LAST_TYPE) {
+                Log.e(TAG, "Invalid metadata type " + metadataType);
+                error = true;
+                break;
+            }
+
+            // Skip to the next one.
+            parcel.setDataPosition(start + size);
+            bytesLeft -= size;
+            ++recCount;
+        }
+
+        if (0 != bytesLeft || error) {
+            Log.e(TAG, "Ran out of data or error on record " + recCount);
+            mKeyToPosMap.clear();
+            return false;
+        } else {
+            return true;
+        }
+    }
+
+    /**
+     * Check a parcel containing metadata is well formed. The header
+     * is checked as well as the individual records format. However, the
+     * data inside the record is not checked because we do lazy access
+     * (we check/unmarshall only data the user asks for.)
+     *
+     * Format of a metadata parcel:
+     <pre>
+                         1                   2                   3
+      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+      |                     metadata total size                       |
+      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+      |     'M'       |     'E'       |     'T'       |     'A'       |
+      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+      |                                                               |
+      |                .... metadata records ....                     |
+      |                                                               |
+      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+     </pre>
+     *
+     * @param parcel With the serialized data. Metadata keeps a
+     *               reference on it to access it later on. The caller
+     *               should not modify the parcel after this call (and
+     *               not call recycle on it.)
+     * @return false if an error occurred.
+     */
+    public boolean parse(Parcel parcel) {
+        if (parcel.dataAvail() < kMetaHeaderSize) {
+            Log.e(TAG, "Not enough data " + parcel.dataAvail());
+            return false;
+        }
+
+        final int pin = parcel.dataPosition();  // to roll back in case of errors.
+        final int size = parcel.readInt();
+
+        // The extra kInt32Size below is to account for the int32 'size' just read.
+        if (parcel.dataAvail() + kInt32Size < size || size < kMetaHeaderSize) {
+            Log.e(TAG, "Bad size " + size + " avail " + parcel.dataAvail() + " position " + pin);
+            parcel.setDataPosition(pin);
+            return false;
+        }
+
+        // Checks if the 'M' 'E' 'T' 'A' marker is present.
+        final int kShouldBeMetaMarker = parcel.readInt();
+        if (kShouldBeMetaMarker != kMetaMarker ) {
+            Log.e(TAG, "Marker missing " + Integer.toHexString(kShouldBeMetaMarker));
+            parcel.setDataPosition(pin);
+            return false;
+        }
+
+        // Scan the records to collect metadata ids and offsets.
+        if (!scanAllRecords(parcel, size - kMetaHeaderSize)) {
+            parcel.setDataPosition(pin);
+            return false;
+        }
+        mParcel = parcel;
+        return true;
+    }
+
+    /**
+     * @return The set of metadata ID found.
+     */
+    public Set<Integer> keySet() {
+        return mKeyToPosMap.keySet();
+    }
+
+    /**
+     * @return true if a value is present for the given key.
+     */
+    public boolean has(final int metadataId) {
+        if (!checkMetadataId(metadataId)) {
+            throw new IllegalArgumentException("Invalid key: " + metadataId);
+        }
+        return mKeyToPosMap.containsKey(metadataId);
+    }
+
+    // Accessors.
+    // Caller must make sure the key is present using the {@code has}
+    // method otherwise a RuntimeException will occur.
+
+    public String getString(final int key) {
+        checkType(key, STRING_VAL);
+        return mParcel.readString();
+    }
+
+    public int getInt(final int key) {
+        checkType(key, INTEGER_VAL);
+        return mParcel.readInt();
+    }
+
+    public boolean getBoolean(final int key) {
+        checkType(key, BOOLEAN_VAL);
+        return mParcel.readInt() == 1;
+    }
+
+    public long getLong(final int key) {
+        checkType(key, LONG_VAL);
+        return mParcel.readLong();
+    }
+
+    public double getDouble(final int key) {
+        checkType(key, DOUBLE_VAL);
+        return mParcel.readDouble();
+    }
+
+    public byte[] getByteArray(final int key) {
+        checkType(key, BYTE_ARRAY_VAL);
+        return mParcel.createByteArray();
+    }
+
+    public Date getDate(final int key) {
+        checkType(key, DATE_VAL);
+        final long timeSinceEpoch = mParcel.readLong();
+        final String timeZone = mParcel.readString();
+
+        if (timeZone.length() == 0) {
+            return new Date(timeSinceEpoch);
+        } else {
+            TimeZone tz = TimeZone.getTimeZone(timeZone);
+            Calendar cal = Calendar.getInstance(tz);
+
+            cal.setTimeInMillis(timeSinceEpoch);
+            return cal.getTime();
+        }
+    }
+
+    public TimedText getTimedText(final int key) {
+        checkType(key, TIMED_TEXT_VAL);
+        final Date startTime = new Date(mParcel.readLong());  // epoch
+        final int duration = mParcel.readInt();  // millisec
+
+        return new TimedText(startTime,
+                             duration,
+                             mParcel.readString());
+    }
+
+    // @return the last available system metadata id. Ids are
+    // 1-indexed.
+    public static int lastSytemId() { return LAST_SYSTEM; }
+
+    // @return the first available cutom metadata id.
+    public static int firstCustomId() { return FIRST_CUSTOM; }
+
+    // @return the last value of known type. Types are 1-indexed.
+    public static int lastType() { return LAST_TYPE; }
+
+    // Check val is either a system id or a custom one.
+    // @param val Metadata key to test.
+    // @return true if it is in a valid range.
+    private boolean checkMetadataId(final int val) {
+        if (val <= ANY || (LAST_SYSTEM < val && val < FIRST_CUSTOM)) {
+            Log.e(TAG, "Invalid metadata ID " + val);
+            return false;
+        }
+        return true;
+    }
+
+    // Check the type of the data match what is expected.
+    private void checkType(final int key, final int expectedType) {
+        final int pos = mKeyToPosMap.get(key);
+
+        mParcel.setDataPosition(pos);
+
+        final int type = mParcel.readInt();
+        if (type != expectedType) {
+            throw new IllegalStateException("Wrong type " + expectedType + " but got " + type);
+        }
+    }
+}
diff --git a/media/java/android/media/RingtoneManager.java b/media/java/android/media/RingtoneManager.java
index 42edae6..44026e4 100644
--- a/media/java/android/media/RingtoneManager.java
+++ b/media/java/android/media/RingtoneManager.java
@@ -122,8 +122,9 @@
      * current ringtone, which will be used to show a checkmark next to the item
      * for this {@link Uri}. If showing an item for "Default" (@see
      * {@link #EXTRA_RINGTONE_SHOW_DEFAULT}), this can also be one of
-     * {@link System#DEFAULT_RINGTONE_URI} or
-     * {@link System#DEFAULT_NOTIFICATION_URI} to have the "Default" item
+     * {@link System#DEFAULT_RINGTONE_URI},
+     * {@link System#DEFAULT_NOTIFICATION_URI}, or
+     * {@link System#DEFAULT_ALARM_ALERT_URI} to have the "Default" item
      * checked.
      * 
      * @see #ACTION_RINGTONE_PICKER
@@ -134,8 +135,9 @@
     /**
      * Given to the ringtone picker as a {@link Uri}. The {@link Uri} of the
      * ringtone to play when the user attempts to preview the "Default"
-     * ringtone. This can be one of {@link System#DEFAULT_RINGTONE_URI} or
-     * {@link System#DEFAULT_NOTIFICATION_URI} to have the "Default" point to
+     * ringtone. This can be one of {@link System#DEFAULT_RINGTONE_URI},
+     * {@link System#DEFAULT_NOTIFICATION_URI}, or
+     * {@link System#DEFAULT_ALARM_ALERT_URI} to have the "Default" point to
      * the current sound for the given default sound type. If you are showing a
      * ringtone picker for some other type of sound, you are free to provide any
      * {@link Uri} here.
@@ -163,8 +165,9 @@
      * <p>
      * It will be one of:
      * <li> the picked ringtone,
-     * <li> a {@link Uri} that equals {@link System#DEFAULT_RINGTONE_URI} or
-     * {@link System#DEFAULT_NOTIFICATION_URI} if the default was chosen,
+     * <li> a {@link Uri} that equals {@link System#DEFAULT_RINGTONE_URI},
+     * {@link System#DEFAULT_NOTIFICATION_URI}, or
+     * {@link System#DEFAULT_ALARM_ALERT_URI} if the default was chosen,
      * <li> null if the "Silent" item was picked.
      * 
      * @see #ACTION_RINGTONE_PICKER
@@ -627,7 +630,8 @@
      * 
      * @param context A context used for querying.
      * @param type The type whose default sound should be returned. One of
-     *            {@link #TYPE_RINGTONE} or {@link #TYPE_NOTIFICATION}.
+     *            {@link #TYPE_RINGTONE}, {@link #TYPE_NOTIFICATION}, or
+     *            {@link #TYPE_ALARM}.
      * @return A {@link Uri} pointing to the default sound for the sound type.
      * @see #setActualDefaultRingtoneUri(Context, int, Uri)
      */
@@ -643,7 +647,8 @@
      * 
      * @param context A context used for querying.
      * @param type The type whose default sound should be set. One of
-     *            {@link #TYPE_RINGTONE} or {@link #TYPE_NOTIFICATION}.
+     *            {@link #TYPE_RINGTONE}, {@link #TYPE_NOTIFICATION}, or
+     *            {@link #TYPE_ALARM}.
      * @param ringtoneUri A {@link Uri} pointing to the default sound to set.
      * @see #getActualDefaultRingtoneUri(Context, int)
      */
@@ -658,6 +663,8 @@
             return Settings.System.RINGTONE;
         } else if ((type & TYPE_NOTIFICATION) != 0) {
             return Settings.System.NOTIFICATION_SOUND;
+        } else if ((type & TYPE_ALARM) != 0) {
+            return Settings.System.ALARM_ALERT;
         } else {
             return null;
         }
@@ -677,8 +684,9 @@
      * Returns the type of a default {@link Uri}.
      * 
      * @param defaultRingtoneUri The default {@link Uri}. For example,
-     *            {@link System#DEFAULT_RINGTONE_URI} or
-     *            {@link System#DEFAULT_NOTIFICATION_URI}.
+     *            {@link System#DEFAULT_RINGTONE_URI},
+     *            {@link System#DEFAULT_NOTIFICATION_URI}, or
+     *            {@link System#DEFAULT_ALARM_ALERT_URI}.
      * @return The type of the defaultRingtoneUri, or -1.
      */
     public static int getDefaultType(Uri defaultRingtoneUri) {
@@ -688,6 +696,8 @@
             return TYPE_RINGTONE;
         } else if (defaultRingtoneUri.equals(Settings.System.DEFAULT_NOTIFICATION_URI)) {
             return TYPE_NOTIFICATION;
+        } else if (defaultRingtoneUri.equals(Settings.System.DEFAULT_ALARM_ALERT_URI)) {
+            return TYPE_ALARM;
         } else {
             return -1;
         }
@@ -707,6 +717,8 @@
             return Settings.System.DEFAULT_RINGTONE_URI;
         } else if ((type & TYPE_NOTIFICATION) != 0) {
             return Settings.System.DEFAULT_NOTIFICATION_URI;
+        } else if ((type & TYPE_ALARM) != 0) {
+            return Settings.System.DEFAULT_ALARM_ALERT_URI;
         } else {
             return null;
         }
diff --git a/media/java/android/media/ToneGenerator.java b/media/java/android/media/ToneGenerator.java
index e5ee9a3..c60a1ac 100644
--- a/media/java/android/media/ToneGenerator.java
+++ b/media/java/android/media/ToneGenerator.java
@@ -724,9 +724,9 @@
     public static final int TONE_CDMA_SIGNAL_OFF = 98;
 
     /** Maximum volume, for use with {@link #ToneGenerator(int,int)} */
-    public static final int MAX_VOLUME = AudioSystem.MAX_VOLUME;
+    public static final int MAX_VOLUME = 100;
     /** Minimum volume setting, for use with {@link #ToneGenerator(int,int)} */
-    public static final int MIN_VOLUME = AudioSystem.MIN_VOLUME;
+    public static final int MIN_VOLUME = 0;
 
 
     /**
diff --git a/media/jni/Android.mk b/media/jni/Android.mk
index 8ee0cbd..1f37111 100644
--- a/media/jni/Android.mk
+++ b/media/jni/Android.mk
@@ -18,14 +18,16 @@
     libnativehelper \
     libcutils \
     libutils \
+    libbinder \
     libmedia \
-    libsgl \
+    libskia \
     libui
 
 LOCAL_STATIC_LIBRARIES :=
 
 LOCAL_C_INCLUDES += \
     external/tremor/Tremor \
+    frameworks/base/core/jni \
     $(PV_INCLUDES) \
     $(JNI_H_INCLUDE) \
     $(call include-path-for, corecg graphics)
diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp
index 6317fe2..d26d039 100644
--- a/media/jni/android_media_MediaPlayer.cpp
+++ b/media/jni/android_media_MediaPlayer.cpp
@@ -20,6 +20,7 @@
 #include "utils/Log.h"
 
 #include <media/mediaplayer.h>
+#include <media/MediaPlayerInterface.h>
 #include <stdio.h>
 #include <assert.h>
 #include <limits.h>
@@ -30,6 +31,8 @@
 #include "JNIHelp.h"
 #include "android_runtime/AndroidRuntime.h"
 #include "utils/Errors.h"  // for status_t
+#include "android_util_Binder.h"
+#include <binder/Parcel.h>
 
 
 // ----------------------------------------------------------------------------
@@ -98,10 +101,9 @@
 
 // ----------------------------------------------------------------------------
 
-static sp<Surface> get_surface(JNIEnv* env, jobject clazz)
+static Surface* get_surface(JNIEnv* env, jobject clazz)
 {
-    Surface* const p = (Surface*)env->GetIntField(clazz, fields.surface_native);
-    return sp<Surface>(p);
+    return (Surface*)env->GetIntField(clazz, fields.surface_native);
 }
 
 static sp<MediaPlayer> getMediaPlayer(JNIEnv* env, jobject thiz)
@@ -202,7 +204,7 @@
 {
     jobject surface = env->GetObjectField(thiz, fields.surface);
     if (surface != NULL) {
-        const sp<Surface>& native_surface = get_surface(env, surface);
+        const sp<Surface> native_surface = get_surface(env, surface);
         LOGV("prepare: surface=%p (id=%d)",
              native_surface.get(), native_surface->ID());
         mp->setVideoSurface(native_surface);
@@ -242,7 +244,7 @@
     }
     jobject surface = env->GetObjectField(thiz, fields.surface);
     if (surface != NULL) {
-        const sp<Surface>& native_surface = get_surface(env, surface);
+        const sp<Surface> native_surface = get_surface(env, surface);
         LOGV("prepareAsync: surface=%p (id=%d)",
              native_surface.get(), native_surface->ID());
         mp->setVideoSurface(native_surface);
@@ -442,6 +444,74 @@
     return NULL;
 }
 
+
+// Sends the request and reply parcels to the media player via the
+// binder interface.
+static jint
+android_media_MediaPlayer_invoke(JNIEnv *env, jobject thiz,
+                                 jobject java_request, jobject java_reply)
+{
+    sp<MediaPlayer> media_player = getMediaPlayer(env, thiz);
+    if (media_player == NULL ) {
+        jniThrowException(env, "java/lang/IllegalStateException", NULL);
+        return UNKNOWN_ERROR;
+    }
+
+
+    Parcel *request = parcelForJavaObject(env, java_request);
+    Parcel *reply = parcelForJavaObject(env, java_reply);
+
+    // Don't use process_media_player_call which use the async loop to
+    // report errors, instead returns the status.
+    return media_player->invoke(*request, reply);
+}
+
+// Sends the new filter to the client.
+static jint
+android_media_MediaPlayer_setMetadataFilter(JNIEnv *env, jobject thiz, jobject request)
+{
+    sp<MediaPlayer> media_player = getMediaPlayer(env, thiz);
+    if (media_player == NULL ) {
+        jniThrowException(env, "java/lang/IllegalStateException", NULL);
+        return UNKNOWN_ERROR;
+    }
+
+    Parcel *filter = parcelForJavaObject(env, request);
+
+    if (filter == NULL ) {
+        jniThrowException(env, "java/lang/RuntimeException", "Filter is null");
+        return UNKNOWN_ERROR;
+    }
+
+    return media_player->setMetadataFilter(*filter);
+}
+
+static jboolean
+android_media_MediaPlayer_getMetadata(JNIEnv *env, jobject thiz, jboolean update_only,
+                                      jboolean apply_filter, jobject reply)
+{
+    sp<MediaPlayer> media_player = getMediaPlayer(env, thiz);
+    if (media_player == NULL ) {
+        jniThrowException(env, "java/lang/IllegalStateException", NULL);
+        return false;
+    }
+
+    Parcel *metadata = parcelForJavaObject(env, reply);
+
+    if (metadata == NULL ) {
+        jniThrowException(env, "java/lang/RuntimeException", "Reply parcel is null");
+        return false;
+    }
+
+    metadata->freeData();
+    // On return metadata is positioned at the beginning of the
+    // metadata. Note however that the parcel actually starts with the
+    // return code so you should not rewind the parcel using
+    // setDataPosition(0).
+    return media_player->getMetadata(update_only, apply_filter, metadata) == OK;
+}
+
+
 static void
 android_media_MediaPlayer_native_setup(JNIEnv *env, jobject thiz, jobject weak_this)
 {
@@ -503,6 +573,9 @@
     {"isLooping",           "()Z",                              (void *)android_media_MediaPlayer_isLooping},
     {"setVolume",           "(FF)V",                            (void *)android_media_MediaPlayer_setVolume},
     {"getFrameAt",          "(I)Landroid/graphics/Bitmap;",     (void *)android_media_MediaPlayer_getFrameAt},
+    {"native_invoke",       "(Landroid/os/Parcel;Landroid/os/Parcel;)I",(void *)android_media_MediaPlayer_invoke},
+    {"native_setMetadataFilter", "(Landroid/os/Parcel;)I",      (void *)android_media_MediaPlayer_setMetadataFilter},
+    {"native_getMetadata", "(ZZLandroid/os/Parcel;)Z",          (void *)android_media_MediaPlayer_getMetadata},
     {"native_setup",        "(Ljava/lang/Object;)V",            (void *)android_media_MediaPlayer_native_setup},
     {"native_finalize",     "()V",                              (void *)android_media_MediaPlayer_native_finalize},
 };
diff --git a/media/jni/soundpool/Android.mk b/media/jni/soundpool/Android.mk
index 374ddeb..9ff2e24 100644
--- a/media/jni/soundpool/Android.mk
+++ b/media/jni/soundpool/Android.mk
@@ -9,6 +9,7 @@
 LOCAL_SHARED_LIBRARIES := \
 	libcutils \
 	libutils \
+	libbinder \
 	libandroid_runtime \
 	libnativehelper \
 	libmedia
diff --git a/media/jni/soundpool/SoundPool.cpp b/media/jni/soundpool/SoundPool.cpp
index 1fdecdd..0d07abe 100644
--- a/media/jni/soundpool/SoundPool.cpp
+++ b/media/jni/soundpool/SoundPool.cpp
@@ -527,13 +527,14 @@
     // wrong audio audio buffer size  (mAudioBufferSize)
     unsigned long toggle = mToggle ^ 1;
     void *userData = (void *)((unsigned long)this | toggle);
+    uint32_t channels = (numChannels == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO;
     
 #ifdef USE_SHARED_MEM_BUFFER
     newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
-            numChannels, sample->getIMemory(), 0, callback, userData);
+            channels, sample->getIMemory(), 0, callback, userData);
 #else
     newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
-            numChannels, frameCount, 0, callback, userData, bufferFrames);
+            channels, frameCount, 0, callback, userData, bufferFrames);
 #endif
     if (newTrack->initCheck() != NO_ERROR) {
         LOGE("Error creating AudioTrack");
diff --git a/media/libdrm/mobile2/include/rights/RoManager.h b/media/libdrm/mobile2/include/rights/RoManager.h
index cf398b3..71e9eef 100644
--- a/media/libdrm/mobile2/include/rights/RoManager.h
+++ b/media/libdrm/mobile2/include/rights/RoManager.h
@@ -64,12 +64,6 @@
     vector<Ro*> getAllRo();
 
     /**
-     * Get the private key of the device.
-     * @return the private key.
-     */
-    const string& getDevicePrivateKey() const;
-
-    /**
      * Get ro which contained rights of specific content.
      * @param contentID the specific id of content.
      * @return NULL if not fount otherwise the related ro.
diff --git a/media/libdrm/mobile2/src/rights/RoManager.cpp b/media/libdrm/mobile2/src/rights/RoManager.cpp
index 848c2ba..a115d21 100644
--- a/media/libdrm/mobile2/src/rights/RoManager.cpp
+++ b/media/libdrm/mobile2/src/rights/RoManager.cpp
@@ -121,9 +121,3 @@
     return true;
 }
 
-/** see RoManager.h */
-const string& RoManager::getDevicePrivateKey() const
-{
-    string pk;
-    return pk;
-}
diff --git a/media/libmedia/Android.mk b/media/libmedia/Android.mk
index 8020da2..9d442c3 100644
--- a/media/libmedia/Android.mk
+++ b/media/libmedia/Android.mk
@@ -2,31 +2,34 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= \
-	AudioTrack.cpp \
-	IAudioFlinger.cpp \
-	IAudioFlingerClient.cpp \
-	IAudioTrack.cpp \
-	IAudioRecord.cpp \
-	AudioRecord.cpp \
-	AudioSystem.cpp \
-	mediaplayer.cpp \
-	IMediaPlayerService.cpp \
-	IMediaPlayerClient.cpp \
-	IMediaPlayer.cpp \
-	IMediaRecorder.cpp \
-	mediarecorder.cpp \
-	IMediaMetadataRetriever.cpp \
-	mediametadataretriever.cpp \
-	ToneGenerator.cpp \
-	JetPlayer.cpp
+    AudioTrack.cpp \
+    IAudioFlinger.cpp \
+    IAudioFlingerClient.cpp \
+    IAudioTrack.cpp \
+    IAudioRecord.cpp \
+    AudioRecord.cpp \
+    AudioSystem.cpp \
+    mediaplayer.cpp \
+    IMediaPlayerService.cpp \
+    IMediaPlayerClient.cpp \
+    IMediaPlayer.cpp \
+    IMediaRecorder.cpp \
+    Metadata.cpp \
+    mediarecorder.cpp \
+    IMediaMetadataRetriever.cpp \
+    mediametadataretriever.cpp \
+    ToneGenerator.cpp \
+    JetPlayer.cpp \
+    IOMX.cpp \
+ 	IAudioPolicyService.cpp
 
 LOCAL_SHARED_LIBRARIES := \
-	libui libcutils libutils libsonivox
+	libui libcutils libutils libbinder libsonivox
 
 LOCAL_MODULE:= libmedia
 
 ifeq ($(TARGET_OS)-$(TARGET_SIMULATOR),linux-true)
-LOCAL_LDLIBS += -ldl
+LOCAL_LDLIBS += -ldl -lpthread
 endif
 
 ifneq ($(TARGET_SIMULATOR),true)
@@ -34,6 +37,7 @@
 endif
 
 LOCAL_C_INCLUDES := \
-	$(call include-path-for, graphics corecg)
+	$(call include-path-for, graphics corecg) \
+        $(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libmedia/AudioRecord.cpp b/media/libmedia/AudioRecord.cpp
index e56efbb..5e35564 100644
--- a/media/libmedia/AudioRecord.cpp
+++ b/media/libmedia/AudioRecord.cpp
@@ -28,12 +28,13 @@
 
 #include <media/AudioSystem.h>
 #include <media/AudioRecord.h>
+#include <media/mediarecorder.h>
 
-#include <utils/IServiceManager.h>
+#include <binder/IServiceManager.h>
 #include <utils/Log.h>
-#include <utils/MemoryDealer.h>
-#include <utils/Parcel.h>
-#include <utils/IPCThreadState.h>
+#include <binder/MemoryDealer.h>
+#include <binder/Parcel.h>
+#include <binder/IPCThreadState.h>
 #include <utils/Timers.h>
 #include <cutils/atomic.h>
 
@@ -45,7 +46,7 @@
 // ---------------------------------------------------------------------------
 
 AudioRecord::AudioRecord()
-    : mStatus(NO_INIT)
+    : mStatus(NO_INIT), mInput(0)
 {
 }
 
@@ -53,15 +54,15 @@
         int inputSource,
         uint32_t sampleRate,
         int format,
-        int channelCount,
+        uint32_t channels,
         int frameCount,
         uint32_t flags,
         callback_t cbf,
         void* user,
         int notificationFrames)
-    : mStatus(NO_INIT)
+    : mStatus(NO_INIT), mInput(0)
 {
-    mStatus = set(inputSource, sampleRate, format, channelCount,
+    mStatus = set(inputSource, sampleRate, format, channels,
             frameCount, flags, cbf, user, notificationFrames);
 }
 
@@ -78,6 +79,7 @@
         }
         mAudioRecord.clear();
         IPCThreadState::self()->flushCommands();
+        AudioSystem::releaseInput(mInput);
     }
 }
 
@@ -85,7 +87,7 @@
         int inputSource,
         uint32_t sampleRate,
         int format,
-        int channelCount,
+        uint32_t channels,
         int frameCount,
         uint32_t flags,
         callback_t cbf,
@@ -94,7 +96,7 @@
         bool threadCanCallJava)
 {
 
-    LOGV("set(): sampleRate %d, channelCount %d, frameCount %d",sampleRate, channelCount, frameCount);
+    LOGV("set(): sampleRate %d, channels %d, frameCount %d",sampleRate, channels, frameCount);
     if (mAudioRecord != 0) {
         return INVALID_OPERATION;
     }
@@ -104,8 +106,8 @@
         return NO_INIT;
     }
 
-    if (inputSource == DEFAULT_INPUT) {
-        inputSource = MIC_INPUT;
+    if (inputSource == AUDIO_SOURCE_DEFAULT) {
+        inputSource = AUDIO_SOURCE_MIC;
     }
 
     if (sampleRate == 0) {
@@ -115,15 +117,21 @@
     if (format == 0) {
         format = AudioSystem::PCM_16_BIT;
     }
-    if (channelCount == 0) {
-        channelCount = 1;
-    }
-
     // validate parameters
-    if (format != AudioSystem::PCM_16_BIT) {
+    if (!AudioSystem::isValidFormat(format)) {
+        LOGE("Invalid format");
         return BAD_VALUE;
     }
-    if (channelCount != 1 && channelCount != 2) {
+
+    if (!AudioSystem::isInputChannel(channels)) {
+        return BAD_VALUE;
+    }
+    int channelCount = AudioSystem::popCount(channels);
+
+    mInput = AudioSystem::getInput(inputSource,
+                                    sampleRate, format, channels, (AudioSystem::audio_in_acoustics)flags);
+    if (mInput == 0) {
+        LOGE("Could not get audio output for stream type %d", inputSource);
         return BAD_VALUE;
     }
 
@@ -132,14 +140,22 @@
     if (AudioSystem::getInputBufferSize(sampleRate, format, channelCount, &inputBuffSizeInBytes)
             != NO_ERROR) {
         LOGE("AudioSystem could not query the input buffer size.");
-        return NO_INIT;    
+        return NO_INIT;
     }
+
     if (inputBuffSizeInBytes == 0) {
         LOGE("Recording parameters are not supported: sampleRate %d, channelCount %d, format %d",
             sampleRate, channelCount, format);
         return BAD_VALUE;
     }
+
     int frameSizeInBytes = channelCount * (format == AudioSystem::PCM_16_BIT ? 2 : 1);
+    if (AudioSystem::isLinearPCM(format)) {
+        frameSizeInBytes = channelCount * (format == AudioSystem::PCM_16_BIT ? sizeof(int16_t) : sizeof(int8_t));
+    } else {
+        frameSizeInBytes = sizeof(int8_t);
+    }
+
 
     // We use 2* size of input buffer for ping pong use of record buffer.
     int minFrameCount = 2 * inputBuffSizeInBytes / frameSizeInBytes;
@@ -157,11 +173,11 @@
 
     // open record channel
     status_t status;
-    sp<IAudioRecord> record = audioFlinger->openRecord(getpid(), inputSource,
+    sp<IAudioRecord> record = audioFlinger->openRecord(getpid(), mInput,
                                                        sampleRate, format,
                                                        channelCount,
                                                        frameCount,
-                                                       ((uint16_t)flags) << 16, 
+                                                       ((uint16_t)flags) << 16,
                                                        &status);
     if (record == 0) {
         LOGE("AudioFlinger could not create record track, status: %d", status);
@@ -188,7 +204,7 @@
     mFormat = format;
     // Update buffer size in case it has been limited by AudioFlinger during track creation
     mFrameCount = mCblk->frameCount;
-    mChannelCount = channelCount;
+    mChannelCount = (uint8_t)channelCount;
     mActive = 0;
     mCbf = cbf;
     mNotificationFrames = notificationFrames;
@@ -234,7 +250,11 @@
 
 int AudioRecord::frameSize() const
 {
-    return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
+    if (AudioSystem::isLinearPCM(mFormat)) {
+        return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
+    } else {
+        return sizeof(uint8_t);
+    }
 }
 
 int AudioRecord::inputSource() const
@@ -262,15 +282,18 @@
      }
 
     if (android_atomic_or(1, &mActive) == 0) {
-        mNewPosition = mCblk->user + mUpdatePeriod;
-        mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
-        mCblk->waitTimeMs = 0;
-        if (t != 0) {
-           t->run("ClientRecordThread", THREAD_PRIORITY_AUDIO_CLIENT);
-        } else {
-            setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
+        ret = AudioSystem::startInput(mInput);
+        if (ret == NO_ERROR) {
+            mNewPosition = mCblk->user + mUpdatePeriod;
+            mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
+            mCblk->waitTimeMs = 0;
+            if (t != 0) {
+               t->run("ClientRecordThread", THREAD_PRIORITY_AUDIO_CLIENT);
+            } else {
+                setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
+            }
+            ret = mAudioRecord->start();
         }
-        ret = mAudioRecord->start();
     }
 
     if (t != 0) {
@@ -301,6 +324,7 @@
         } else {
             setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
         }
+        AudioSystem::stopInput(mInput);
     }
 
     if (t != 0) {
@@ -421,7 +445,7 @@
         "this shouldn't happen (user=%08x, server=%08x)", cblk->user, cblk->server);
 
     cblk->waitTimeMs = 0;
-    
+
     if (framesReq > framesReady) {
         framesReq = framesReady;
     }
@@ -437,7 +461,7 @@
     audioBuffer->channelCount= mChannelCount;
     audioBuffer->format      = mFormat;
     audioBuffer->frameCount  = framesReq;
-    audioBuffer->size        = framesReq*mChannelCount*sizeof(int16_t);
+    audioBuffer->size        = framesReq*cblk->frameSize;
     audioBuffer->raw         = (int8_t*)cblk->buffer(u);
     active = mActive;
     return active ? status_t(NO_ERROR) : status_t(STOPPED);
@@ -468,7 +492,7 @@
 
     do {
 
-        audioBuffer.frameCount = userSize/mChannelCount/sizeof(int16_t);
+        audioBuffer.frameCount = userSize/frameSize();
 
         // Calling obtainBuffer() with a negative wait count causes
         // an (almost) infinite wait time.
@@ -519,8 +543,8 @@
 
     do {
         audioBuffer.frameCount = frames;
-        // Calling obtainBuffer() with a wait count of 1 
-        // limits wait time to WAIT_PERIOD_MS. This prevents from being 
+        // Calling obtainBuffer() with a wait count of 1
+        // limits wait time to WAIT_PERIOD_MS. This prevents from being
         // stuck here not being able to handle timed events (position, markers).
         status_t err = obtainBuffer(&audioBuffer, 1);
         if (err < NO_ERROR) {
@@ -548,14 +572,14 @@
         if (readSize > reqSize) readSize = reqSize;
 
         audioBuffer.size = readSize;
-        audioBuffer.frameCount = readSize/mChannelCount/sizeof(int16_t);
+        audioBuffer.frameCount = readSize/frameSize();
         frames -= audioBuffer.frameCount;
 
         releaseBuffer(&audioBuffer);
 
     } while (frames);
 
-    
+
     // Manage overrun callback
     if (mActive && (mCblk->framesAvailable_l() == 0)) {
         LOGV("Overrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag);
diff --git a/media/libmedia/AudioSystem.cpp b/media/libmedia/AudioSystem.cpp
index a21a7a4..1fc1024 100644
--- a/media/libmedia/AudioSystem.cpp
+++ b/media/libmedia/AudioSystem.cpp
@@ -18,10 +18,20 @@
 //#define LOG_NDEBUG 0
 
 #include <utils/Log.h>
-#include <utils/IServiceManager.h>
+#include <binder/IServiceManager.h>
 #include <media/AudioSystem.h>
+#include <media/IAudioPolicyService.h>
 #include <math.h>
 
+// ----------------------------------------------------------------------------
+// the sim build doesn't have gettid
+
+#ifndef HAVE_GETTID
+# define gettid getpid
+#endif
+
+// ----------------------------------------------------------------------------
+
 namespace android {
 
 // client singleton for AudioFlinger binder interface
@@ -30,10 +40,9 @@
 sp<AudioSystem::AudioFlingerClient> AudioSystem::gAudioFlingerClient;
 audio_error_callback AudioSystem::gAudioErrorCallback = NULL;
 // Cached values
-int AudioSystem::gOutSamplingRate[NUM_AUDIO_OUTPUT_TYPES];
-int AudioSystem::gOutFrameCount[NUM_AUDIO_OUTPUT_TYPES];
-uint32_t AudioSystem::gOutLatency[NUM_AUDIO_OUTPUT_TYPES];
-bool AudioSystem::gA2dpEnabled;
+DefaultKeyedVector<int, audio_io_handle_t> AudioSystem::gStreamOutputMap(0);
+DefaultKeyedVector<audio_io_handle_t, AudioSystem::OutputDescriptor *> AudioSystem::gOutputs(0);
+
 // Cached values for recording queries
 uint32_t AudioSystem::gPrevInSamplingRate = 16000;
 int AudioSystem::gPrevInFormat = AudioSystem::PCM_16_BIT;
@@ -65,44 +74,12 @@
         binder->linkToDeath(gAudioFlingerClient);
         gAudioFlinger = interface_cast<IAudioFlinger>(binder);
         gAudioFlinger->registerClient(gAudioFlingerClient);
-        // Cache frequently accessed parameters 
-        for (int output = 0; output < NUM_AUDIO_OUTPUT_TYPES; output++) {
-            gOutFrameCount[output] = (int)gAudioFlinger->frameCount(output);
-            gOutSamplingRate[output] = (int)gAudioFlinger->sampleRate(output);
-            gOutLatency[output] = gAudioFlinger->latency(output);
-        }
-        gA2dpEnabled = gAudioFlinger->isA2dpEnabled();
     }
     LOGE_IF(gAudioFlinger==0, "no AudioFlinger!?");
+
     return gAudioFlinger;
 }
 
-// routing helper functions
-status_t AudioSystem::speakerphone(bool state) {
-    uint32_t routes = state ? ROUTE_SPEAKER : ROUTE_EARPIECE;
-    return setRouting(MODE_IN_CALL, routes, ROUTE_ALL);
-}
-
-status_t AudioSystem::isSpeakerphoneOn(bool* state) {
-    uint32_t routes = 0;
-    status_t s = getRouting(MODE_IN_CALL, &routes);
-    *state = !!(routes & ROUTE_SPEAKER);
-    return s;
-}
-
-status_t AudioSystem::bluetoothSco(bool state) {
-    uint32_t mask = ROUTE_BLUETOOTH_SCO;
-    uint32_t routes = state ? mask : ROUTE_EARPIECE;
-    return setRouting(MODE_IN_CALL, routes, ROUTE_ALL);
-}
-
-status_t AudioSystem::isBluetoothScoOn(bool* state) {
-    uint32_t routes = 0;
-    status_t s = getRouting(MODE_IN_CALL, &routes);
-    *state = !!(routes & ROUTE_BLUETOOTH_SCO);
-    return s;
-}
-
 status_t AudioSystem::muteMicrophone(bool state) {
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     if (af == 0) return PERMISSION_DENIED;
@@ -148,12 +125,12 @@
     return NO_ERROR;
 }
 
-status_t AudioSystem::setStreamVolume(int stream, float value)
+status_t AudioSystem::setStreamVolume(int stream, float value, void *output)
 {
     if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE;
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     if (af == 0) return PERMISSION_DENIED;
-    af->setStreamVolume(stream, value);
+    af->setStreamVolume(stream, value, output);
     return NO_ERROR;
 }
 
@@ -166,12 +143,12 @@
     return NO_ERROR;
 }
 
-status_t AudioSystem::getStreamVolume(int stream, float* volume)
+status_t AudioSystem::getStreamVolume(int stream, float* volume, void *output)
 {
     if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE;
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     if (af == 0) return PERMISSION_DENIED;
-    *volume = af->streamVolume(stream);
+    *volume = af->streamVolume(stream, output);
     return NO_ERROR;
 }
 
@@ -192,29 +169,6 @@
     return af->setMode(mode);
 }
 
-status_t AudioSystem::getMode(int* mode)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    *mode = af->getMode();
-    return NO_ERROR;
-}
-
-status_t AudioSystem::setRouting(int mode, uint32_t routes, uint32_t mask)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    return af->setRouting(mode, routes, mask);
-}
-
-status_t AudioSystem::getRouting(int mode, uint32_t* routes)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    uint32_t r = af->getRouting(mode);
-    *routes = r;
-    return NO_ERROR;
-}
 
 status_t AudioSystem::isMusicActive(bool* state) {
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
@@ -223,12 +177,20 @@
     return NO_ERROR;
 }
 
-// Temporary interface, do not use
-// TODO: Replace with a more generic key:value get/set mechanism
-status_t AudioSystem::setParameter(const char* key, const char* value) {
+
+status_t AudioSystem::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) {
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     if (af == 0) return PERMISSION_DENIED;
-    return af->setParameter(key, value);
+    return af->setParameters(ioHandle, keyValuePairs);
+}
+
+String8 AudioSystem::getParameters(audio_io_handle_t ioHandle, const String8& keys) {
+    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
+    String8 result = String8("");
+    if (af == 0) return result;
+
+    result = af->getParameters(ioHandle, keys);
+    return result;
 }
 
 // convert volume steps to natural log scale
@@ -257,55 +219,108 @@
 
 status_t AudioSystem::getOutputSamplingRate(int* samplingRate, int streamType)
 {
-    int output = getOutput(streamType);
-    
-    if (output == NUM_AUDIO_OUTPUT_TYPES) return PERMISSION_DENIED;
+    OutputDescriptor *outputDesc;
+    audio_io_handle_t output;
 
-    // gOutSamplingRate[] is updated by getOutput() which calls get_audio_flinger()
-    LOGV("getOutputSamplingRate() streamType %d, output %d, sampling rate %d", streamType, output, gOutSamplingRate[output]);
-    
-    *samplingRate = gOutSamplingRate[output];
-    
+    if (streamType == DEFAULT) {
+        streamType = MUSIC;
+    }
+
+    output = getOutput((stream_type)streamType);
+    if (output == 0) {
+        return PERMISSION_DENIED;
+    }
+
+    gLock.lock();
+    outputDesc = AudioSystem::gOutputs.valueFor(output);
+    if (outputDesc == 0) {
+        LOGV("getOutputSamplingRate() no output descriptor for output %p in gOutputs", output);
+        gLock.unlock();
+        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
+        if (af == 0) return PERMISSION_DENIED;
+        *samplingRate = af->sampleRate(output);
+    } else {
+        LOGV("getOutputSamplingRate() reading from output desc");
+        *samplingRate = outputDesc->samplingRate;
+        gLock.unlock();
+    }
+
+    LOGV("getOutputSamplingRate() streamType %d, output %p, sampling rate %d", streamType, output, *samplingRate);
+
     return NO_ERROR;
 }
 
 status_t AudioSystem::getOutputFrameCount(int* frameCount, int streamType)
 {
-    int output = getOutput(streamType);
+    OutputDescriptor *outputDesc;
+    audio_io_handle_t output;
 
-    if (output == NUM_AUDIO_OUTPUT_TYPES) return PERMISSION_DENIED;
+    if (streamType == DEFAULT) {
+        streamType = MUSIC;
+    }
 
-    // gOutFrameCount[] is updated by getOutput() which calls get_audio_flinger()
-    LOGV("getOutputFrameCount() streamType %d, output %d, frame count %d", streamType, output, gOutFrameCount[output]);
+    output = getOutput((stream_type)streamType);
+    if (output == 0) {
+        return PERMISSION_DENIED;
+    }
 
-    *frameCount = gOutFrameCount[output];
-    
+    gLock.lock();
+    outputDesc = AudioSystem::gOutputs.valueFor(output);
+    if (outputDesc == 0) {
+        gLock.unlock();
+        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
+        if (af == 0) return PERMISSION_DENIED;
+        *frameCount = af->frameCount(output);
+    } else {
+        *frameCount = outputDesc->frameCount;
+        gLock.unlock();
+    }
+
+    LOGV("getOutputFrameCount() streamType %d, output %p, frameCount %d", streamType, output, *frameCount);
+
     return NO_ERROR;
 }
 
 status_t AudioSystem::getOutputLatency(uint32_t* latency, int streamType)
 {
-    int output = getOutput(streamType);
+    OutputDescriptor *outputDesc;
+    audio_io_handle_t output;
 
-    if (output == NUM_AUDIO_OUTPUT_TYPES) return PERMISSION_DENIED;
+    if (streamType == DEFAULT) {
+        streamType = MUSIC;
+    }
 
-    // gOutLatency[] is updated by getOutput() which calls get_audio_flinger()
-    LOGV("getOutputLatency() streamType %d, output %d, latency %d", streamType, output, gOutLatency[output]);
+    output = getOutput((stream_type)streamType);
+    if (output == 0) {
+        return PERMISSION_DENIED;
+    }
 
-    *latency = gOutLatency[output];
-    
+    gLock.lock();
+    outputDesc = AudioSystem::gOutputs.valueFor(output);
+    if (outputDesc == 0) {
+        gLock.unlock();
+        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
+        if (af == 0) return PERMISSION_DENIED;
+        *latency = af->latency(output);
+    } else {
+        *latency = outputDesc->latency;
+        gLock.unlock();
+    }
+
+    LOGV("getOutputLatency() streamType %d, output %p, latency %d", streamType, output, *latency);
+
     return NO_ERROR;
 }
 
-status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, int format, int channelCount, 
+status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, int format, int channelCount,
     size_t* buffSize)
 {
     // Do we have a stale gInBufferSize or are we requesting the input buffer size for new values
-    if ((gInBuffSize == 0) || (sampleRate != gPrevInSamplingRate) || (format != gPrevInFormat) 
+    if ((gInBuffSize == 0) || (sampleRate != gPrevInSamplingRate) || (format != gPrevInFormat)
         || (channelCount != gPrevInChannelCount)) {
         // save the request params
         gPrevInSamplingRate = sampleRate;
-        gPrevInFormat = format; 
+        gPrevInFormat = format;
         gPrevInChannelCount = channelCount;
 
         gInBuffSize = 0;
@@ -314,24 +329,18 @@
             return PERMISSION_DENIED;
         }
         gInBuffSize = af->getInputBufferSize(sampleRate, format, channelCount);
-    } 
+    }
     *buffSize = gInBuffSize;
-    
+
     return NO_ERROR;
 }
 
 // ---------------------------------------------------------------------------
 
-void AudioSystem::AudioFlingerClient::binderDied(const wp<IBinder>& who) {   
+void AudioSystem::AudioFlingerClient::binderDied(const wp<IBinder>& who) {
     Mutex::Autolock _l(AudioSystem::gLock);
-    AudioSystem::gAudioFlinger.clear();
 
-    for (int output = 0; output < NUM_AUDIO_OUTPUT_TYPES; output++) {
-        gOutFrameCount[output] = 0;
-        gOutSamplingRate[output] = 0;
-        gOutLatency[output] = 0;
-    }
-    AudioSystem::gInBuffSize = 0;
+    AudioSystem::gAudioFlinger.clear();
 
     if (gAudioErrorCallback) {
         gAudioErrorCallback(DEAD_OBJECT);
@@ -339,33 +348,83 @@
     LOGW("AudioFlinger server died!");
 }
 
-void AudioSystem::AudioFlingerClient::a2dpEnabledChanged(bool enabled) {
-    gA2dpEnabled = enabled;        
-    LOGV("AudioFlinger A2DP enabled status changed! %d", enabled);
+void AudioSystem::AudioFlingerClient::ioConfigChanged(int event, void *param1, void *param2) {
+    LOGV("ioConfigChanged() event %d", event);
+    audio_io_handle_t ioHandle = (audio_io_handle_t)param1;
+    OutputDescriptor *desc;
+    uint32_t stream;
+
+    if (param1 == 0) return;
+
+    Mutex::Autolock _l(AudioSystem::gLock);
+
+    switch (event) {
+    case STREAM_CONFIG_CHANGED:
+        if (param2 == 0) break;
+        stream = *(uint32_t *)param2;
+        LOGV("ioConfigChanged() STREAM_CONFIG_CHANGED stream %d, output %p", stream, ioHandle);
+        if (gStreamOutputMap.indexOfKey(stream) >= 0) {
+            gStreamOutputMap.replaceValueFor(stream, ioHandle);
+        }
+        break;
+    case OUTPUT_OPENED: {
+        if (gOutputs.indexOfKey(ioHandle) >= 0) {
+            LOGV("ioConfigChanged() opening already existing output! %p", ioHandle);
+            break;
+        }
+        if (param2 == 0) break;
+        desc = (OutputDescriptor *)param2;
+
+        OutputDescriptor *outputDesc =  new OutputDescriptor(*desc);
+        gOutputs.add(ioHandle, outputDesc);
+        LOGV("ioConfigChanged() new output samplingRate %d, format %d channels %d frameCount %d latency %d",
+                outputDesc->samplingRate, outputDesc->format, outputDesc->channels, outputDesc->frameCount, outputDesc->latency);
+        } break;
+    case OUTPUT_CLOSED: {
+        if (gOutputs.indexOfKey(ioHandle) < 0) {
+            LOGW("ioConfigChanged() closing unknow output! %p", ioHandle);
+            break;
+        }
+        LOGV("ioConfigChanged() output %p closed", ioHandle);
+
+        gOutputs.removeItem(ioHandle);
+        for (int i = gStreamOutputMap.size() - 1; i >= 0 ; i--) {
+            if (gStreamOutputMap.valueAt(i) == ioHandle) {
+                gStreamOutputMap.removeItemsAt(i);
+            }
+        }
+        } break;
+
+    case OUTPUT_CONFIG_CHANGED: {
+        int index = gOutputs.indexOfKey(ioHandle);
+        if (index < 0) {
+            LOGW("ioConfigChanged() modifying unknow output! %p", ioHandle);
+            break;
+        }
+        if (param2 == 0) break;
+        desc = (OutputDescriptor *)param2;
+
+        LOGV("ioConfigChanged() new config for output %p samplingRate %d, format %d channels %d frameCount %d latency %d",
+                ioHandle, desc->samplingRate, desc->format,
+                desc->channels, desc->frameCount, desc->latency);
+        OutputDescriptor *outputDesc = gOutputs.valueAt(index);
+        delete outputDesc;
+        outputDesc =  new OutputDescriptor(*desc);
+        gOutputs.replaceValueFor(ioHandle, outputDesc);
+    } break;
+    case INPUT_OPENED:
+    case INPUT_CLOSED:
+    case INPUT_CONFIG_CHANGED:
+        break;
+
+    }
 }
 
 void AudioSystem::setErrorCallback(audio_error_callback cb) {
-    Mutex::Autolock _l(AudioSystem::gLock);
+    Mutex::Autolock _l(gLock);
     gAudioErrorCallback = cb;
 }
 
-int AudioSystem::getOutput(int streamType)
-{   
-    // make sure that gA2dpEnabled is valid by calling get_audio_flinger() which in turn 
-    // will call gAudioFlinger->isA2dpEnabled()
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return NUM_AUDIO_OUTPUT_TYPES;
-
-    if (streamType == DEFAULT) {
-        streamType = MUSIC;
-    }
-    if (gA2dpEnabled && routedToA2dpOutput(streamType)) {
-        return AUDIO_OUTPUT_A2DP;
-    } else {
-        return AUDIO_OUTPUT_HARDWARE;
-    }
-}
-
 bool AudioSystem::routedToA2dpOutput(int streamType) {
     switch(streamType) {
     case MUSIC:
@@ -379,6 +438,451 @@
 }
 
 
+// client singleton for AudioPolicyService binder interface
+sp<IAudioPolicyService> AudioSystem::gAudioPolicyService;
+sp<AudioSystem::AudioPolicyServiceClient> AudioSystem::gAudioPolicyServiceClient;
+
+
+// establish binder interface to AudioFlinger service
+const sp<IAudioPolicyService>& AudioSystem::get_audio_policy_service()
+{
+    gLock.lock();
+    if (gAudioPolicyService.get() == 0) {
+        sp<IServiceManager> sm = defaultServiceManager();
+        sp<IBinder> binder;
+        do {
+            binder = sm->getService(String16("media.audio_policy"));
+            if (binder != 0)
+                break;
+            LOGW("AudioPolicyService not published, waiting...");
+            usleep(500000); // 0.5 s
+        } while(true);
+        if (gAudioPolicyServiceClient == NULL) {
+            gAudioPolicyServiceClient = new AudioPolicyServiceClient();
+        }
+        binder->linkToDeath(gAudioPolicyServiceClient);
+        gAudioPolicyService = interface_cast<IAudioPolicyService>(binder);
+        gLock.unlock();
+    } else {
+        gLock.unlock();
+    }
+    return gAudioPolicyService;
+}
+
+status_t AudioSystem::setDeviceConnectionState(audio_devices device,
+                                                  device_connection_state state,
+                                                  const char *device_address)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+
+    return aps->setDeviceConnectionState(device, state, device_address);
+}
+
+AudioSystem::device_connection_state AudioSystem::getDeviceConnectionState(audio_devices device,
+                                                  const char *device_address)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return DEVICE_STATE_UNAVAILABLE;
+
+    return aps->getDeviceConnectionState(device, device_address);
+}
+
+status_t AudioSystem::setPhoneState(int state)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+
+    return aps->setPhoneState(state);
+}
+
+status_t AudioSystem::setRingerMode(uint32_t mode, uint32_t mask)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+    return aps->setRingerMode(mode, mask);
+}
+
+status_t AudioSystem::setForceUse(force_use usage, forced_config config)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+    return aps->setForceUse(usage, config);
+}
+
+AudioSystem::forced_config AudioSystem::getForceUse(force_use usage)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return FORCE_NONE;
+    return aps->getForceUse(usage);
+}
+
+
+audio_io_handle_t AudioSystem::getOutput(stream_type stream,
+                                    uint32_t samplingRate,
+                                    uint32_t format,
+                                    uint32_t channels,
+                                    output_flags flags)
+{
+    audio_io_handle_t output = NULL;
+    if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) == 0) {
+        Mutex::Autolock _l(gLock);
+        output = AudioSystem::gStreamOutputMap.valueFor(stream);
+        LOGV_IF((output != NULL), "getOutput() read %p from cache for stream %d", output, stream);
+    }
+    if (output == NULL) {
+        const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+        if (aps == 0) return NULL;
+        output = aps->getOutput(stream, samplingRate, format, channels, flags);
+        if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) == 0) {
+            Mutex::Autolock _l(gLock);
+            AudioSystem::gStreamOutputMap.add(stream, output);
+        }
+    }
+    return output;
+}
+
+status_t AudioSystem::startOutput(audio_io_handle_t output, AudioSystem::stream_type stream)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+    return aps->startOutput(output, stream);
+}
+
+status_t AudioSystem::stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+    return aps->stopOutput(output, stream);
+}
+
+void AudioSystem::releaseOutput(audio_io_handle_t output)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return;
+    aps->releaseOutput(output);
+}
+
+audio_io_handle_t AudioSystem::getInput(int inputSource,
+                                    uint32_t samplingRate,
+                                    uint32_t format,
+                                    uint32_t channels,
+                                    audio_in_acoustics acoustics)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return NULL;
+    return aps->getInput(inputSource, samplingRate, format, channels, acoustics);
+}
+
+status_t AudioSystem::startInput(audio_io_handle_t input)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+    return aps->startInput(input);
+}
+
+status_t AudioSystem::stopInput(audio_io_handle_t input)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+    return aps->stopInput(input);
+}
+
+void AudioSystem::releaseInput(audio_io_handle_t input)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return;
+    aps->releaseInput(input);
+}
+
+status_t AudioSystem::initStreamVolume(stream_type stream,
+                                    int indexMin,
+                                    int indexMax)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+    return aps->initStreamVolume(stream, indexMin, indexMax);
+}
+
+status_t AudioSystem::setStreamVolumeIndex(stream_type stream, int index)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+    return aps->setStreamVolumeIndex(stream, index);
+}
+
+status_t AudioSystem::getStreamVolumeIndex(stream_type stream, int *index)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) return PERMISSION_DENIED;
+    return aps->getStreamVolumeIndex(stream, index);
+}
+
+// ---------------------------------------------------------------------------
+
+void AudioSystem::AudioPolicyServiceClient::binderDied(const wp<IBinder>& who) {
+    Mutex::Autolock _l(AudioSystem::gLock);
+    AudioSystem::gAudioPolicyService.clear();
+
+    LOGW("AudioPolicyService server died!");
+}
+
+// ---------------------------------------------------------------------------
+
+
+// use emulated popcount optimization
+// http://www.df.lth.se/~john_e/gems/gem002d.html
+uint32_t AudioSystem::popCount(uint32_t u)
+{
+    u = ((u&0x55555555) + ((u>>1)&0x55555555));
+    u = ((u&0x33333333) + ((u>>2)&0x33333333));
+    u = ((u&0x0f0f0f0f) + ((u>>4)&0x0f0f0f0f));
+    u = ((u&0x00ff00ff) + ((u>>8)&0x00ff00ff));
+    u = ( u&0x0000ffff) + (u>>16);
+    return u;
+}
+
+bool AudioSystem::isOutputDevice(audio_devices device)
+{
+    if ((popCount(device) == 1 ) &&
+        ((device & ~AudioSystem::DEVICE_OUT_ALL) == 0)) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+bool AudioSystem::isInputDevice(audio_devices device)
+{
+    if ((popCount(device) == 1 ) &&
+        ((device & ~AudioSystem::DEVICE_IN_ALL) == 0)) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+bool AudioSystem::isA2dpDevice(audio_devices device)
+{
+    if ((popCount(device) == 1 ) &&
+        (device & (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
+                   AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
+                   AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER))) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+bool AudioSystem::isBluetoothScoDevice(audio_devices device)
+{
+    if ((popCount(device) == 1 ) &&
+        (device & (AudioSystem::DEVICE_OUT_BLUETOOTH_SCO |
+                   AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
+                   AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT))) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+bool AudioSystem::isLowVisibility(stream_type stream)
+{
+    if (stream == AudioSystem::SYSTEM || stream == AudioSystem::NOTIFICATION) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+bool AudioSystem::isInputChannel(uint32_t channel)
+{
+    if ((channel & ~AudioSystem::CHANNEL_IN_ALL) == 0) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+bool AudioSystem::isOutputChannel(uint32_t channel)
+{
+    if ((channel & ~AudioSystem::CHANNEL_OUT_ALL) == 0) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+bool AudioSystem::isValidFormat(uint32_t format)
+{
+    switch (format & MAIN_FORMAT_MASK) {
+    case         PCM:
+    case         MP3:
+    case         AMR_NB:
+    case         AMR_WB:
+    case         AAC:
+    case         HE_AAC_V1:
+    case         HE_AAC_V2:
+    case         VORBIS:
+        return true;
+    default:
+        return false;
+    }
+}
+
+bool AudioSystem::isLinearPCM(uint32_t format)
+{
+    switch (format) {
+    case         PCM_16_BIT:
+    case         PCM_8_BIT:
+        return true;
+    default:
+        return false;
+    }
+}
+
+//------------------------- AudioParameter class implementation ---------------
+
+const char *AudioParameter::keyRouting = "routing";
+const char *AudioParameter::keySamplingRate = "sampling_rate";
+const char *AudioParameter::keyFormat = "format";
+const char *AudioParameter::keyChannels = "channels";
+const char *AudioParameter::keyFrameCount = "frame_count";
+
+AudioParameter::AudioParameter(const String8& keyValuePairs)
+{
+    char *str = new char[keyValuePairs.length()+1];
+    mKeyValuePairs = keyValuePairs;
+
+    strcpy(str, keyValuePairs.string());
+    char *pair = strtok(str, ";");
+    while (pair != NULL) {
+        if (strlen(pair) != 0) {
+            size_t eqIdx = strcspn(pair, "=");
+            String8 key = String8(pair, eqIdx);
+            String8 value;
+            if (eqIdx == strlen(pair)) {
+                value = String8("");
+            } else {
+                value = String8(pair + eqIdx + 1);
+            }
+            if (mParameters.indexOfKey(key) < 0) {
+                mParameters.add(key, value);
+            } else {
+                mParameters.replaceValueFor(key, value);
+            }
+        } else {
+            LOGV("AudioParameter() cstor empty key value pair");
+        }
+        pair = strtok(NULL, ";");
+    }
+
+    delete[] str;
+}
+
+AudioParameter::~AudioParameter()
+{
+    mParameters.clear();
+}
+
+String8 AudioParameter::toString()
+{
+    String8 str = String8("");
+
+    size_t size = mParameters.size();
+    for (size_t i = 0; i < size; i++) {
+        str += mParameters.keyAt(i);
+        str += "=";
+        str += mParameters.valueAt(i);
+        if (i < (size - 1)) str += ";";
+    }
+    return str;
+}
+
+status_t AudioParameter::add(const String8& key, const String8& value)
+{
+    if (mParameters.indexOfKey(key) < 0) {
+        mParameters.add(key, value);
+        return NO_ERROR;
+    } else {
+        mParameters.replaceValueFor(key, value);
+        return ALREADY_EXISTS;
+    }
+}
+
+status_t AudioParameter::addInt(const String8& key, const int value)
+{
+    char str[12];
+    if (snprintf(str, 12, "%d", value) > 0) {
+        String8 str8 = String8(str);
+        return add(key, str8);
+    } else {
+        return BAD_VALUE;
+    }
+}
+
+status_t AudioParameter::addFloat(const String8& key, const float value)
+{
+    char str[23];
+    if (snprintf(str, 23, "%.10f", value) > 0) {
+        String8 str8 = String8(str);
+        return add(key, str8);
+    } else {
+        return BAD_VALUE;
+    }
+}
+
+status_t AudioParameter::remove(const String8& key)
+{
+    if (mParameters.indexOfKey(key) >= 0) {
+        mParameters.removeItem(key);
+        return NO_ERROR;
+    } else {
+        return BAD_VALUE;
+    }
+}
+
+status_t AudioParameter::get(const String8& key, String8& value)
+{
+    if (mParameters.indexOfKey(key) >= 0) {
+        value = mParameters.valueFor(key);
+        return NO_ERROR;
+    } else {
+        return BAD_VALUE;
+    }
+}
+
+status_t AudioParameter::getInt(const String8& key, int& value)
+{
+    String8 str8;
+    status_t result = get(key, str8);
+    value = 0;
+    if (result == NO_ERROR) {
+        int val;
+        if (sscanf(str8.string(), "%d", &val) == 1) {
+            value = val;
+        } else {
+            result = INVALID_OPERATION;
+        }
+    }
+    return result;
+}
+
+status_t AudioParameter::getFloat(const String8& key, float& value)
+{
+    String8 str8;
+    status_t result = get(key, str8);
+    value = 0;
+    if (result == NO_ERROR) {
+        float val;
+        if (sscanf(str8.string(), "%f", &val) == 1) {
+            value = val;
+        } else {
+            result = INVALID_OPERATION;
+        }
+    }
+    return result;
+}
 
 }; // namespace android
 
diff --git a/media/libmedia/AudioTrack.cpp b/media/libmedia/AudioTrack.cpp
index b2c067b..b147d25 100644
--- a/media/libmedia/AudioTrack.cpp
+++ b/media/libmedia/AudioTrack.cpp
@@ -32,9 +32,9 @@
 #include <media/AudioTrack.h>
 
 #include <utils/Log.h>
-#include <utils/MemoryDealer.h>
-#include <utils/Parcel.h>
-#include <utils/IPCThreadState.h>
+#include <binder/MemoryDealer.h>
+#include <binder/Parcel.h>
+#include <binder/IPCThreadState.h>
 #include <utils/Timers.h>
 #include <cutils/atomic.h>
 
@@ -54,7 +54,7 @@
         int streamType,
         uint32_t sampleRate,
         int format,
-        int channelCount,
+        int channels,
         int frameCount,
         uint32_t flags,
         callback_t cbf,
@@ -62,7 +62,7 @@
         int notificationFrames)
     : mStatus(NO_INIT)
 {
-    mStatus = set(streamType, sampleRate, format, channelCount,
+    mStatus = set(streamType, sampleRate, format, channels,
             frameCount, flags, cbf, user, notificationFrames, 0);
 }
 
@@ -70,7 +70,7 @@
         int streamType,
         uint32_t sampleRate,
         int format,
-        int channelCount,
+        int channels,
         const sp<IMemory>& sharedBuffer,
         uint32_t flags,
         callback_t cbf,
@@ -78,7 +78,7 @@
         int notificationFrames)
     : mStatus(NO_INIT)
 {
-    mStatus = set(streamType, sampleRate, format, channelCount,
+    mStatus = set(streamType, sampleRate, format, channels,
             0, flags, cbf, user, notificationFrames, sharedBuffer);
 }
 
@@ -97,6 +97,7 @@
         }
         mAudioTrack.clear();
         IPCThreadState::self()->flushCommands();
+        AudioSystem::releaseOutput(getOutput());
     }
 }
 
@@ -104,7 +105,7 @@
         int streamType,
         uint32_t sampleRate,
         int format,
-        int channelCount,
+        int channels,
         int frameCount,
         uint32_t flags,
         callback_t cbf,
@@ -150,63 +151,84 @@
     if (format == 0) {
         format = AudioSystem::PCM_16_BIT;
     }
-    if (channelCount == 0) {
-        channelCount = 2;
+    if (channels == 0) {
+        channels = AudioSystem::CHANNEL_OUT_STEREO;
     }
 
     // validate parameters
-    if (((format != AudioSystem::PCM_8_BIT) || sharedBuffer != 0) &&
-        (format != AudioSystem::PCM_16_BIT)) {
+    if (!AudioSystem::isValidFormat(format)) {
         LOGE("Invalid format");
         return BAD_VALUE;
     }
-    if (channelCount != 1 && channelCount != 2) {
-        LOGE("Invalid channel number");
+
+    // force direct flag if format is not linear PCM
+    if (!AudioSystem::isLinearPCM(format)) {
+        flags |= AudioSystem::OUTPUT_FLAG_DIRECT;
+    }
+
+    if (!AudioSystem::isOutputChannel(channels)) {
+        LOGE("Invalid channel mask");
+        return BAD_VALUE;
+    }
+    uint32_t channelCount = AudioSystem::popCount(channels);
+
+    audio_io_handle_t output = AudioSystem::getOutput((AudioSystem::stream_type)streamType,
+            sampleRate, format, channels, (AudioSystem::output_flags)flags);
+
+    if (output == 0) {
+        LOGE("Could not get audio output for stream type %d", streamType);
         return BAD_VALUE;
     }
 
-    // Ensure that buffer depth covers at least audio hardware latency
-    uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
-    if (minBufCount < 2) minBufCount = 2;
-
-    // When playing from shared buffer, playback will start even if last audioflinger
-    // block is partly filled.
-    if (sharedBuffer != 0 && minBufCount > 1) {
-        minBufCount--;
-    }
-
-    int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
-
-    if (sharedBuffer == 0) {
-        if (frameCount == 0) {
-            frameCount = minFrameCount;
-        }
-        if (notificationFrames == 0) {
-            notificationFrames = frameCount/2;
-        }
-        // Make sure that application is notified with sufficient margin
-        // before underrun
-        if (notificationFrames > frameCount/2) {
-            notificationFrames = frameCount/2;
+    if (!AudioSystem::isLinearPCM(format)) {
+        if (sharedBuffer != 0) {
+            frameCount = sharedBuffer->size();
         }
     } else {
-        // Ensure that buffer alignment matches channelcount
-        if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
-            LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
-            return BAD_VALUE;
-        }
-        frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
-    }
+        // Ensure that buffer depth covers at least audio hardware latency
+        uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
+        if (minBufCount < 2) minBufCount = 2;
 
-    if (frameCount < minFrameCount) {
-      LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
-      return BAD_VALUE;
+        int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
+
+        if (sharedBuffer == 0) {
+            if (frameCount == 0) {
+                frameCount = minFrameCount;
+            }
+            if (notificationFrames == 0) {
+                notificationFrames = frameCount/2;
+            }
+            // Make sure that application is notified with sufficient margin
+            // before underrun
+            if (notificationFrames > frameCount/2) {
+                notificationFrames = frameCount/2;
+            }
+            if (frameCount < minFrameCount) {
+              LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
+              return BAD_VALUE;
+            }
+        } else {
+            // Ensure that buffer alignment matches channelcount
+            if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
+                LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
+                return BAD_VALUE;
+            }
+            frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
+        }
     }
 
     // create the track
     status_t status;
     sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
-                streamType, sampleRate, format, channelCount, frameCount, flags, sharedBuffer, &status);
+                                                      streamType,
+                                                      sampleRate,
+                                                      format,
+                                                      channelCount,
+                                                      frameCount,
+                                                      ((uint16_t)flags) << 16,
+                                                      sharedBuffer,
+                                                      output,
+                                                      &status);
 
     if (track == 0) {
         LOGE("AudioFlinger could not create track, status: %d", status);
@@ -245,6 +267,7 @@
     mVolume[RIGHT] = 1.0f;
     mStreamType = streamType;
     mFormat = format;
+    mChannels = channels;
     mChannelCount = channelCount;
     mSharedBuffer = sharedBuffer;
     mMuted = false;
@@ -259,6 +282,7 @@
     mMarkerReached = false;
     mNewPosition = 0;
     mUpdatePeriod = 0;
+    mFlags = flags;
 
     return NO_ERROR;
 }
@@ -297,7 +321,11 @@
 
 int AudioTrack::frameSize() const
 {
-    return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
+    if (AudioSystem::isLinearPCM(mFormat)) {
+        return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
+    } else {
+        return sizeof(uint8_t);
+    }
 }
 
 sp<IMemory>& AudioTrack::sharedBuffer()
@@ -323,6 +351,7 @@
      }
 
     if (android_atomic_or(1, &mActive) == 0) {
+        AudioSystem::startOutput(getOutput(), (AudioSystem::stream_type)mStreamType);
         mNewPosition = mCblk->server + mUpdatePeriod;
         mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
         mCblk->waitTimeMs = 0;
@@ -367,6 +396,7 @@
         } else {
             setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
         }
+        AudioSystem::stopOutput(getOutput(), (AudioSystem::stream_type)mStreamType);
     }
 
     if (t != 0) {
@@ -382,12 +412,12 @@
 void AudioTrack::flush()
 {
     LOGV("flush");
-    
+
     // clear playback marker and periodic update counter
     mMarkerPosition = 0;
     mMarkerReached = false;
     mUpdatePeriod = 0;
-    
+
 
     if (!mActive) {
         mAudioTrack->flush();
@@ -403,6 +433,7 @@
     if (android_atomic_and(~1, &mActive) == 1) {
         mActive = 0;
         mAudioTrack->pause();
+        AudioSystem::stopOutput(getOutput(), (AudioSystem::stream_type)mStreamType);
     }
 }
 
@@ -455,7 +486,6 @@
 {
     audio_track_cblk_t* cblk = mCblk;
 
-
     Mutex::Autolock _l(cblk->lock);
 
     if (loopCount == 0) {
@@ -476,7 +506,7 @@
         LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
             loopStart, loopEnd, mFrameCount);
         return BAD_VALUE;
-    }   
+    }
 
     cblk->loopStart = loopStart;
     cblk->loopEnd = loopEnd;
@@ -555,7 +585,7 @@
 
     mCblk->server = position;
     mCblk->forceReady = 1;
-    
+
     return NO_ERROR;
 }
 
@@ -571,7 +601,7 @@
 status_t AudioTrack::reload()
 {
     if (!stopped()) return INVALID_OPERATION;
-    
+
     flush();
 
     mCblk->stepUser(mFrameCount);
@@ -579,6 +609,12 @@
     return NO_ERROR;
 }
 
+audio_io_handle_t AudioTrack::getOutput()
+{
+    return AudioSystem::getOutput((AudioSystem::stream_type)mStreamType,
+            mCblk->sampleRate, mFormat, mChannels, (AudioSystem::output_flags)mFlags);
+}
+
 // -------------------------------------------------------------------------
 
 status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
@@ -608,7 +644,7 @@
                 return WOULD_BLOCK;
             timeout = 0;
             result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
-            if (__builtin_expect(result!=NO_ERROR, false)) { 
+            if (__builtin_expect(result!=NO_ERROR, false)) {
                 cblk->waitTimeMs += waitTimeMs;
                 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
                     // timing out when a loop has been set and we have already written upto loop end
@@ -616,7 +652,7 @@
                     if (cblk->user < cblk->loopEnd) {
                         LOGW(   "obtainBuffer timed out (is the CPU pegged?) %p "
                                 "user=%08x, server=%08x", this, cblk->user, cblk->server);
-                        //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140) 
+                        //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
                         cblk->lock.unlock();
                         mAudioTrack->start();
                         cblk->lock.lock();
@@ -624,7 +660,7 @@
                     }
                     cblk->waitTimeMs = 0;
                 }
-                
+
                 if (--waitCount == 0) {
                     return TIMED_OUT;
                 }
@@ -636,7 +672,7 @@
     }
 
     cblk->waitTimeMs = 0;
-    
+
     if (framesReq > framesAvail) {
         framesReq = framesAvail;
     }
@@ -653,12 +689,16 @@
         "but didn't need to be locked. We recovered, but "
         "this shouldn't happen (user=%08x, server=%08x)", cblk->user, cblk->server);
 
-    audioBuffer->flags       = mMuted ? Buffer::MUTE : 0;
-    audioBuffer->channelCount= mChannelCount;
-    audioBuffer->format      = AudioSystem::PCM_16_BIT;
-    audioBuffer->frameCount  = framesReq;
-    audioBuffer->size = framesReq*mChannelCount*sizeof(int16_t);
-    audioBuffer->raw         = (int8_t *)cblk->buffer(u);
+    audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
+    audioBuffer->channelCount = mChannelCount;
+    audioBuffer->frameCount = framesReq;
+    audioBuffer->size = framesReq * cblk->frameSize;
+    if (AudioSystem::isLinearPCM(mFormat)) {
+        audioBuffer->format = AudioSystem::PCM_16_BIT;
+    } else {
+        audioBuffer->format = mFormat;
+    }
+    audioBuffer->raw = (int8_t *)cblk->buffer(u);
     active = mActive;
     return active ? status_t(NO_ERROR) : status_t(STOPPED);
 }
@@ -690,10 +730,8 @@
     Buffer audioBuffer;
 
     do {
-        audioBuffer.frameCount = userSize/mChannelCount;
-        if (mFormat == AudioSystem::PCM_16_BIT) {
-            audioBuffer.frameCount >>= 1;
-        }
+        audioBuffer.frameCount = userSize/frameSize();
+
         // Calling obtainBuffer() with a negative wait count causes
         // an (almost) infinite wait time.
         status_t err = obtainBuffer(&audioBuffer, -1);
@@ -705,6 +743,7 @@
         }
 
         size_t toWrite;
+
         if (mFormat == AudioSystem::PCM_8_BIT) {
             // Divide capacity by 2 to take expansion into account
             toWrite = audioBuffer.size>>1;
@@ -742,13 +781,13 @@
         if (mCblk->flowControlFlag == 0) {
             mCbf(EVENT_UNDERRUN, mUserData, 0);
             if (mCblk->server == mCblk->frameCount) {
-                mCbf(EVENT_BUFFER_END, mUserData, 0);                
+                mCbf(EVENT_BUFFER_END, mUserData, 0);
             }
             mCblk->flowControlFlag = 1;
             if (mSharedBuffer != 0) return false;
         }
     }
-    
+
     // Manage loop end callback
     while (mLoopCount > mCblk->loopCount) {
         int loopCount = -1;
@@ -767,7 +806,7 @@
     }
 
     // Manage new position callback
-    if(mUpdatePeriod > 0) {
+    if (mUpdatePeriod > 0) {
         while (mCblk->server >= mNewPosition) {
             mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
             mNewPosition += mUpdatePeriod;
@@ -784,10 +823,10 @@
     do {
 
         audioBuffer.frameCount = frames;
-        
-        // Calling obtainBuffer() with a wait count of 1 
-        // limits wait time to WAIT_PERIOD_MS. This prevents from being 
-        // stuck here not being able to handle timed events (position, markers, loops). 
+
+        // Calling obtainBuffer() with a wait count of 1
+        // limits wait time to WAIT_PERIOD_MS. This prevents from being
+        // stuck here not being able to handle timed events (position, markers, loops).
         status_t err = obtainBuffer(&audioBuffer, 1);
         if (err < NO_ERROR) {
             if (err != TIMED_OUT) {
@@ -832,7 +871,11 @@
         }
 
         audioBuffer.size = writtenSize;
-        audioBuffer.frameCount = writtenSize/mChannelCount/sizeof(int16_t);
+        // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
+        // 8 bit PCM data: in this case,  mCblk->frameSize is based on a sampel size of
+        // 16 bit.
+        audioBuffer.frameCount = writtenSize/mCblk->frameSize;
+
         frames -= audioBuffer.frameCount;
 
         releaseBuffer(&audioBuffer);
@@ -891,7 +934,7 @@
 // =========================================================================
 
 audio_track_cblk_t::audio_track_cblk_t()
-    : user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0),
+    : lock(Mutex::SHARED), user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0),
     loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), flowControlFlag(1), forceReady(0)
 {
 }
@@ -949,7 +992,7 @@
         // we switch to normal obtainBuffer() timeout period
         if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
             bufferTimeoutMs = MAX_RUN_TIMEOUT_MS - 1;
-        }        
+        }
         // It is possible that we receive a flush()
         // while the mixer is processing a block: in this case,
         // stepServer() is called After the flush() has reset u & s and
@@ -981,7 +1024,7 @@
 
 void* audio_track_cblk_t::buffer(uint32_t offset) const
 {
-    return (int16_t *)this->buffers + (offset-userBase)*this->channels;
+    return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
 }
 
 uint32_t audio_track_cblk_t::framesAvailable()
diff --git a/media/libmedia/IAudioFlinger.cpp b/media/libmedia/IAudioFlinger.cpp
index eeaa54f..9385367 100644
--- a/media/libmedia/IAudioFlinger.cpp
+++ b/media/libmedia/IAudioFlinger.cpp
@@ -16,12 +16,13 @@
 */
 
 #define LOG_TAG "IAudioFlinger"
+//#define LOG_NDEBUG 0
 #include <utils/Log.h>
 
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 
 #include <media/IAudioFlinger.h>
 
@@ -44,17 +45,21 @@
     STREAM_VOLUME,
     STREAM_MUTE,
     SET_MODE,
-    GET_MODE,
-    SET_ROUTING,
-    GET_ROUTING,
     SET_MIC_MUTE,
     GET_MIC_MUTE,
     IS_MUSIC_ACTIVE,
-    SET_PARAMETER,
+    SET_PARAMETERS,
+    GET_PARAMETERS,
     REGISTER_CLIENT,
     GET_INPUTBUFFERSIZE,
-    WAKE_UP,
-    IS_A2DP_ENABLED
+    OPEN_OUTPUT,
+    OPEN_DUPLICATE_OUTPUT,
+    CLOSE_OUTPUT,
+    SUSPEND_OUTPUT,
+    RESTORE_OUTPUT,
+    OPEN_INPUT,
+    CLOSE_INPUT,
+    SET_STREAM_OUTPUT
 };
 
 class BpAudioFlinger : public BpInterface<IAudioFlinger>
@@ -74,6 +79,7 @@
                                 int frameCount,
                                 uint32_t flags,
                                 const sp<IMemory>& sharedBuffer,
+                                void *output,
                                 status_t *status)
     {
         Parcel data, reply;
@@ -86,6 +92,7 @@
         data.writeInt32(frameCount);
         data.writeInt32(flags);
         data.writeStrongBinder(sharedBuffer->asBinder());
+        data.write(&output, sizeof(void *));
         status_t lStatus = remote()->transact(CREATE_TRACK, data, &reply);
         if (lStatus != NO_ERROR) {
             LOGE("createTrack error: %s", strerror(-lStatus));
@@ -99,7 +106,7 @@
 
     virtual sp<IAudioRecord> openRecord(
                                 pid_t pid,
-                                int inputSource,
+                                void *input,
                                 uint32_t sampleRate,
                                 int format,
                                 int channelCount,
@@ -110,7 +117,7 @@
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
         data.writeInt32(pid);
-        data.writeInt32(inputSource);
+        data.write(&input, sizeof(void *));
         data.writeInt32(sampleRate);
         data.writeInt32(format);
         data.writeInt32(channelCount);
@@ -124,47 +131,47 @@
         return interface_cast<IAudioRecord>(reply.readStrongBinder());
     }
 
-    virtual uint32_t sampleRate(int output) const
+    virtual uint32_t sampleRate(void *output) const
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(output);
+        data.write(&output, sizeof(void *));
         remote()->transact(SAMPLE_RATE, data, &reply);
         return reply.readInt32();
     }
 
-    virtual int channelCount(int output) const
+    virtual int channelCount(void *output) const
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(output);
+        data.write(&output, sizeof(void *));
         remote()->transact(CHANNEL_COUNT, data, &reply);
         return reply.readInt32();
     }
 
-    virtual int format(int output) const
+    virtual int format(void *output) const
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(output);
+        data.write(&output, sizeof(void *));
         remote()->transact(FORMAT, data, &reply);
         return reply.readInt32();
     }
 
-    virtual size_t frameCount(int output) const
+    virtual size_t frameCount(void *output) const
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(output);
+        data.write(&output, sizeof(void *));
         remote()->transact(FRAME_COUNT, data, &reply);
         return reply.readInt32();
     }
 
-    virtual uint32_t latency(int output) const
+    virtual uint32_t latency(void *output) const
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(output);
+        data.write(&output, sizeof(void *));
         remote()->transact(LATENCY, data, &reply);
         return reply.readInt32();
     }
@@ -203,12 +210,13 @@
         return reply.readInt32();
     }
 
-    virtual status_t setStreamVolume(int stream, float value)
+    virtual status_t setStreamVolume(int stream, float value, void *output)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
         data.writeInt32(stream);
         data.writeFloat(value);
+        data.write(&output, sizeof(void *));
         remote()->transact(SET_STREAM_VOLUME, data, &reply);
         return reply.readInt32();
     }
@@ -223,11 +231,12 @@
         return reply.readInt32();
     }
 
-    virtual float streamVolume(int stream) const
+    virtual float streamVolume(int stream, void *output) const
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
         data.writeInt32(stream);
+        data.write(&output, sizeof(void *));
         remote()->transact(STREAM_VOLUME, data, &reply);
         return reply.readFloat();
     }
@@ -241,26 +250,6 @@
         return reply.readInt32();
     }
 
-    virtual status_t setRouting(int mode, uint32_t routes, uint32_t mask)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(mode);
-        data.writeInt32(routes);
-        data.writeInt32(mask);
-        remote()->transact(SET_ROUTING, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual uint32_t getRouting(int mode) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(mode);
-        remote()->transact(GET_ROUTING, data, &reply);
-        return reply.readInt32();
-    }
-
     virtual status_t setMode(int mode)
     {
         Parcel data, reply;
@@ -270,14 +259,6 @@
         return reply.readInt32();
     }
 
-    virtual int getMode() const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        remote()->transact(GET_MODE, data, &reply);
-        return reply.readInt32();
-    }
-
     virtual status_t setMicMute(bool state)
     {
         Parcel data, reply;
@@ -303,16 +284,26 @@
         return reply.readInt32();
     }
 
-    virtual status_t setParameter(const char* key, const char* value)
+    virtual status_t setParameters(void *ioHandle, const String8& keyValuePairs)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeCString(key);
-        data.writeCString(value);
-        remote()->transact(SET_PARAMETER, data, &reply);
+        data.write(&ioHandle, sizeof(void *));
+        data.writeString8(keyValuePairs);
+        remote()->transact(SET_PARAMETERS, data, &reply);
         return reply.readInt32();
     }
-    
+
+    virtual String8 getParameters(void *ioHandle, const String8& keys)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
+        data.write(&ioHandle, sizeof(void *));
+        data.writeString8(keys);
+        remote()->transact(GET_PARAMETERS, data, &reply);
+        return reply.readString8();
+    }
+
     virtual void registerClient(const sp<IAudioFlingerClient>& client)
     {
         Parcel data, reply;
@@ -320,7 +311,7 @@
         data.writeStrongBinder(client->asBinder());
         remote()->transact(REGISTER_CLIENT, data, &reply);
     }
-    
+
     virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
     {
         Parcel data, reply;
@@ -331,21 +322,133 @@
         remote()->transact(GET_INPUTBUFFERSIZE, data, &reply);
         return reply.readInt32();
     }
-    
-    virtual void wakeUp()
+
+    virtual void *openOutput(uint32_t *pDevices,
+                            uint32_t *pSamplingRate,
+                            uint32_t *pFormat,
+                            uint32_t *pChannels,
+                            uint32_t *pLatencyMs,
+                            uint32_t flags)
     {
         Parcel data, reply;
+        uint32_t devices = pDevices ? *pDevices : 0;
+        uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
+        uint32_t format = pFormat ? *pFormat : 0;
+        uint32_t channels = pChannels ? *pChannels : 0;
+        uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
+
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        remote()->transact(WAKE_UP, data, &reply, IBinder::FLAG_ONEWAY);
-        return;
+        data.writeInt32(devices);
+        data.writeInt32(samplingRate);
+        data.writeInt32(format);
+        data.writeInt32(channels);
+        data.writeInt32(latency);
+        data.writeInt32(flags);
+        remote()->transact(OPEN_OUTPUT, data, &reply);
+        void *output;
+        reply.read(&output, sizeof(void *));
+        LOGV("openOutput() returned output, %p", output);
+        devices = reply.readInt32();
+        if (pDevices) *pDevices = devices;
+        samplingRate = reply.readInt32();
+        if (pSamplingRate) *pSamplingRate = samplingRate;
+        format = reply.readInt32();
+        if (pFormat) *pFormat = format;
+        channels = reply.readInt32();
+        if (pChannels) *pChannels = channels;
+        latency = reply.readInt32();
+        if (pLatencyMs) *pLatencyMs = latency;
+        return output;
     }
 
-    virtual bool isA2dpEnabled() const
+    virtual void *openDuplicateOutput(void *output1, void *output2)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        remote()->transact(IS_A2DP_ENABLED, data, &reply);
-        return (bool)reply.readInt32();
+        data.write(&output1, sizeof(void *));
+        data.write(&output2, sizeof(void *));
+        remote()->transact(OPEN_DUPLICATE_OUTPUT, data, &reply);
+        void *output;
+        reply.read(&output, sizeof(void *));
+        return output;
+    }
+
+    virtual status_t closeOutput(void *output)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
+        data.write(&output, sizeof(void *));
+        remote()->transact(CLOSE_OUTPUT, data, &reply);
+        return reply.readInt32();
+    }
+
+    virtual status_t suspendOutput(void *output)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
+        data.write(&output, sizeof(void *));
+        remote()->transact(SUSPEND_OUTPUT, data, &reply);
+        return reply.readInt32();
+    }
+
+    virtual status_t restoreOutput(void *output)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
+        data.write(&output, sizeof(void *));
+        remote()->transact(RESTORE_OUTPUT, data, &reply);
+        return reply.readInt32();
+    }
+
+    virtual void *openInput(uint32_t *pDevices,
+                                        uint32_t *pSamplingRate,
+                                        uint32_t *pFormat,
+                                        uint32_t *pChannels,
+                                        uint32_t acoustics)
+    {
+        Parcel data, reply;
+        uint32_t devices = pDevices ? *pDevices : 0;
+        uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
+        uint32_t format = pFormat ? *pFormat : 0;
+        uint32_t channels = pChannels ? *pChannels : 0;
+
+        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
+        data.writeInt32(devices);
+        data.writeInt32(samplingRate);
+        data.writeInt32(format);
+        data.writeInt32(channels);
+        data.writeInt32(acoustics);
+        remote()->transact(OPEN_INPUT, data, &reply);
+        void *input;
+        reply.read(&input, sizeof(void *));
+        devices = reply.readInt32();
+        if (pDevices) *pDevices = devices;
+        samplingRate = reply.readInt32();
+        if (pSamplingRate) *pSamplingRate = samplingRate;
+        format = reply.readInt32();
+        if (pFormat) *pFormat = format;
+        channels = reply.readInt32();
+        if (pChannels) *pChannels = channels;
+        return input;
+    }
+
+    virtual status_t closeInput(void *input)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
+        data.write(&input, sizeof(void *));
+        remote()->transact(CLOSE_INPUT, data, &reply);
+        return reply.readInt32();
+    }
+
+    virtual status_t setStreamOutput(uint32_t stream, void *output)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
+        data.writeInt32(stream);
+        data.write(&output, sizeof(void *));
+        remote()->transact(SET_STREAM_OUTPUT, data, &reply);
+        return reply.readInt32();
     }
 };
 
@@ -353,12 +456,6 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnAudioFlinger::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
@@ -373,10 +470,12 @@
             size_t bufferCount = data.readInt32();
             uint32_t flags = data.readInt32();
             sp<IMemory> buffer = interface_cast<IMemory>(data.readStrongBinder());
+            void *output;
+            data.read(&output, sizeof(void *));
             status_t status;
             sp<IAudioTrack> track = createTrack(pid,
                     streamType, sampleRate, format,
-                    channelCount, bufferCount, flags, buffer, &status);
+                    channelCount, bufferCount, flags, buffer, output, &status);
             reply->writeInt32(status);
             reply->writeStrongBinder(track->asBinder());
             return NO_ERROR;
@@ -384,14 +483,15 @@
         case OPEN_RECORD: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             pid_t pid = data.readInt32();
-            int inputSource = data.readInt32();
+            void *input;
+            data.read(&input, sizeof(void *));
             uint32_t sampleRate = data.readInt32();
             int format = data.readInt32();
             int channelCount = data.readInt32();
             size_t bufferCount = data.readInt32();
             uint32_t flags = data.readInt32();
             status_t status;
-            sp<IAudioRecord> record = openRecord(pid, inputSource,
+            sp<IAudioRecord> record = openRecord(pid, input,
                     sampleRate, format, channelCount, bufferCount, flags, &status);
             reply->writeInt32(status);
             reply->writeStrongBinder(record->asBinder());
@@ -399,31 +499,36 @@
         } break;
         case SAMPLE_RATE: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int output = data.readInt32();
+            void *output;
+            data.read(&output, sizeof(void *));
             reply->writeInt32( sampleRate(output) );
             return NO_ERROR;
         } break;
         case CHANNEL_COUNT: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int output = data.readInt32();
+            void *output;
+            data.read(&output, sizeof(void *));
             reply->writeInt32( channelCount(output) );
             return NO_ERROR;
         } break;
         case FORMAT: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int output = data.readInt32();
+            void *output;
+            data.read(&output, sizeof(void *));
             reply->writeInt32( format(output) );
             return NO_ERROR;
         } break;
         case FRAME_COUNT: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int output = data.readInt32();
+            void *output;
+            data.read(&output, sizeof(void *));
             reply->writeInt32( frameCount(output) );
             return NO_ERROR;
         } break;
         case LATENCY: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int output = data.readInt32();
+            void *output;
+            data.read(&output, sizeof(void *));
             reply->writeInt32( latency(output) );
             return NO_ERROR;
         } break;
@@ -450,7 +555,10 @@
         case SET_STREAM_VOLUME: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             int stream = data.readInt32();
-            reply->writeInt32( setStreamVolume(stream, data.readFloat()) );
+            float volume = data.readFloat();
+            void *output;
+            data.read(&output, sizeof(void *));
+            reply->writeInt32( setStreamVolume(stream, volume, output) );
             return NO_ERROR;
         } break;
         case SET_STREAM_MUTE: {
@@ -462,7 +570,9 @@
         case STREAM_VOLUME: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             int stream = data.readInt32();
-            reply->writeFloat( streamVolume(stream) );
+            void *output;
+            data.read(&output, sizeof(void *));
+            reply->writeFloat( streamVolume(stream, output) );
             return NO_ERROR;
         } break;
         case STREAM_MUTE: {
@@ -471,31 +581,12 @@
             reply->writeInt32( streamMute(stream) );
             return NO_ERROR;
         } break;
-        case SET_ROUTING: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int mode = data.readInt32();
-            uint32_t routes = data.readInt32();
-            uint32_t mask = data.readInt32();
-            reply->writeInt32( setRouting(mode, routes, mask) );
-            return NO_ERROR;
-        } break;
-        case GET_ROUTING: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int mode = data.readInt32();
-            reply->writeInt32( getRouting(mode) );
-            return NO_ERROR;
-        } break;
         case SET_MODE: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             int mode = data.readInt32();
             reply->writeInt32( setMode(mode) );
             return NO_ERROR;
         } break;
-        case GET_MODE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32( getMode() );
-            return NO_ERROR;
-        } break;
         case SET_MIC_MUTE: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             int state = data.readInt32();
@@ -512,13 +603,23 @@
             reply->writeInt32( isMusicActive() );
             return NO_ERROR;
         } break;
-        case SET_PARAMETER: {
+        case SET_PARAMETERS: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            const char *key = data.readCString();
-            const char *value = data.readCString();
-            reply->writeInt32( setParameter(key, value) );
+            void *ioHandle;
+            data.read(&ioHandle, sizeof(void *));
+            String8 keyValuePairs(data.readString8());
+            reply->writeInt32(setParameters(ioHandle, keyValuePairs));
             return NO_ERROR;
-        } break;
+         } break;
+        case GET_PARAMETERS: {
+            CHECK_INTERFACE(IAudioFlinger, data, reply);
+            void *ioHandle;
+            data.read(&ioHandle, sizeof(void *));
+            String8 keys(data.readString8());
+            reply->writeString8(getParameters(ioHandle, keys));
+            return NO_ERROR;
+         } break;
+
         case REGISTER_CLIENT: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient>(data.readStrongBinder());
@@ -533,14 +634,93 @@
             reply->writeInt32( getInputBufferSize(sampleRate, format, channelCount) );
             return NO_ERROR;
         } break;
-        case WAKE_UP: {
+        case OPEN_OUTPUT: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            wakeUp();
+            uint32_t devices = data.readInt32();
+            uint32_t samplingRate = data.readInt32();
+            uint32_t format = data.readInt32();
+            uint32_t channels = data.readInt32();
+            uint32_t latency = data.readInt32();
+            uint32_t flags = data.readInt32();
+            void *output = openOutput(&devices,
+                                     &samplingRate,
+                                     &format,
+                                     &channels,
+                                     &latency,
+                                     flags);
+            LOGV("OPEN_OUTPUT output, %p", output);
+            reply->write(&output, sizeof(void *));
+            reply->writeInt32(devices);
+            reply->writeInt32(samplingRate);
+            reply->writeInt32(format);
+            reply->writeInt32(channels);
+            reply->writeInt32(latency);
             return NO_ERROR;
         } break;
-        case IS_A2DP_ENABLED: {
+        case OPEN_DUPLICATE_OUTPUT: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32( (int)isA2dpEnabled() );
+            void *output1;
+            void *output2;
+            data.read(&output1, sizeof(void *));
+            data.read(&output2, sizeof(void *));
+            void *output = openDuplicateOutput(output1, output2);
+            reply->write(&output, sizeof(void *));
+            return NO_ERROR;
+        } break;
+        case CLOSE_OUTPUT: {
+            CHECK_INTERFACE(IAudioFlinger, data, reply);
+            void *output;
+            data.read(&output, sizeof(void *));
+            reply->writeInt32(closeOutput(output));
+            return NO_ERROR;
+        } break;
+        case SUSPEND_OUTPUT: {
+            CHECK_INTERFACE(IAudioFlinger, data, reply);
+            void *output;
+            data.read(&output, sizeof(void *));
+            reply->writeInt32(suspendOutput(output));
+            return NO_ERROR;
+        } break;
+        case RESTORE_OUTPUT: {
+            CHECK_INTERFACE(IAudioFlinger, data, reply);
+            void *output;
+            data.read(&output, sizeof(void *));
+            reply->writeInt32(restoreOutput(output));
+            return NO_ERROR;
+        } break;
+        case OPEN_INPUT: {
+            CHECK_INTERFACE(IAudioFlinger, data, reply);
+            uint32_t devices = data.readInt32();
+            uint32_t samplingRate = data.readInt32();
+            uint32_t format = data.readInt32();
+            uint32_t channels = data.readInt32();
+            uint32_t acoutics = data.readInt32();
+
+            void *input = openInput(&devices,
+                                     &samplingRate,
+                                     &format,
+                                     &channels,
+                                     acoutics);
+            reply->write(&input, sizeof(void *));
+            reply->writeInt32(devices);
+            reply->writeInt32(samplingRate);
+            reply->writeInt32(format);
+            reply->writeInt32(channels);
+            return NO_ERROR;
+        } break;
+        case CLOSE_INPUT: {
+            CHECK_INTERFACE(IAudioFlinger, data, reply);
+            void *input;
+            data.read(&input, sizeof(void *));
+            reply->writeInt32(closeInput(input));
+            return NO_ERROR;
+        } break;
+        case SET_STREAM_OUTPUT: {
+            CHECK_INTERFACE(IAudioFlinger, data, reply);
+            void *output;
+            uint32_t stream = data.readInt32();
+            data.read(&output, sizeof(void *));
+            reply->writeInt32(setStreamOutput(stream, output));
             return NO_ERROR;
         } break;
         default:
diff --git a/media/libmedia/IAudioFlingerClient.cpp b/media/libmedia/IAudioFlingerClient.cpp
index 9d00aefb..eaae977 100644
--- a/media/libmedia/IAudioFlingerClient.cpp
+++ b/media/libmedia/IAudioFlingerClient.cpp
@@ -20,14 +20,15 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 
 #include <media/IAudioFlingerClient.h>
+#include <media/AudioSystem.h>
 
 namespace android {
 
 enum {
-    AUDIO_OUTPUT_CHANGED = IBinder::FIRST_CALL_TRANSACTION
+    IO_CONFIG_CHANGED = IBinder::FIRST_CALL_TRANSACTION
 };
 
 class BpAudioFlingerClient : public BpInterface<IAudioFlingerClient>
@@ -38,12 +39,25 @@
     {
     }
 
-    void a2dpEnabledChanged(bool enabled)
+    void ioConfigChanged(int event, void *param1, void *param2)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlingerClient::getInterfaceDescriptor());
-        data.writeInt32((int)enabled);
-        remote()->transact(AUDIO_OUTPUT_CHANGED, data, &reply, IBinder::FLAG_ONEWAY);
+        data.writeInt32(event);
+        data.write(&param1, sizeof(void *));
+        if (event == AudioSystem::STREAM_CONFIG_CHANGED) {
+            uint32_t stream = *(uint32_t *)param2;
+            LOGV("ioConfigChanged stream %d", stream);
+            data.writeInt32(stream);
+        } else if (event != AudioSystem::OUTPUT_CLOSED && event != AudioSystem::INPUT_CLOSED) {
+            AudioSystem::OutputDescriptor *desc = (AudioSystem::OutputDescriptor *)param2;
+            data.writeInt32(desc->samplingRate);
+            data.writeInt32(desc->format);
+            data.writeInt32(desc->channels);
+            data.writeInt32(desc->frameCount);
+            data.writeInt32(desc->latency);
+        }
+        remote()->transact(IO_CONFIG_CHANGED, data, &reply, IBinder::FLAG_ONEWAY);
     }
 };
 
@@ -51,20 +65,31 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnAudioFlingerClient::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
     switch(code) {
-        case AUDIO_OUTPUT_CHANGED: {
+    case IO_CONFIG_CHANGED: {
             CHECK_INTERFACE(IAudioFlingerClient, data, reply);
-            bool enabled = (bool)data.readInt32();
-            a2dpEnabledChanged(enabled);
+            int event = data.readInt32();
+            void *param1;
+            void *param2 = 0;
+            AudioSystem::OutputDescriptor desc;
+            uint32_t stream;
+            data.read(&param1, sizeof(void *));
+            if (event == AudioSystem::STREAM_CONFIG_CHANGED) {
+                stream = data.readInt32();
+                param2 = &stream;
+                LOGV("STREAM_CONFIG_CHANGED stream %d", stream);
+            } else if (event != AudioSystem::OUTPUT_CLOSED && event != AudioSystem::INPUT_CLOSED) {
+                desc.samplingRate = data.readInt32();
+                desc.format = data.readInt32();
+                desc.channels = data.readInt32();
+                desc.frameCount = data.readInt32();
+                desc.latency = data.readInt32();
+                param2 = &desc;
+            }
+            ioConfigChanged(event, param1, param2);
             return NO_ERROR;
         } break;
         default:
diff --git a/media/libmedia/IAudioPolicyService.cpp b/media/libmedia/IAudioPolicyService.cpp
new file mode 100644
index 0000000..0d8a329
--- /dev/null
+++ b/media/libmedia/IAudioPolicyService.cpp
@@ -0,0 +1,423 @@
+/*
+**
+** Copyright 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 "IAudioPolicyService"
+#include <utils/Log.h>
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <binder/Parcel.h>
+
+#include <media/IAudioPolicyService.h>
+
+namespace android {
+
+enum {
+    SET_DEVICE_CONNECTION_STATE = IBinder::FIRST_CALL_TRANSACTION,
+    GET_DEVICE_CONNECTION_STATE,
+    SET_PHONE_STATE,
+    SET_RINGER_MODE,
+    SET_FORCE_USE,
+    GET_FORCE_USE,
+    GET_OUTPUT,
+    START_OUTPUT,
+    STOP_OUTPUT,
+    RELEASE_OUTPUT,
+    GET_INPUT,
+    START_INPUT,
+    STOP_INPUT,
+    RELEASE_INPUT,
+    INIT_STREAM_VOLUME,
+    SET_STREAM_VOLUME,
+    GET_STREAM_VOLUME
+};
+
+class BpAudioPolicyService : public BpInterface<IAudioPolicyService>
+{
+public:
+    BpAudioPolicyService(const sp<IBinder>& impl)
+        : BpInterface<IAudioPolicyService>(impl)
+    {
+    }
+
+    virtual status_t setDeviceConnectionState(
+                                    AudioSystem::audio_devices device,
+                                    AudioSystem::device_connection_state state,
+                                    const char *device_address)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(static_cast <uint32_t>(device));
+        data.writeInt32(static_cast <uint32_t>(state));
+        data.writeCString(device_address);
+        remote()->transact(SET_DEVICE_CONNECTION_STATE, data, &reply);
+        return static_cast <status_t> (reply.readInt32());
+    }
+
+    virtual AudioSystem::device_connection_state getDeviceConnectionState(
+                                    AudioSystem::audio_devices device,
+                                    const char *device_address)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(static_cast <uint32_t>(device));
+        data.writeCString(device_address);
+        remote()->transact(GET_DEVICE_CONNECTION_STATE, data, &reply);
+        return static_cast <AudioSystem::device_connection_state>(reply.readInt32());
+    }
+
+    virtual status_t setPhoneState(int state)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(state);
+        remote()->transact(SET_PHONE_STATE, data, &reply);
+        return static_cast <status_t> (reply.readInt32());
+    }
+
+    virtual status_t setRingerMode(uint32_t mode, uint32_t mask)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(mode);
+        data.writeInt32(mask);
+        remote()->transact(SET_RINGER_MODE, data, &reply);
+        return static_cast <status_t> (reply.readInt32());
+    }
+
+    virtual status_t setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(static_cast <uint32_t>(usage));
+        data.writeInt32(static_cast <uint32_t>(config));
+        remote()->transact(SET_FORCE_USE, data, &reply);
+        return static_cast <status_t> (reply.readInt32());
+    }
+
+    virtual AudioSystem::forced_config getForceUse(AudioSystem::force_use usage)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(static_cast <uint32_t>(usage));
+        remote()->transact(GET_FORCE_USE, data, &reply);
+        return static_cast <AudioSystem::forced_config> (reply.readInt32());
+    }
+
+    virtual audio_io_handle_t getOutput(
+                                        AudioSystem::stream_type stream,
+                                        uint32_t samplingRate,
+                                        uint32_t format,
+                                        uint32_t channels,
+                                        AudioSystem::output_flags flags)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(static_cast <uint32_t>(stream));
+        data.writeInt32(samplingRate);
+        data.writeInt32(static_cast <uint32_t>(format));
+        data.writeInt32(channels);
+        data.writeInt32(static_cast <uint32_t>(flags));
+        remote()->transact(GET_OUTPUT, data, &reply);
+        audio_io_handle_t output;
+        reply.read(&output, sizeof(audio_io_handle_t));
+        return output;
+    }
+
+    virtual status_t startOutput(audio_io_handle_t output, AudioSystem::stream_type stream)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.write(&output, sizeof(audio_io_handle_t));
+        data.writeInt32(stream);
+        remote()->transact(START_OUTPUT, data, &reply);
+        return static_cast <status_t> (reply.readInt32());
+    }
+
+    virtual status_t stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.write(&output, sizeof(audio_io_handle_t));
+        data.writeInt32(stream);
+        remote()->transact(STOP_OUTPUT, data, &reply);
+        return static_cast <status_t> (reply.readInt32());
+    }
+
+    virtual void releaseOutput(audio_io_handle_t output)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.write(&output, sizeof(audio_io_handle_t));
+        remote()->transact(RELEASE_OUTPUT, data, &reply);
+    }
+
+    virtual audio_io_handle_t getInput(
+                                    int inputSource,
+                                    uint32_t samplingRate,
+                                    uint32_t format,
+                                    uint32_t channels,
+                                    AudioSystem::audio_in_acoustics acoustics)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(inputSource);
+        data.writeInt32(samplingRate);
+        data.writeInt32(static_cast <uint32_t>(format));
+        data.writeInt32(channels);
+        data.writeInt32(static_cast <uint32_t>(acoustics));
+        remote()->transact(GET_INPUT, data, &reply);
+        audio_io_handle_t input;
+        reply.read(&input, sizeof(audio_io_handle_t));
+        return input;
+    }
+
+    virtual status_t startInput(audio_io_handle_t input)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.write(&input, sizeof(audio_io_handle_t));
+        remote()->transact(START_INPUT, data, &reply);
+        return static_cast <status_t> (reply.readInt32());
+    }
+
+    virtual status_t stopInput(audio_io_handle_t input)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.write(&input, sizeof(audio_io_handle_t));
+        remote()->transact(STOP_INPUT, data, &reply);
+        return static_cast <status_t> (reply.readInt32());
+    }
+
+    virtual void releaseInput(audio_io_handle_t input)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.write(&input, sizeof(audio_io_handle_t));
+        remote()->transact(RELEASE_INPUT, data, &reply);
+    }
+
+    virtual status_t initStreamVolume(AudioSystem::stream_type stream,
+                                    int indexMin,
+                                    int indexMax)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(static_cast <uint32_t>(stream));
+        data.writeInt32(indexMin);
+        data.writeInt32(indexMax);
+        remote()->transact(INIT_STREAM_VOLUME, data, &reply);
+        return static_cast <status_t> (reply.readInt32());
+    }
+
+    virtual status_t setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(static_cast <uint32_t>(stream));
+        data.writeInt32(index);
+        remote()->transact(SET_STREAM_VOLUME, data, &reply);
+        return static_cast <status_t> (reply.readInt32());
+    }
+
+    virtual status_t getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeInt32(static_cast <uint32_t>(stream));
+        remote()->transact(GET_STREAM_VOLUME, data, &reply);
+        int lIndex = reply.readInt32();
+        if (index) *index = lIndex;
+        return static_cast <status_t> (reply.readInt32());
+    }
+};
+
+IMPLEMENT_META_INTERFACE(AudioPolicyService, "android.media.IAudioPolicyService");
+
+// ----------------------------------------------------------------------
+
+
+status_t BnAudioPolicyService::onTransact(
+    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
+{
+    switch(code) {
+        case SET_DEVICE_CONNECTION_STATE: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            AudioSystem::audio_devices device = static_cast <AudioSystem::audio_devices>(data.readInt32());
+            AudioSystem::device_connection_state state = static_cast <AudioSystem::device_connection_state>(data.readInt32());
+            const char *device_address = data.readCString();
+            reply->writeInt32(static_cast <uint32_t>(setDeviceConnectionState(device, state, device_address)));
+            return NO_ERROR;
+        } break;
+
+        case GET_DEVICE_CONNECTION_STATE: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            AudioSystem::audio_devices device = static_cast <AudioSystem::audio_devices>(data.readInt32());
+            const char *device_address = data.readCString();
+            reply->writeInt32(static_cast <uint32_t>(getDeviceConnectionState(device, device_address)));
+            return NO_ERROR;
+        } break;
+
+        case SET_PHONE_STATE: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            reply->writeInt32(static_cast <uint32_t>(setPhoneState(data.readInt32())));
+            return NO_ERROR;
+        } break;
+
+        case SET_RINGER_MODE: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            uint32_t mode = data.readInt32();
+            uint32_t mask = data.readInt32();
+            reply->writeInt32(static_cast <uint32_t>(setRingerMode(mode, mask)));
+            return NO_ERROR;
+        } break;
+
+        case SET_FORCE_USE: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            AudioSystem::force_use usage = static_cast <AudioSystem::force_use>(data.readInt32());
+            AudioSystem::forced_config config = static_cast <AudioSystem::forced_config>(data.readInt32());
+            reply->writeInt32(static_cast <uint32_t>(setForceUse(usage, config)));
+            return NO_ERROR;
+        } break;
+
+        case GET_FORCE_USE: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            AudioSystem::force_use usage = static_cast <AudioSystem::force_use>(data.readInt32());
+            reply->writeInt32(static_cast <uint32_t>(getForceUse(usage)));
+            return NO_ERROR;
+        } break;
+
+        case GET_OUTPUT: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            AudioSystem::stream_type stream = static_cast <AudioSystem::stream_type>(data.readInt32());
+            uint32_t samplingRate = data.readInt32();
+            uint32_t format = data.readInt32();
+            uint32_t channels = data.readInt32();
+            AudioSystem::output_flags flags = static_cast <AudioSystem::output_flags>(data.readInt32());
+
+            audio_io_handle_t output = getOutput(stream,
+                                                 samplingRate,
+                                                 format,
+                                                 channels,
+                                                 flags);
+            reply->write(&output, sizeof(audio_io_handle_t));
+            return NO_ERROR;
+        } break;
+
+        case START_OUTPUT: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_io_handle_t output;
+            data.read(&output, sizeof(audio_io_handle_t));
+            uint32_t stream = data.readInt32();
+            reply->writeInt32(static_cast <uint32_t>(startOutput(output, (AudioSystem::stream_type)stream)));
+            return NO_ERROR;
+        } break;
+
+        case STOP_OUTPUT: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_io_handle_t output;
+            data.read(&output, sizeof(audio_io_handle_t));
+            uint32_t stream = data.readInt32();
+            reply->writeInt32(static_cast <uint32_t>(stopOutput(output, (AudioSystem::stream_type)stream)));
+            return NO_ERROR;
+        } break;
+
+        case RELEASE_OUTPUT: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_io_handle_t output;
+            data.read(&output, sizeof(audio_io_handle_t));
+            releaseOutput(output);
+            return NO_ERROR;
+        } break;
+
+        case GET_INPUT: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            int inputSource = data.readInt32();
+            uint32_t samplingRate = data.readInt32();
+            uint32_t format = data.readInt32();
+            uint32_t channels = data.readInt32();
+            AudioSystem::audio_in_acoustics acoustics = static_cast <AudioSystem::audio_in_acoustics>(data.readInt32());
+            audio_io_handle_t input = getInput(inputSource,
+                                               samplingRate,
+                                               format,
+                                               channels,
+                                               acoustics);
+            reply->write(&input, sizeof(audio_io_handle_t));
+            return NO_ERROR;
+        } break;
+
+        case START_INPUT: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_io_handle_t input;
+            data.read(&input, sizeof(audio_io_handle_t));
+            reply->writeInt32(static_cast <uint32_t>(startInput(input)));
+            return NO_ERROR;
+        } break;
+
+        case STOP_INPUT: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_io_handle_t input;
+            data.read(&input, sizeof(audio_io_handle_t));
+            reply->writeInt32(static_cast <uint32_t>(stopInput(input)));
+            return NO_ERROR;
+        } break;
+
+        case RELEASE_INPUT: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_io_handle_t input;
+            data.read(&input, sizeof(audio_io_handle_t));
+            releaseInput(input);
+            return NO_ERROR;
+        } break;
+
+        case INIT_STREAM_VOLUME: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            AudioSystem::stream_type stream = static_cast <AudioSystem::stream_type>(data.readInt32());
+            int indexMin = data.readInt32();
+            int indexMax = data.readInt32();
+            reply->writeInt32(static_cast <uint32_t>(initStreamVolume(stream, indexMin,indexMax)));
+            return NO_ERROR;
+        } break;
+
+        case SET_STREAM_VOLUME: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            AudioSystem::stream_type stream = static_cast <AudioSystem::stream_type>(data.readInt32());
+            int index = data.readInt32();
+            reply->writeInt32(static_cast <uint32_t>(setStreamVolumeIndex(stream, index)));
+            return NO_ERROR;
+        } break;
+
+        case GET_STREAM_VOLUME: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            AudioSystem::stream_type stream = static_cast <AudioSystem::stream_type>(data.readInt32());
+            int index;
+            status_t status = getStreamVolumeIndex(stream, &index);
+            reply->writeInt32(index);
+            reply->writeInt32(static_cast <uint32_t>(status));
+            return NO_ERROR;
+        } break;
+
+        default:
+            return BBinder::onTransact(code, data, reply, flags);
+    }
+}
+
+// ----------------------------------------------------------------------------
+
+}; // namespace android
diff --git a/media/libmedia/IAudioRecord.cpp b/media/libmedia/IAudioRecord.cpp
index 6e42dac..8fb5d3d 100644
--- a/media/libmedia/IAudioRecord.cpp
+++ b/media/libmedia/IAudioRecord.cpp
@@ -18,7 +18,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 
 #include <media/IAudioRecord.h>
 
@@ -66,12 +66,6 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnAudioRecord::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/media/libmedia/IAudioTrack.cpp b/media/libmedia/IAudioTrack.cpp
index abc202d..75b861b 100644
--- a/media/libmedia/IAudioTrack.cpp
+++ b/media/libmedia/IAudioTrack.cpp
@@ -18,7 +18,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 
 #include <media/IAudioTrack.h>
 
@@ -91,12 +91,6 @@
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnAudioTrack::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/media/libmedia/IMediaMetadataRetriever.cpp b/media/libmedia/IMediaMetadataRetriever.cpp
index 85b5944..397a55b 100644
--- a/media/libmedia/IMediaMetadataRetriever.cpp
+++ b/media/libmedia/IMediaMetadataRetriever.cpp
@@ -17,7 +17,7 @@
 
 #include <stdint.h>
 #include <sys/types.h>
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 #include <SkBitmap.h>
 #include <media/IMediaMetadataRetriever.h>
 
@@ -126,16 +126,10 @@
     }
 };
 
-IMPLEMENT_META_INTERFACE(MediaMetadataRetriever, "android.hardware.IMediaMetadataRetriever");
+IMPLEMENT_META_INTERFACE(MediaMetadataRetriever, "android.media.IMediaMetadataRetriever");
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnMediaMetadataRetriever::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
@@ -215,4 +209,3 @@
 // ----------------------------------------------------------------------------
 
 }; // namespace android
-
diff --git a/media/libmedia/IMediaPlayer.cpp b/media/libmedia/IMediaPlayer.cpp
index f18765a..5d9db10 100644
--- a/media/libmedia/IMediaPlayer.cpp
+++ b/media/libmedia/IMediaPlayer.cpp
@@ -18,7 +18,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 
 #include <media/IMediaPlayer.h>
 #include <ui/ISurface.h>
@@ -39,7 +39,10 @@
     RESET,
     SET_AUDIO_STREAM_TYPE,
     SET_LOOPING,
-    SET_VOLUME
+    SET_VOLUME,
+    INVOKE,
+    SET_METADATA_FILTER,
+    GET_METADATA,
 };
 
 class BpMediaPlayer: public BpInterface<IMediaPlayer>
@@ -170,18 +173,38 @@
         remote()->transact(SET_VOLUME, data, &reply);
         return reply.readInt32();
     }
+
+    status_t invoke(const Parcel& request, Parcel *reply)
+    { // Avoid doing any extra copy. The interface descriptor should
+      // have been set by MediaPlayer.java.
+        return remote()->transact(INVOKE, request, reply);
+    }
+
+    status_t setMetadataFilter(const Parcel& request)
+    {
+        Parcel reply;
+        // Avoid doing any extra copy of the request. The interface
+        // descriptor should have been set by MediaPlayer.java.
+        remote()->transact(SET_METADATA_FILTER, request, &reply);
+        return reply.readInt32();
+    }
+
+    status_t getMetadata(bool update_only, bool apply_filter, Parcel *reply)
+    {
+        Parcel request;
+        request.writeInterfaceToken(IMediaPlayer::getInterfaceDescriptor());
+        // TODO: Burning 2 ints for 2 boolean. Should probably use flags in an int here.
+        request.writeInt32(update_only);
+        request.writeInt32(apply_filter);
+        remote()->transact(GET_METADATA, request, reply);
+        return reply->readInt32();
+    }
 };
 
-IMPLEMENT_META_INTERFACE(MediaPlayer, "android.hardware.IMediaPlayer");
+IMPLEMENT_META_INTERFACE(MediaPlayer, "android.media.IMediaPlayer");
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnMediaPlayer::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
@@ -266,6 +289,24 @@
             reply->writeInt32(setVolume(data.readFloat(), data.readFloat()));
             return NO_ERROR;
         } break;
+        case INVOKE: {
+            CHECK_INTERFACE(IMediaPlayer, data, reply);
+            invoke(data, reply);
+            return NO_ERROR;
+        } break;
+        case SET_METADATA_FILTER: {
+            CHECK_INTERFACE(IMediaPlayer, data, reply);
+            reply->writeInt32(setMetadataFilter(data));
+            return NO_ERROR;
+        } break;
+        case GET_METADATA: {
+            CHECK_INTERFACE(IMediaPlayer, data, reply);
+            const status_t retcode = getMetadata(data.readInt32(), data.readInt32(), reply);
+            reply->setDataPosition(0);
+            reply->writeInt32(retcode);
+            reply->setDataPosition(0);
+            return NO_ERROR;
+        } break;
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
@@ -274,4 +315,3 @@
 // ----------------------------------------------------------------------------
 
 }; // namespace android
-
diff --git a/media/libmedia/IMediaPlayerClient.cpp b/media/libmedia/IMediaPlayerClient.cpp
index 65022cd..bf51829 100644
--- a/media/libmedia/IMediaPlayerClient.cpp
+++ b/media/libmedia/IMediaPlayerClient.cpp
@@ -16,8 +16,8 @@
 */
 
 #include <utils/RefBase.h>
-#include <utils/IInterface.h>
-#include <utils/Parcel.h>
+#include <binder/IInterface.h>
+#include <binder/Parcel.h>
 
 #include <media/IMediaPlayerClient.h>
 
@@ -46,16 +46,10 @@
     }
 };
 
-IMPLEMENT_META_INTERFACE(MediaPlayerClient, "android.hardware.IMediaPlayerClient");
+IMPLEMENT_META_INTERFACE(MediaPlayerClient, "android.media.IMediaPlayerClient");
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnMediaPlayerClient::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
@@ -74,4 +68,3 @@
 }
 
 }; // namespace android
-
diff --git a/media/libmedia/IMediaPlayerService.cpp b/media/libmedia/IMediaPlayerService.cpp
index 01cdb6c..8d2c360 100644
--- a/media/libmedia/IMediaPlayerService.cpp
+++ b/media/libmedia/IMediaPlayerService.cpp
@@ -17,11 +17,14 @@
 
 #include <stdint.h>
 #include <sys/types.h>
-#include <utils/Parcel.h>
 
-#include <utils/IMemory.h>
+#include <binder/Parcel.h>
+#include <binder/IMemory.h>
 #include <media/IMediaPlayerService.h>
 #include <media/IMediaRecorder.h>
+#include <media/IOMX.h>
+
+#include <utils/Errors.h>  // for status_t
 
 namespace android {
 
@@ -32,6 +35,7 @@
     DECODE_FD,
     CREATE_MEDIA_RECORDER,
     CREATE_METADATA_RETRIEVER,
+    CREATE_OMX,
 };
 
 class BpMediaPlayerService: public BpInterface<IMediaPlayerService>
@@ -109,18 +113,19 @@
         *pFormat = reply.readInt32();
         return interface_cast<IMemory>(reply.readStrongBinder());
     }
+
+    virtual sp<IOMX> createOMX() {
+        Parcel data, reply;
+        data.writeInterfaceToken(IMediaPlayerService::getInterfaceDescriptor());
+        remote()->transact(CREATE_OMX, data, &reply);
+        return interface_cast<IOMX>(reply.readStrongBinder());
+    }
 };
 
-IMPLEMENT_META_INTERFACE(MediaPlayerService, "android.hardware.IMediaPlayerService");
+IMPLEMENT_META_INTERFACE(MediaPlayerService, "android.media.IMediaPlayerService");
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-            LOGW("Call incorrectly routed to " #interface); \
-            return PERMISSION_DENIED; \
-        } } while (0)
-
 status_t BnMediaPlayerService::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
@@ -187,6 +192,12 @@
             reply->writeStrongBinder(retriever->asBinder());
             return NO_ERROR;
         } break;
+        case CREATE_OMX: {
+            CHECK_INTERFACE(IMediaPlayerService, data, reply);
+            sp<IOMX> omx = createOMX();
+            reply->writeStrongBinder(omx->asBinder());
+            return NO_ERROR;
+        } break;
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/media/libmedia/IMediaRecorder.cpp b/media/libmedia/IMediaRecorder.cpp
index 84d08c4..df7d301 100644
--- a/media/libmedia/IMediaRecorder.cpp
+++ b/media/libmedia/IMediaRecorder.cpp
@@ -18,7 +18,7 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "IMediaRecorder"
 #include <utils/Log.h>
-#include <utils/Parcel.h>
+#include <binder/Parcel.h>
 #include <ui/ISurface.h>
 #include <ui/ICamera.h>
 #include <media/IMediaPlayerClient.h>
@@ -264,16 +264,10 @@
     }
 };
 
-IMPLEMENT_META_INTERFACE(MediaRecorder, "android.hardware.IMediaRecorder");
+IMPLEMENT_META_INTERFACE(MediaRecorder, "android.media.IMediaRecorder");
 
 // ----------------------------------------------------------------------
 
-#define CHECK_INTERFACE(interface, data, reply) \
-    do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
-        LOGW("Call incorrectly routed to " #interface); \
-        return PERMISSION_DENIED; \
-    } } while (0)
-
 status_t BnMediaRecorder::onTransact(
                                      uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
diff --git a/media/libmedia/IOMX.cpp b/media/libmedia/IOMX.cpp
new file mode 100644
index 0000000..f2a657a
--- /dev/null
+++ b/media/libmedia/IOMX.cpp
@@ -0,0 +1,561 @@
+//#define LOG_NDEBUG 0
+#define LOG_TAG "IOMX"
+#include <utils/Log.h>
+
+#include <binder/IMemory.h>
+#include <binder/Parcel.h>
+#include <media/IOMX.h>
+
+namespace android {
+
+enum {
+    CONNECT = IBinder::FIRST_CALL_TRANSACTION,
+    LIST_NODES,
+    ALLOCATE_NODE,
+    FREE_NODE,
+    SEND_COMMAND,
+    GET_PARAMETER,
+    SET_PARAMETER,
+    USE_BUFFER,
+    ALLOC_BUFFER,
+    ALLOC_BUFFER_WITH_BACKUP,
+    FREE_BUFFER,
+    OBSERVE_NODE,
+    FILL_BUFFER,
+    EMPTY_BUFFER,
+    OBSERVER_ON_MSG,
+};
+
+static void *readVoidStar(const Parcel *parcel) {
+    // FIX if sizeof(void *) != sizeof(int32)
+    return (void *)parcel->readInt32();
+}
+
+static void writeVoidStar(void *x, Parcel *parcel) {
+    // FIX if sizeof(void *) != sizeof(int32)
+    parcel->writeInt32((int32_t)x);
+}
+
+class BpOMX : public BpInterface<IOMX> {
+public:
+    BpOMX(const sp<IBinder> &impl)
+        : BpInterface<IOMX>(impl) {
+    }
+
+#if IOMX_USES_SOCKETS
+    virtual status_t connect(int *sd) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        remote()->transact(CONNECT, data, &reply);
+
+        status_t err = reply.readInt32();
+        if (err == OK) {
+            *sd = dup(reply.readFileDescriptor());
+        } else {
+            *sd = -1;
+        }
+
+        return reply.readInt32();
+    }
+#endif
+
+    virtual status_t list_nodes(List<String8> *list) {
+        list->clear();
+
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        remote()->transact(LIST_NODES, data, &reply);
+
+        int32_t n = reply.readInt32();
+        for (int32_t i = 0; i < n; ++i) {
+            String8 s = reply.readString8();
+
+            list->push_back(s);
+        }
+
+        return OK;
+    }
+
+    virtual status_t allocate_node(const char *name, node_id *node) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        data.writeCString(name);
+        remote()->transact(ALLOCATE_NODE, data, &reply);
+
+        status_t err = reply.readInt32();
+        if (err == OK) {
+            *node = readVoidStar(&reply);
+        } else {
+            *node = 0;
+        }
+
+        return err;
+    }
+
+    virtual status_t free_node(node_id node) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        remote()->transact(FREE_NODE, data, &reply);
+
+        return reply.readInt32();
+    }
+
+    virtual status_t send_command(
+            node_id node, OMX_COMMANDTYPE cmd, OMX_S32 param) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        data.writeInt32(cmd);
+        data.writeInt32(param);
+        remote()->transact(SEND_COMMAND, data, &reply);
+
+        return reply.readInt32();
+    }
+
+    virtual status_t get_parameter(
+            node_id node, OMX_INDEXTYPE index,
+            void *params, size_t size) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        data.writeInt32(index);
+        data.writeInt32(size);
+        data.write(params, size);
+        remote()->transact(GET_PARAMETER, data, &reply);
+
+        status_t err = reply.readInt32();
+        if (err != OK) {
+            return err;
+        }
+
+        reply.read(params, size);
+
+        return OK;
+    }
+
+    virtual status_t set_parameter(
+            node_id node, OMX_INDEXTYPE index,
+            const void *params, size_t size) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        data.writeInt32(index);
+        data.writeInt32(size);
+        data.write(params, size);
+        remote()->transact(SET_PARAMETER, data, &reply);
+
+        return reply.readInt32();
+    }
+
+    virtual status_t use_buffer(
+            node_id node, OMX_U32 port_index, const sp<IMemory> &params,
+            buffer_id *buffer) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        data.writeInt32(port_index);
+        data.writeStrongBinder(params->asBinder());
+        remote()->transact(USE_BUFFER, data, &reply);
+
+        status_t err = reply.readInt32();
+        if (err != OK) {
+            *buffer = 0;
+
+            return err;
+        }
+
+        *buffer = readVoidStar(&reply);
+
+        return err;
+    }
+
+    virtual status_t allocate_buffer(
+            node_id node, OMX_U32 port_index, size_t size,
+            buffer_id *buffer) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        data.writeInt32(port_index);
+        data.writeInt32(size);
+        remote()->transact(ALLOC_BUFFER, data, &reply);
+
+        status_t err = reply.readInt32();
+        if (err != OK) {
+            *buffer = 0;
+
+            return err;
+        }
+
+        *buffer = readVoidStar(&reply);
+
+        return err;
+    }
+
+    virtual status_t allocate_buffer_with_backup(
+            node_id node, OMX_U32 port_index, const sp<IMemory> &params,
+            buffer_id *buffer) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        data.writeInt32(port_index);
+        data.writeStrongBinder(params->asBinder());
+        remote()->transact(ALLOC_BUFFER_WITH_BACKUP, data, &reply);
+
+        status_t err = reply.readInt32();
+        if (err != OK) {
+            *buffer = 0;
+
+            return err;
+        }
+
+        *buffer = readVoidStar(&reply);
+
+        return err;
+    }
+
+    virtual status_t free_buffer(
+            node_id node, OMX_U32 port_index, buffer_id buffer) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        data.writeInt32(port_index);
+        writeVoidStar(buffer, &data);
+        remote()->transact(FREE_BUFFER, data, &reply);
+
+        return reply.readInt32();
+    }
+
+#if !IOMX_USES_SOCKETS
+    virtual status_t observe_node(
+            node_id node, const sp<IOMXObserver> &observer) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        data.writeStrongBinder(observer->asBinder());
+        remote()->transact(OBSERVE_NODE, data, &reply);
+
+        return reply.readInt32();
+    }
+
+    virtual void fill_buffer(node_id node, buffer_id buffer) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        writeVoidStar(buffer, &data);
+        remote()->transact(FILL_BUFFER, data, &reply, IBinder::FLAG_ONEWAY);
+    }
+
+    virtual void empty_buffer(
+            node_id node,
+            buffer_id buffer,
+            OMX_U32 range_offset, OMX_U32 range_length,
+            OMX_U32 flags, OMX_TICKS timestamp) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
+        writeVoidStar(node, &data);
+        writeVoidStar(buffer, &data);
+        data.writeInt32(range_offset);
+        data.writeInt32(range_length);
+        data.writeInt32(flags);
+        data.writeInt64(timestamp);
+        remote()->transact(EMPTY_BUFFER, data, &reply, IBinder::FLAG_ONEWAY);
+    }
+#endif
+};
+
+IMPLEMENT_META_INTERFACE(OMX, "android.hardware.IOMX");
+
+////////////////////////////////////////////////////////////////////////////////
+
+#define CHECK_INTERFACE(interface, data, reply) \
+        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
+            LOGW("Call incorrectly routed to " #interface); \
+            return PERMISSION_DENIED; \
+        } } while (0)
+
+status_t BnOMX::onTransact(
+    uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
+    switch (code) {
+#if IOMX_USES_SOCKETS
+        case CONNECT:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            int s;
+            status_t err = connect(&s);
+            
+            reply->writeInt32(err);
+            if (err == OK) {
+                assert(s >= 0);
+                reply->writeDupFileDescriptor(s);
+                close(s);
+                s = -1;
+            } else {
+                assert(s == -1);
+            }
+
+            return NO_ERROR;
+        }
+#endif
+
+        case LIST_NODES:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            List<String8> list;
+            list_nodes(&list);
+
+            reply->writeInt32(list.size());
+            for (List<String8>::iterator it = list.begin();
+                 it != list.end(); ++it) {
+                reply->writeString8(*it);
+            }
+
+            return NO_ERROR;
+        }
+
+        case ALLOCATE_NODE:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node;
+            status_t err = allocate_node(data.readCString(), &node);
+            reply->writeInt32(err);
+            if (err == OK) {
+                writeVoidStar(node, reply);
+            }
+                
+            return NO_ERROR;
+        }
+
+        case FREE_NODE:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+
+            reply->writeInt32(free_node(node));
+                
+            return NO_ERROR;
+        }
+
+        case SEND_COMMAND:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+
+            OMX_COMMANDTYPE cmd =
+                static_cast<OMX_COMMANDTYPE>(data.readInt32());
+
+            OMX_S32 param = data.readInt32();
+            reply->writeInt32(send_command(node, cmd, param));
+
+            return NO_ERROR;
+        }
+
+        case GET_PARAMETER:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+            OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());
+
+            size_t size = data.readInt32();
+
+            // XXX I am not happy with this but Parcel::readInplace didn't work.
+            void *params = malloc(size);
+            data.read(params, size);
+
+            status_t err = get_parameter(node, index, params, size);
+
+            reply->writeInt32(err);
+
+            if (err == OK) {
+                reply->write(params, size);
+            }
+
+            free(params);
+            params = NULL;
+
+            return NO_ERROR;
+        }
+
+        case SET_PARAMETER:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+            OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());
+
+            size_t size = data.readInt32();
+            void *params = const_cast<void *>(data.readInplace(size));
+
+            reply->writeInt32(set_parameter(node, index, params, size));
+
+            return NO_ERROR;
+        }
+
+        case USE_BUFFER:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+            OMX_U32 port_index = data.readInt32();
+            sp<IMemory> params =
+                interface_cast<IMemory>(data.readStrongBinder());
+
+            buffer_id buffer;
+            status_t err = use_buffer(node, port_index, params, &buffer);
+            reply->writeInt32(err);
+
+            if (err == OK) {
+                writeVoidStar(buffer, reply);
+            }
+
+            return NO_ERROR;
+        }
+
+        case ALLOC_BUFFER:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+            OMX_U32 port_index = data.readInt32();
+            size_t size = data.readInt32();
+
+            buffer_id buffer;
+            status_t err = allocate_buffer(node, port_index, size, &buffer);
+            reply->writeInt32(err);
+
+            if (err == OK) {
+                writeVoidStar(buffer, reply);
+            }
+
+            return NO_ERROR;
+        }
+
+        case ALLOC_BUFFER_WITH_BACKUP:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+            OMX_U32 port_index = data.readInt32();
+            sp<IMemory> params =
+                interface_cast<IMemory>(data.readStrongBinder());
+
+            buffer_id buffer;
+            status_t err = allocate_buffer_with_backup(
+                    node, port_index, params, &buffer);
+
+            reply->writeInt32(err);
+
+            if (err == OK) {
+                writeVoidStar(buffer, reply);
+            }
+
+            return NO_ERROR;
+        }
+
+        case FREE_BUFFER:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+            OMX_U32 port_index = data.readInt32();
+            buffer_id buffer = readVoidStar(&data);
+            reply->writeInt32(free_buffer(node, port_index, buffer));
+
+            return NO_ERROR;
+        }
+
+#if !IOMX_USES_SOCKETS
+        case OBSERVE_NODE:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+            sp<IOMXObserver> observer =
+                interface_cast<IOMXObserver>(data.readStrongBinder());
+            reply->writeInt32(observe_node(node, observer));
+
+            return NO_ERROR;
+        }
+
+        case FILL_BUFFER:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+            buffer_id buffer = readVoidStar(&data);
+            fill_buffer(node, buffer);
+
+            return NO_ERROR;
+        }
+
+        case EMPTY_BUFFER:
+        {
+            CHECK_INTERFACE(IOMX, data, reply);
+
+            node_id node = readVoidStar(&data);
+            buffer_id buffer = readVoidStar(&data);
+            OMX_U32 range_offset = data.readInt32();
+            OMX_U32 range_length = data.readInt32();
+            OMX_U32 flags = data.readInt32();
+            OMX_TICKS timestamp = data.readInt64();
+
+            empty_buffer(
+                    node, buffer, range_offset, range_length,
+                    flags, timestamp);
+
+            return NO_ERROR;
+        }
+#endif
+
+        default:
+            return BBinder::onTransact(code, data, reply, flags);
+    }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+class BpOMXObserver : public BpInterface<IOMXObserver> {
+public:
+    BpOMXObserver(const sp<IBinder> &impl)
+        : BpInterface<IOMXObserver>(impl) {
+    }
+
+    virtual void on_message(const omx_message &msg) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IOMXObserver::getInterfaceDescriptor());
+        data.write(&msg, sizeof(msg));
+
+        remote()->transact(OBSERVER_ON_MSG, data, &reply, IBinder::FLAG_ONEWAY);
+    }
+};
+
+IMPLEMENT_META_INTERFACE(OMXObserver, "android.hardware.IOMXObserver");
+
+status_t BnOMXObserver::onTransact(
+    uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
+    switch (code) {
+        case OBSERVER_ON_MSG:
+        {
+            CHECK_INTERFACE(IOMXObserver, data, reply);
+
+            omx_message msg;
+            data.read(&msg, sizeof(msg));
+
+            // XXX Could use readInplace maybe?
+            on_message(msg);
+
+            return NO_ERROR;
+        }
+
+        default:
+            return BBinder::onTransact(code, data, reply, flags);
+    }
+}
+
+}  // namespace android
diff --git a/media/libmedia/JetPlayer.cpp b/media/libmedia/JetPlayer.cpp
index 586aacb..ee9e1d8 100644
--- a/media/libmedia/JetPlayer.cpp
+++ b/media/libmedia/JetPlayer.cpp
@@ -99,7 +99,7 @@
     mAudioTrack->set(AudioSystem::MUSIC,  //TODO parametrize this
             pLibConfig->sampleRate,
             1, // format = PCM 16bits per sample,
-            pLibConfig->numChannels,
+            (pLibConfig->numChannels == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
             mTrackBufferSize,
             0);
 
diff --git a/media/libmedia/Metadata.cpp b/media/libmedia/Metadata.cpp
new file mode 100644
index 0000000..35ec6b3
--- /dev/null
+++ b/media/libmedia/Metadata.cpp
@@ -0,0 +1,168 @@
+/*
+ * 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_NDEBUG 0
+#define LOG_TAG "Metadata"
+#include <utils/Log.h>
+
+#include <sys/types.h>
+#include <media/Metadata.h>
+#include <binder/Parcel.h>
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+
+// This file contains code to serialize Metadata triples (key, type,
+// value) into a parcel. The Parcel is destinated to be decoded by the
+// Metadata.java class.
+
+namespace {
+// All these constants below must be kept in sync with Metadata.java.
+enum MetadataId {
+    FIRST_SYSTEM_ID = 1,
+    LAST_SYSTEM_ID = 31,
+    FIRST_CUSTOM_ID = 8192
+};
+
+// Types
+enum Types {
+    STRING_VAL = 1,
+    INTEGER_VAL,
+    BOOLEAN_VAL,
+    LONG_VAL,
+    DOUBLE_VAL,
+    TIMED_TEXT_VAL,
+    DATE_VAL,
+    BYTE_ARRAY_VAL,
+};
+
+const size_t kRecordHeaderSize = 3 * sizeof(int32_t);
+const int32_t kMetaMarker = 0x4d455441;  // 'M' 'E' 'T' 'A'
+
+}  // anonymous namespace
+
+namespace android {
+namespace media {
+
+Metadata::Metadata(Parcel *p)
+    :mData(p),
+     mBegin(p->dataPosition()) { }
+
+Metadata::~Metadata() { }
+
+void Metadata::resetParcel()
+{
+    mData->setDataPosition(mBegin);
+}
+
+// Update the 4 bytes int at the beginning of the parcel which holds
+// the number of bytes written so far.
+void Metadata::updateLength()
+{
+    const size_t end = mData->dataPosition();
+
+    mData->setDataPosition(mBegin);
+    mData->writeInt32(end - mBegin);
+    mData->setDataPosition(end);
+}
+
+// Write the header. The java layer will look for the marker.
+bool Metadata::appendHeader()
+{
+    bool ok = true;
+
+    // Placeholder for the length of the metadata
+    ok = ok && mData->writeInt32(-1) == OK;
+    ok = ok && mData->writeInt32(kMetaMarker) == OK;
+    return ok;
+}
+
+bool Metadata::appendBool(int key, bool val)
+{
+    if (!checkKey(key)) {
+        return false;
+    }
+
+    const size_t begin = mData->dataPosition();
+    bool ok = true;
+
+    // 4 int32s: size, key, type, value.
+    ok = ok && mData->writeInt32(4 * sizeof(int32_t)) == OK;
+    ok = ok && mData->writeInt32(key) == OK;
+    ok = ok && mData->writeInt32(BOOLEAN_VAL) == OK;
+    ok = ok && mData->writeInt32(val ? 1 : 0) == OK;
+    if (!ok) {
+        mData->setDataPosition(begin);
+    }
+    return ok;
+}
+
+bool Metadata::appendInt32(int key, int32_t val)
+{
+    if (!checkKey(key)) {
+        return false;
+    }
+
+    const size_t begin = mData->dataPosition();
+    bool ok = true;
+
+    // 4 int32s: size, key, type, value.
+    ok = ok && mData->writeInt32(4 * sizeof(int32_t)) == OK;
+    ok = ok && mData->writeInt32(key) == OK;
+    ok = ok && mData->writeInt32(INTEGER_VAL) == OK;
+    ok = ok && mData->writeInt32(val) == OK;
+    if (!ok) {
+        mData->setDataPosition(begin);
+    }
+    return ok;
+}
+
+// Check the key (i.e metadata id) is valid if it is a system one.
+// Loop over all the exiting ones in the Parcel to check for duplicate
+// (not allowed).
+bool Metadata::checkKey(int key)
+{
+    if (key < FIRST_SYSTEM_ID ||
+        (LAST_SYSTEM_ID < key && key < FIRST_CUSTOM_ID)) {
+        LOGE("Bad key %d", key);
+        return false;
+    }
+    size_t curr = mData->dataPosition();
+    // Loop over the keys to check if it has been used already.
+    mData->setDataPosition(mBegin);
+
+    bool error = false;
+    size_t left = curr - mBegin;
+    while (left > 0) {
+        size_t pos = mData->dataPosition();
+        size_t size = mData->readInt32();
+        if (size < kRecordHeaderSize || size > left) {
+            error = true;
+            break;
+        }
+        if (mData->readInt32() == key) {
+            LOGE("Key exists already %d", key);
+            error = true;
+            break;
+        }
+        mData->setDataPosition(pos + size);
+        left -= size;
+    }
+    mData->setDataPosition(curr);
+    return !error;
+}
+
+}  // namespace android::media
+}  // namespace android
diff --git a/media/libmedia/ToneGenerator.cpp b/media/libmedia/ToneGenerator.cpp
index 5435da7..3ea64ae 100644
--- a/media/libmedia/ToneGenerator.cpp
+++ b/media/libmedia/ToneGenerator.cpp
@@ -1001,7 +1001,7 @@
 
    // Open audio track in mono, PCM 16bit, default sampling rate, default buffer size
     mpAudioTrack
-            = new AudioTrack(mStreamType, 0, AudioSystem::PCM_16_BIT, 1, 0, 0, audioCallback, this, 0);
+            = new AudioTrack(mStreamType, 0, AudioSystem::PCM_16_BIT, AudioSystem::CHANNEL_OUT_MONO, 0, 0, audioCallback, this, 0);
 
     if (mpAudioTrack == 0) {
         LOGE("AudioTrack allocation failed");
diff --git a/media/libmedia/mediametadataretriever.cpp b/media/libmedia/mediametadataretriever.cpp
index 09afc6c..d34a8ed 100644
--- a/media/libmedia/mediametadataretriever.cpp
+++ b/media/libmedia/mediametadataretriever.cpp
@@ -18,8 +18,8 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "MediaMetadataRetriever"
 
-#include <utils/IServiceManager.h>
-#include <utils/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/IPCThreadState.h>
 #include <media/mediametadataretriever.h>
 #include <media/IMediaPlayerService.h>
 #include <utils/Log.h>
diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp
index 24e3e6f..aeb43c5 100644
--- a/media/libmedia/mediaplayer.cpp
+++ b/media/libmedia/mediaplayer.cpp
@@ -24,13 +24,13 @@
 #include <unistd.h>
 #include <fcntl.h>
 
-#include <utils/IServiceManager.h>
-#include <utils/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/IPCThreadState.h>
 
 #include <media/mediaplayer.h>
 #include <media/AudioTrack.h>
 
-#include <utils/MemoryBase.h>
+#include <binder/MemoryBase.h>
 
 namespace android {
 
@@ -196,12 +196,47 @@
     return err;
 }
 
+status_t MediaPlayer::invoke(const Parcel& request, Parcel *reply)
+{
+    Mutex::Autolock _l(mLock);
+    if ((mPlayer != NULL) && ( mCurrentState & MEDIA_PLAYER_INITIALIZED ))
+    {
+         LOGV("invoke %d", request.dataSize());
+         return  mPlayer->invoke(request, reply);
+    }
+    LOGE("invoke failed: wrong state %X", mCurrentState);
+    return INVALID_OPERATION;
+}
+
+status_t MediaPlayer::setMetadataFilter(const Parcel& filter)
+{
+    LOGD("setMetadataFilter");
+    Mutex::Autolock lock(mLock);
+    if (mPlayer == NULL) {
+        return NO_INIT;
+    }
+    return mPlayer->setMetadataFilter(filter);
+}
+
+status_t MediaPlayer::getMetadata(bool update_only, bool apply_filter, Parcel *metadata)
+{
+    LOGD("getMetadata");
+    Mutex::Autolock lock(mLock);
+    if (mPlayer == NULL) {
+        return NO_INIT;
+    }
+    return mPlayer->getMetadata(update_only, apply_filter, metadata);
+}
+
 status_t MediaPlayer::setVideoSurface(const sp<Surface>& surface)
 {
     LOGV("setVideoSurface");
     Mutex::Autolock _l(mLock);
     if (mPlayer == 0) return NO_INIT;
-    return  mPlayer->setVideoSurface(surface->getISurface());
+    if (surface != NULL)
+        return  mPlayer->setVideoSurface(surface->getISurface());
+    else
+        return  mPlayer->setVideoSurface(NULL);
 }
 
 // must call with lock held
diff --git a/media/libmedia/mediarecorder.cpp b/media/libmedia/mediarecorder.cpp
index 5093f0e..6b63931 100644
--- a/media/libmedia/mediarecorder.cpp
+++ b/media/libmedia/mediarecorder.cpp
@@ -20,7 +20,7 @@
 #include <utils/Log.h>
 #include <ui/Surface.h>
 #include <media/mediarecorder.h>
-#include <utils/IServiceManager.h>
+#include <binder/IServiceManager.h>
 #include <utils/String8.h>
 #include <media/IMediaPlayerService.h>
 #include <media/IMediaRecorder.h>
diff --git a/media/libmediaplayerservice/Android.mk b/media/libmediaplayerservice/Android.mk
index f7f2490..f74ef3a 100644
--- a/media/libmediaplayerservice/Android.mk
+++ b/media/libmediaplayerservice/Android.mk
@@ -10,6 +10,7 @@
     MediaRecorderClient.cpp \
     MediaPlayerService.cpp \
     MetadataRetrieverClient.cpp \
+    TestPlayerStub.cpp \
     VorbisPlayer.cpp \
     MidiFile.cpp
 
@@ -20,6 +21,7 @@
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
     libutils \
+	libbinder \
     libvorbisidec \
     libsonivox \
     libopencore_player \
@@ -27,10 +29,27 @@
     libmedia \
     libandroid_runtime
 
+ifneq ($(TARGET_SIMULATOR),true)
+LOCAL_SHARED_LIBRARIES += libdl
+endif
+
 LOCAL_C_INCLUDES := external/tremor/Tremor \
-    $(call include-path-for, graphics corecg)
+	$(call include-path-for, graphics corecg) \
+	$(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include
 
 LOCAL_MODULE:= libmediaplayerservice
 
+ifeq ($(BUILD_WITH_STAGEFRIGHT),true)
+    LOCAL_SRC_FILES += StagefrightPlayer.cpp
+
+    LOCAL_SHARED_LIBRARIES += \
+	libstagefright        \
+	libstagefright_omx
+
+    LOCAL_C_INCLUDES += $(TOP)/frameworks/base/media/libstagefright/omx
+
+    LOCAL_CFLAGS += -DBUILD_WITH_STAGEFRIGHT -DUSE_STAGEFRIGHT
+endif
+
 include $(BUILD_SHARED_LIBRARY)
 
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index 31eecac..1d960c5 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -27,18 +27,27 @@
 #include <unistd.h>
 
 #include <string.h>
+
 #include <cutils/atomic.h>
+#include <cutils/properties.h> // for property_get
+
+#include <utils/misc.h>
 
 #include <android_runtime/ActivityManager.h>
-#include <utils/IPCThreadState.h>
-#include <utils/IServiceManager.h>
-#include <utils/MemoryHeapBase.h>
-#include <utils/MemoryBase.h>
+
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/MemoryHeapBase.h>
+#include <binder/MemoryBase.h>
+#include <utils/Errors.h>  // for status_t
+#include <utils/String8.h>
+#include <utils/Vector.h>
 #include <cutils/properties.h>
 
 #include <media/MediaPlayerInterface.h>
 #include <media/mediarecorder.h>
 #include <media/MediaMetadataRetrieverInterface.h>
+#include <media/Metadata.h>
 #include <media/AudioTrack.h>
 
 #include "MediaRecorderClient.h"
@@ -48,6 +57,19 @@
 #include "MidiFile.h"
 #include "VorbisPlayer.h"
 #include <media/PVPlayer.h>
+#include "TestPlayerStub.h"
+
+#if USE_STAGEFRIGHT
+#include "StagefrightPlayer.h"
+#endif
+
+#ifdef BUILD_WITH_STAGEFRIGHT
+#include <OMX.h>
+#else
+#include <media/IOMX.h>
+#endif
+
+
 
 /* desktop Linux needs a little help with gettid() */
 #if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
@@ -61,6 +83,111 @@
 #undef __KERNEL__
 #endif
 
+namespace {
+using android::media::Metadata;
+using android::status_t;
+using android::OK;
+using android::BAD_VALUE;
+using android::NOT_ENOUGH_DATA;
+using android::Parcel;
+
+// Max number of entries in the filter.
+const int kMaxFilterSize = 64;  // I pulled that out of thin air.
+
+// FIXME: Move all the metadata related function in the Metadata.cpp
+
+
+// Unmarshall a filter from a Parcel.
+// Filter format in a parcel:
+//
+//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// |                       number of entries (n)                   |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// |                       metadata type 1                         |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// |                       metadata type 2                         |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+//  ....
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// |                       metadata type n                         |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+//
+// @param p Parcel that should start with a filter.
+// @param[out] filter On exit contains the list of metadata type to be
+//                    filtered.
+// @param[out] status On exit contains the status code to be returned.
+// @return true if the parcel starts with a valid filter.
+bool unmarshallFilter(const Parcel& p,
+                      Metadata::Filter *filter,
+                      status_t *status)
+{
+    int32_t val;
+    if (p.readInt32(&val) != OK)
+    {
+        LOGE("Failed to read filter's length");
+        *status = NOT_ENOUGH_DATA;
+        return false;
+    }
+
+    if( val > kMaxFilterSize || val < 0)
+    {
+        LOGE("Invalid filter len %d", val);
+        *status = BAD_VALUE;
+        return false;
+    }
+
+    const size_t num = val;
+
+    filter->clear();
+    filter->setCapacity(num);
+
+    size_t size = num * sizeof(Metadata::Type);
+
+
+    if (p.dataAvail() < size)
+    {
+        LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
+        *status = NOT_ENOUGH_DATA;
+        return false;
+    }
+
+    const Metadata::Type *data =
+            static_cast<const Metadata::Type*>(p.readInplace(size));
+
+    if (NULL == data)
+    {
+        LOGE("Filter had no data");
+        *status = BAD_VALUE;
+        return false;
+    }
+
+    // TODO: The stl impl of vector would be more efficient here
+    // because it degenerates into a memcpy on pod types. Try to
+    // replace later or use stl::set.
+    for (size_t i = 0; i < num; ++i)
+    {
+        filter->add(*data);
+        ++data;
+    }
+    *status = OK;
+    return true;
+}
+
+// @param filter Of metadata type.
+// @param val To be searched.
+// @return true if a match was found.
+bool findMetadata(const Metadata::Filter& filter, const int32_t val)
+{
+    // Deal with empty and ANY right away
+    if (filter.isEmpty()) return false;
+    if (filter[0] == Metadata::kAny) return true;
+
+    return filter.indexOf(val) >= 0;
+}
+
+}  // anonymous namespace
+
 
 namespace android {
 
@@ -70,6 +197,10 @@
     const player_type playertype;
 } extmap;
 extmap FILE_EXTS [] =  {
+#if USE_STAGEFRIGHT
+        {".mp4", STAGEFRIGHT_PLAYER},
+        {".3gp", STAGEFRIGHT_PLAYER},
+#endif
         {".mid", SONIVOX_PLAYER},
         {".midi", SONIVOX_PLAYER},
         {".smf", SONIVOX_PLAYER},
@@ -105,7 +236,11 @@
 
 sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
 {
+#ifndef NO_OPENCORE
     sp<MediaRecorderClient> recorder = new MediaRecorderClient(pid);
+#else
+    sp<MediaRecorderClient> recorder = NULL;
+#endif
     LOGV("Create new media recorder client from pid %d", pid);
     return recorder;
 }
@@ -151,6 +286,14 @@
     return c;
 }
 
+sp<IOMX> MediaPlayerService::createOMX() {
+#ifdef BUILD_WITH_STAGEFRIGHT
+    return new OMX;
+#else
+    return NULL;
+#endif
+}
+
 status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
 {
     const size_t SIZE = 256;
@@ -457,6 +600,7 @@
         p = mPlayer;
     }
     mClient.clear();
+
     mPlayer.clear();
 
     // clear the notification to prevent callbacks to dead client
@@ -504,12 +648,19 @@
         EAS_Shutdown(easdata);
     }
 
+#if USE_STAGEFRIGHT
+    return STAGEFRIGHT_PLAYER;
+#endif
+
     // Fall through to PV
     return PV_PLAYER;
 }
 
 static player_type getPlayerType(const char* url)
 {
+    if (TestPlayerStub::canBeUsed(url)) {
+        return TEST_PLAYER;
+    }
 
     // use MidiFile for MIDI extensions
     int lenURL = strlen(url);
@@ -523,6 +674,10 @@
         }
     }
 
+#if USE_STAGEFRIGHT
+    return STAGEFRIGHT_PLAYER;
+#endif
+
     // Fall through to PV
     return PV_PLAYER;
 }
@@ -532,10 +687,12 @@
 {
     sp<MediaPlayerBase> p;
     switch (playerType) {
+#ifndef NO_OPENCORE
         case PV_PLAYER:
             LOGV(" create PVPlayer");
             p = new PVPlayer();
             break;
+#endif
         case SONIVOX_PLAYER:
             LOGV(" create MidiFile");
             p = new MidiFile();
@@ -544,6 +701,21 @@
             LOGV(" create VorbisPlayer");
             p = new VorbisPlayer();
             break;
+#if USE_STAGEFRIGHT
+        case STAGEFRIGHT_PLAYER:
+            LOGV(" create StagefrightPlayer");
+            p = new StagefrightPlayer;
+            break;
+#else
+        case STAGEFRIGHT_PLAYER:
+            LOG_ALWAYS_FATAL(
+                    "Should not be here, stagefright player not enabled.");
+            break;
+#endif
+        case TEST_PLAYER:
+            LOGV("Create Test Player stub");
+            p = new TestPlayerStub();
+            break;
     }
     if (p != NULL) {
         if (p->initCheck() == NO_ERROR) {
@@ -608,7 +780,11 @@
         // now set data source
         LOGV(" setDataSource");
         mStatus = p->setDataSource(url);
-        if (mStatus == NO_ERROR) mPlayer = p;
+        if (mStatus == NO_ERROR) {
+            mPlayer = p;
+        } else {
+            LOGE("  error: %d", mStatus);
+        }
         return mStatus;
     }
 }
@@ -665,6 +841,73 @@
     return p->setVideoSurface(surface);
 }
 
+status_t MediaPlayerService::Client::invoke(const Parcel& request,
+                                            Parcel *reply)
+{
+    sp<MediaPlayerBase> p = getPlayer();
+    if (p == NULL) return UNKNOWN_ERROR;
+    return p->invoke(request, reply);
+}
+
+// This call doesn't need to access the native player.
+status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
+{
+    status_t status;
+    media::Metadata::Filter allow, drop;
+
+    if (unmarshallFilter(filter, &allow, &status) &&
+        unmarshallFilter(filter, &drop, &status)) {
+        Mutex::Autolock lock(mLock);
+
+        mMetadataAllow = allow;
+        mMetadataDrop = drop;
+    }
+    return status;
+}
+
+status_t MediaPlayerService::Client::getMetadata(
+        bool update_only, bool apply_filter, Parcel *reply)
+{
+    sp<MediaPlayerBase> player = getPlayer();
+    if (player == 0) return UNKNOWN_ERROR;
+
+    status_t status;
+    // Placeholder for the return code, updated by the caller.
+    reply->writeInt32(-1);
+
+    media::Metadata::Filter ids;
+
+    // We don't block notifications while we fetch the data. We clear
+    // mMetadataUpdated first so we don't lose notifications happening
+    // during the rest of this call.
+    {
+        Mutex::Autolock lock(mLock);
+        if (update_only) {
+            ids = mMetadataUpdated;
+        }
+        mMetadataUpdated.clear();
+    }
+
+    media::Metadata metadata(reply);
+
+    metadata.appendHeader();
+    status = player->getMetadata(ids, reply);
+
+    if (status != OK) {
+        metadata.resetParcel();
+        LOGE("getMetadata failed %d", status);
+        return status;
+    }
+
+    // FIXME: Implement filtering on the result. Not critical since
+    // filtering takes place on the update notifications already. This
+    // would be when all the metadata are fetch and a filter is set.
+
+    // Everything is fine, update the metadata length.
+    metadata.updateLength();
+    return OK;
+}
+
 status_t MediaPlayerService::Client::prepareAsync()
 {
     LOGV("[%d] prepareAsync", mConnId);
@@ -784,13 +1027,51 @@
     return NO_ERROR;
 }
 
+
 void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
 {
     Client* client = static_cast<Client*>(cookie);
+
+    if (MEDIA_INFO == msg &&
+        MEDIA_INFO_METADATA_UPDATE == ext1) {
+        const media::Metadata::Type metadata_type = ext2;
+
+        if(client->shouldDropMetadata(metadata_type)) {
+            return;
+        }
+
+        // Update the list of metadata that have changed. getMetadata
+        // also access mMetadataUpdated and clears it.
+        client->addNewMetadataUpdate(metadata_type);
+    }
     LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
     client->mClient->notify(msg, ext1, ext2);
 }
 
+
+bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
+{
+    Mutex::Autolock lock(mLock);
+
+    if (findMetadata(mMetadataDrop, code)) {
+        return true;
+    }
+
+    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
+        return false;
+    } else {
+        return true;
+    }
+}
+
+
+void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
+    Mutex::Autolock lock(mLock);
+    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
+        mMetadataUpdated.add(metadata_type);
+    }
+}
+
 #if CALLBACK_ANTAGONIZER
 const int Antagonizer::interval = 10000; // 10 msecs
 
@@ -927,7 +1208,8 @@
 #undef LOG_TAG
 #define LOG_TAG "AudioSink"
 MediaPlayerService::AudioOutput::AudioOutput()
-{
+    : mCallback(NULL),
+      mCallbackCookie(NULL) {
     mTrack = 0;
     mStreamType = AudioSystem::MUSIC;
     mLeftVolume = 1.0;
@@ -997,8 +1279,13 @@
     return mMsecsPerFrame;
 }
 
-status_t MediaPlayerService::AudioOutput::open(uint32_t sampleRate, int channelCount, int format, int bufferCount)
+status_t MediaPlayerService::AudioOutput::open(
+        uint32_t sampleRate, int channelCount, int format, int bufferCount,
+        AudioCallback cb, void *cookie)
 {
+    mCallback = cb;
+    mCallbackCookie = cookie;
+
     // Check argument "bufferCount" against the mininum buffer count
     if (bufferCount < mMinBufferCount) {
         LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
@@ -1019,7 +1306,27 @@
     }
 
     frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
-    AudioTrack *t = new AudioTrack(mStreamType, sampleRate, format, channelCount, frameCount);
+
+    AudioTrack *t;
+    if (mCallback != NULL) {
+        t = new AudioTrack(
+                mStreamType,
+                sampleRate,
+                format,
+                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
+                frameCount,
+                0 /* flags */,
+                CallbackWrapper,
+                this);
+    } else {
+        t = new AudioTrack(
+                mStreamType,
+                sampleRate,
+                format,
+                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
+                frameCount);
+    }
+
     if ((t == 0) || (t->initCheck() != NO_ERROR)) {
         LOGE("Unable to create audio track");
         delete t;
@@ -1045,6 +1352,8 @@
 
 ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
 {
+    LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
+
     //LOGV("write(%p, %u)", buffer, size);
     if (mTrack) return mTrack->write(buffer, size);
     return NO_INIT;
@@ -1085,6 +1394,20 @@
     }
 }
 
+// static
+void MediaPlayerService::AudioOutput::CallbackWrapper(
+        int event, void *cookie, void *info) {
+    if (event != AudioTrack::EVENT_MORE_DATA) {
+        return;
+    }
+
+    AudioOutput *me = (AudioOutput *)cookie;
+    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
+
+    (*me->mCallback)(
+            me, buffer->raw, buffer->size, me->mCallbackCookie);
+}
+
 #undef LOG_TAG
 #define LOG_TAG "AudioCache"
 MediaPlayerService::AudioCache::AudioCache(const char* name) :
@@ -1105,8 +1428,14 @@
     return mMsecsPerFrame;
 }
 
-status_t MediaPlayerService::AudioCache::open(uint32_t sampleRate, int channelCount, int format, int bufferCount)
+status_t MediaPlayerService::AudioCache::open(
+        uint32_t sampleRate, int channelCount, int format, int bufferCount,
+        AudioCallback cb, void *cookie)
 {
+    if (cb != NULL) {
+        return UNKNOWN_ERROR;  // TODO: implement this.
+    }
+
     LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
     if (mHeap->getHeapID() < 0) return NO_INIT;
     mSampleRate = sampleRate;
@@ -1171,4 +1500,4 @@
     p->mSignal.signal();
 }
 
-}; // namespace android
+} // namespace android
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
index f138886..a4be414 100644
--- a/media/libmediaplayerservice/MediaPlayerService.h
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -18,17 +18,23 @@
 #ifndef ANDROID_MEDIAPLAYERSERVICE_H
 #define ANDROID_MEDIAPLAYERSERVICE_H
 
-#include <utils.h>
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 #include <utils/KeyedVector.h>
+#include <utils/Vector.h>
 #include <ui/SurfaceComposerClient.h>
 
 #include <media/IMediaPlayerService.h>
 #include <media/MediaPlayerInterface.h>
+#include <media/Metadata.h>
 
 namespace android {
 
 class IMediaRecorder;
 class IMediaMetadataRetriever;
+class IOMX;
 
 #define CALLBACK_ANTAGONIZER 0
 #if CALLBACK_ANTAGONIZER
@@ -69,7 +75,12 @@
         virtual ssize_t         frameSize() const;
         virtual uint32_t        latency() const;
         virtual float           msecsPerFrame() const;
-        virtual status_t        open(uint32_t sampleRate, int channelCount, int format, int bufferCount=4);
+
+        virtual status_t        open(
+                uint32_t sampleRate, int channelCount,
+                int format, int bufferCount,
+                AudioCallback cb, void *cookie);
+
         virtual void            start();
         virtual ssize_t         write(const void* buffer, size_t size);
         virtual void            stop();
@@ -84,8 +95,12 @@
         static int              getMinBufferCount();
     private:
         static void             setMinBufferCount();
+        static void             CallbackWrapper(
+                int event, void *me, void *info);
 
         AudioTrack*             mTrack;
+        AudioCallback           mCallback;
+        void *                  mCallbackCookie;
         int                     mStreamType;
         float                   mLeftVolume;
         float                   mRightVolume;
@@ -113,7 +128,12 @@
         virtual ssize_t         frameSize() const { return ssize_t(mChannelCount * ((mFormat == AudioSystem::PCM_16_BIT)?sizeof(int16_t):sizeof(u_int8_t))); }
         virtual uint32_t        latency() const;
         virtual float           msecsPerFrame() const;
-        virtual status_t        open(uint32_t sampleRate, int channelCount, int format, int bufferCount=1);
+
+        virtual status_t        open(
+                uint32_t sampleRate, int channelCount, int format,
+                int bufferCount = 1,
+                AudioCallback cb = NULL, void *cookie = NULL);
+
         virtual void            start() {}
         virtual ssize_t         write(const void* buffer, size_t size);
         virtual void            stop() {}
@@ -140,7 +160,7 @@
         sp<MemoryHeapBase>  mHeap;
         float               mMsecsPerFrame;
         uint16_t            mChannelCount;
-        uint16_t			mFormat;
+        uint16_t            mFormat;
         ssize_t             mFrameCount;
         uint32_t            mSampleRate;
         uint32_t            mSize;
@@ -160,11 +180,13 @@
     virtual sp<IMediaPlayer>    create(pid_t pid, const sp<IMediaPlayerClient>& client, int fd, int64_t offset, int64_t length);
     virtual sp<IMemory>         decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
     virtual sp<IMemory>         decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
+    virtual sp<IOMX>            createOMX();
 
     virtual status_t            dump(int fd, const Vector<String16>& args);
 
             void                removeClient(wp<Client> client);
 
+
 private:
 
     class Client : public BnMediaPlayer {
@@ -184,6 +206,11 @@
         virtual status_t        setAudioStreamType(int type);
         virtual status_t        setLooping(int loop);
         virtual status_t        setVolume(float leftVolume, float rightVolume);
+        virtual status_t        invoke(const Parcel& request, Parcel *reply);
+        virtual status_t        setMetadataFilter(const Parcel& filter);
+        virtual status_t        getMetadata(bool update_only,
+                                            bool apply_filter,
+                                            Parcel *reply);
 
         sp<MediaPlayerBase>     createPlayer(player_type playerType);
                 status_t        setDataSource(const char *url);
@@ -206,6 +233,18 @@
 
         sp<MediaPlayerBase>     getPlayer() const { Mutex::Autolock lock(mLock); return mPlayer; }
 
+
+
+        // @param type Of the metadata to be tested.
+        // @return true if the metadata should be dropped according to
+        //              the filters.
+        bool shouldDropMetadata(media::Metadata::Type type) const;
+
+        // Add a new element to the set of metadata updated. Noop if
+        // the element exists already.
+        // @param type Of the metadata to be recorded.
+        void addNewMetadataUpdate(media::Metadata::Type type);
+
         mutable     Mutex                       mLock;
                     sp<MediaPlayerBase>         mPlayer;
                     sp<MediaPlayerService>      mService;
@@ -215,6 +254,17 @@
                     status_t                    mStatus;
                     bool                        mLoop;
                     int32_t                     mConnId;
+
+        // Metadata filters.
+        media::Metadata::Filter mMetadataAllow;  // protected by mLock
+        media::Metadata::Filter mMetadataDrop;  // protected by mLock
+
+        // Metadata updated. For each MEDIA_INFO_METADATA_UPDATE
+        // notification we try to update mMetadataUpdated which is a
+        // set: no duplicate.
+        // getMetadata clears this set.
+        media::Metadata::Filter mMetadataUpdated;  // protected by mLock
+
 #if CALLBACK_ANTAGONIZER
                     Antagonizer*                mAntagonizer;
 #endif
@@ -235,4 +285,3 @@
 }; // namespace android
 
 #endif // ANDROID_MEDIAPLAYERSERVICE_H
-
diff --git a/media/libmediaplayerservice/MediaRecorderClient.cpp b/media/libmediaplayerservice/MediaRecorderClient.cpp
index 8bc410c..e54f20d 100644
--- a/media/libmediaplayerservice/MediaRecorderClient.cpp
+++ b/media/libmediaplayerservice/MediaRecorderClient.cpp
@@ -25,10 +25,10 @@
 #include <string.h>
 #include <cutils/atomic.h>
 #include <android_runtime/ActivityManager.h>
-#include <utils/IPCThreadState.h>
-#include <utils/IServiceManager.h>
-#include <utils/MemoryHeapBase.h>
-#include <utils/MemoryBase.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/MemoryHeapBase.h>
+#include <binder/MemoryBase.h>
 #include <media/PVMediaRecorder.h>
 #include <utils/String16.h>
 
diff --git a/media/libmediaplayerservice/MetadataRetrieverClient.cpp b/media/libmediaplayerservice/MetadataRetrieverClient.cpp
index a320bd5..ba8d9a8 100644
--- a/media/libmediaplayerservice/MetadataRetrieverClient.cpp
+++ b/media/libmediaplayerservice/MetadataRetrieverClient.cpp
@@ -26,10 +26,10 @@
 
 #include <string.h>
 #include <cutils/atomic.h>
-#include <utils/MemoryDealer.h>
+#include <binder/MemoryDealer.h>
 #include <android_runtime/ActivityManager.h>
-#include <utils/IPCThreadState.h>
-#include <utils/IServiceManager.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
 #include <media/MediaMetadataRetrieverInterface.h>
 #include <media/MediaPlayerInterface.h>
 #include <media/PVMetadataRetriever.h>
@@ -49,7 +49,11 @@
     mThumbnail = NULL;
     mAlbumArt = NULL;
 
+#ifndef NO_OPENCORE
     mRetriever = new PVMetadataRetriever();
+#else
+    mRetriever = NULL;
+#endif
     if (mRetriever == NULL) {
         LOGE("failed to initialize the retriever");
     }
diff --git a/media/libmediaplayerservice/MetadataRetrieverClient.h b/media/libmediaplayerservice/MetadataRetrieverClient.h
index ce29c98..88d50bf 100644
--- a/media/libmediaplayerservice/MetadataRetrieverClient.h
+++ b/media/libmediaplayerservice/MetadataRetrieverClient.h
@@ -18,9 +18,12 @@
 #ifndef ANDROID_MEDIAMETADATARETRIEVERSERVICE_H
 #define ANDROID_MEDIAMETADATARETRIEVERSERVICE_H
 
-#include <utils.h>
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 #include <utils/KeyedVector.h>
-#include <utils/IMemory.h>
+#include <binder/IMemory.h>
 
 #include <media/MediaMetadataRetrieverInterface.h>
 
diff --git a/media/libmediaplayerservice/MidiFile.h b/media/libmediaplayerservice/MidiFile.h
index 302f1cf..25d4a1b 100644
--- a/media/libmediaplayerservice/MidiFile.h
+++ b/media/libmediaplayerservice/MidiFile.h
@@ -46,6 +46,9 @@
     virtual status_t    reset();
     virtual status_t    setLooping(int loop);
     virtual player_type playerType() { return SONIVOX_PLAYER; }
+    virtual status_t    invoke(const Parcel& request, Parcel *reply) {
+        return INVALID_OPERATION;
+    }
 
 private:
             status_t    createOutputTrack();
@@ -74,4 +77,3 @@
 }; // namespace android
 
 #endif // ANDROID_MIDIFILE_H
-
diff --git a/media/libmediaplayerservice/StagefrightPlayer.cpp b/media/libmediaplayerservice/StagefrightPlayer.cpp
new file mode 100644
index 0000000..9a06d13
--- /dev/null
+++ b/media/libmediaplayerservice/StagefrightPlayer.cpp
@@ -0,0 +1,208 @@
+//#define LOG_NDEBUG 0
+#define LOG_TAG "StagefrightPlayer"
+#include <utils/Log.h>
+
+#include "StagefrightPlayer.h"
+#include <media/stagefright/MediaPlayerImpl.h>
+
+namespace android {
+
+StagefrightPlayer::StagefrightPlayer()
+    : mPlayer(NULL) {
+    LOGV("StagefrightPlayer");
+}
+
+StagefrightPlayer::~StagefrightPlayer() {
+    LOGV("~StagefrightPlayer");
+    reset();
+    LOGV("~StagefrightPlayer done.");
+}
+
+status_t StagefrightPlayer::initCheck() {
+    LOGV("initCheck");
+    return OK;
+}
+
+status_t StagefrightPlayer::setDataSource(const char *url) {
+    LOGV("setDataSource('%s')", url);
+
+    reset();
+    mPlayer = new MediaPlayerImpl(url);
+
+    status_t err = mPlayer->initCheck();
+    if (err != OK) {
+        delete mPlayer;
+        mPlayer = NULL;
+    } else {
+        mPlayer->setAudioSink(mAudioSink);
+    }
+
+    return err;
+}
+
+status_t StagefrightPlayer::setDataSource(int fd, int64_t offset, int64_t length) {
+    LOGV("setDataSource(%d, %lld, %lld)", fd, offset, length);
+
+    reset();
+    mPlayer = new MediaPlayerImpl(fd, offset, length);
+
+    status_t err = mPlayer->initCheck();
+    if (err != OK) {
+        delete mPlayer;
+        mPlayer = NULL;
+    } else {
+        mPlayer->setAudioSink(mAudioSink);
+    }
+
+    return err;
+}
+
+status_t StagefrightPlayer::setVideoSurface(const sp<ISurface> &surface) {
+    LOGV("setVideoSurface");
+
+    if (mPlayer == NULL) {
+        return NO_INIT;
+    }
+
+    mPlayer->setISurface(surface);
+
+    return OK;
+}
+
+status_t StagefrightPlayer::prepare() {
+    LOGV("prepare");
+
+    if (mPlayer == NULL) {
+        return NO_INIT;
+    }
+
+    sendEvent(
+            MEDIA_SET_VIDEO_SIZE,
+            mPlayer->getWidth(), mPlayer->getHeight());
+
+    return OK;
+}
+
+status_t StagefrightPlayer::prepareAsync() {
+    LOGV("prepareAsync");
+
+    status_t err = prepare();
+
+    if (err != OK) {
+        return err;
+    }
+
+    sendEvent(MEDIA_PREPARED);
+
+    return OK;
+}
+
+status_t StagefrightPlayer::start() {
+    LOGV("start");
+
+    if (mPlayer == NULL) {
+        return NO_INIT;
+    }
+
+    mPlayer->play();
+
+    return OK;
+}
+
+status_t StagefrightPlayer::stop() {
+    LOGV("stop");
+
+    if (mPlayer == NULL) {
+        return NO_INIT;
+    }
+
+    reset();
+
+    return OK;
+}
+
+status_t StagefrightPlayer::pause() {
+    LOGV("pause");
+
+    if (mPlayer == NULL) {
+        return NO_INIT;
+    }
+
+    mPlayer->pause();
+
+    return OK;
+}
+
+bool StagefrightPlayer::isPlaying() {
+    LOGV("isPlaying");
+    return mPlayer != NULL && mPlayer->isPlaying();
+}
+
+status_t StagefrightPlayer::seekTo(int msec) {
+    LOGV("seekTo");
+
+    if (mPlayer == NULL) {
+        return NO_INIT;
+    }
+
+    status_t err = mPlayer->seekTo((int64_t)msec * 1000);
+
+    sendEvent(MEDIA_SEEK_COMPLETE);
+
+    return err;
+}
+
+status_t StagefrightPlayer::getCurrentPosition(int *msec) {
+    LOGV("getCurrentPosition");
+
+    if (mPlayer == NULL) {
+        return NO_INIT;
+    }
+
+    *msec = mPlayer->getPosition() / 1000;
+    return OK;
+}
+
+status_t StagefrightPlayer::getDuration(int *msec) {
+    LOGV("getDuration");
+
+    if (mPlayer == NULL) {
+        return NO_INIT;
+    }
+
+    *msec = mPlayer->getDuration() / 1000;
+    return OK;
+}
+
+status_t StagefrightPlayer::reset() {
+    LOGV("reset");
+
+    delete mPlayer;
+    mPlayer = NULL;
+
+    return OK;
+}
+
+status_t StagefrightPlayer::setLooping(int loop) {
+    LOGV("setLooping");
+    return UNKNOWN_ERROR;
+}
+
+player_type StagefrightPlayer::playerType() {
+    LOGV("playerType");
+    return STAGEFRIGHT_PLAYER;
+}
+
+status_t StagefrightPlayer::invoke(const Parcel &request, Parcel *reply) {
+    return INVALID_OPERATION;
+}
+
+void StagefrightPlayer::setAudioSink(const sp<AudioSink> &audioSink) {
+    MediaPlayerInterface::setAudioSink(audioSink);
+
+    if (mPlayer != NULL) {
+        mPlayer->setAudioSink(audioSink);
+    }
+}
+
+}  // namespace android
diff --git a/media/libmediaplayerservice/StagefrightPlayer.h b/media/libmediaplayerservice/StagefrightPlayer.h
new file mode 100644
index 0000000..f214872c
--- /dev/null
+++ b/media/libmediaplayerservice/StagefrightPlayer.h
@@ -0,0 +1,60 @@
+/*
+**
+** Copyright 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.
+*/
+
+#ifndef ANDROID_STAGEFRIGHTPLAYER_H
+#define ANDROID_STAGEFRIGHTPLAYER_H
+
+#include <media/MediaPlayerInterface.h>
+
+namespace android {
+
+class MediaPlayerImpl;
+
+class StagefrightPlayer : public MediaPlayerInterface {
+public:
+    StagefrightPlayer();
+    virtual ~StagefrightPlayer();
+
+    virtual status_t initCheck();
+    virtual status_t setDataSource(const char *url);
+    virtual status_t setDataSource(int fd, int64_t offset, int64_t length);
+    virtual status_t setVideoSurface(const sp<ISurface> &surface);
+    virtual status_t prepare();
+    virtual status_t prepareAsync();
+    virtual status_t start();
+    virtual status_t stop();
+    virtual status_t pause();
+    virtual bool isPlaying();
+    virtual status_t seekTo(int msec);
+    virtual status_t getCurrentPosition(int *msec);
+    virtual status_t getDuration(int *msec);
+    virtual status_t reset();
+    virtual status_t setLooping(int loop);
+    virtual player_type playerType();
+    virtual status_t invoke(const Parcel &request, Parcel *reply);
+    virtual void setAudioSink(const sp<AudioSink> &audioSink);
+
+private:
+    MediaPlayerImpl *mPlayer;
+
+    StagefrightPlayer(const StagefrightPlayer &);
+    StagefrightPlayer &operator=(const StagefrightPlayer &);
+};
+
+}  // namespace android
+
+#endif  // ANDROID_STAGEFRIGHTPLAYER_H
diff --git a/media/libmediaplayerservice/TestPlayerStub.cpp b/media/libmediaplayerservice/TestPlayerStub.cpp
new file mode 100644
index 0000000..8627708
--- /dev/null
+++ b/media/libmediaplayerservice/TestPlayerStub.cpp
@@ -0,0 +1,196 @@
+/*
+ * 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_NDEBUG 0
+#define LOG_TAG "TestPlayerStub"
+#include "utils/Log.h"
+
+#include "TestPlayerStub.h"
+
+#include <dlfcn.h>  // for dlopen/dlclose
+#include <stdlib.h>
+#include <string.h>
+#include <cutils/properties.h>
+#include <utils/Errors.h>  // for status_t
+
+#include "media/MediaPlayerInterface.h"
+
+
+namespace {
+using android::status_t;
+using android::MediaPlayerBase;
+
+const char *kTestUrlScheme = "test:";
+const char *kUrlParam = "url=";
+
+const char *kBuildTypePropName = "ro.build.type";
+const char *kEngBuild = "eng";
+const char *kTestBuild = "test";
+
+// @return true if the current build is 'eng' or 'test'.
+bool isTestBuild()
+{
+    char prop[PROPERTY_VALUE_MAX] = { '\0', };
+
+    property_get(kBuildTypePropName, prop, '\0');
+    return strcmp(prop, kEngBuild) == 0 || strcmp(prop, kTestBuild) == 0;
+}
+
+// @return true if the url scheme is 'test:'
+bool isTestUrl(const char *url)
+{
+    return url && strncmp(url, kTestUrlScheme, strlen(kTestUrlScheme)) == 0;
+}
+
+}  // anonymous namespace
+
+namespace android {
+
+TestPlayerStub::TestPlayerStub()
+    :mUrl(NULL), mFilename(NULL), mContentUrl(NULL),
+     mHandle(NULL), mNewPlayer(NULL), mDeletePlayer(NULL),
+     mPlayer(NULL) { }
+
+TestPlayerStub::~TestPlayerStub()
+{
+    resetInternal();
+}
+
+status_t TestPlayerStub::initCheck()
+{
+    return isTestBuild() ? OK : INVALID_OPERATION;
+}
+
+// Parse mUrl to get:
+// * The library to be dlopened.
+// * The url to be passed to the real setDataSource impl.
+//
+// mUrl is expected to be in following format:
+//
+// test:<name of the .so>?url=<url for setDataSource>
+//
+// The value of the url parameter is treated as a string (no
+// unescaping of illegal charaters).
+status_t TestPlayerStub::parseUrl()
+{
+    if (strlen(mUrl) < strlen(kTestUrlScheme)) {
+        resetInternal();
+        return BAD_VALUE;
+    }
+
+    char *i = mUrl + strlen(kTestUrlScheme);
+
+    mFilename = i;
+
+    while (*i != '\0' && *i != '?') {
+        ++i;
+    }
+
+    if (*i == '\0' || strncmp(i + 1, kUrlParam, strlen(kUrlParam)) != 0) {
+        resetInternal();
+        return BAD_VALUE;
+    }
+    *i = '\0';  // replace '?' to nul-terminate mFilename
+
+    mContentUrl = i + 1 + strlen(kUrlParam);
+    return OK;
+}
+
+// Load the dynamic library.
+// Create the test player.
+// Call setDataSource on the test player with the url in param.
+status_t TestPlayerStub::setDataSource(const char *url)
+{
+    if (!isTestUrl(url) || NULL != mHandle) {
+        return INVALID_OPERATION;
+    }
+
+    mUrl = strdup(url);
+
+    status_t status = parseUrl();
+
+    if (OK != status) {
+        resetInternal();
+        return status;
+    }
+
+    ::dlerror();  // Clears any pending error.
+
+    // Load the test player from the url. dlopen will fail if the lib
+    // is not there. dls are under /system/lib
+    // None of the entry points should be NULL.
+    mHandle = ::dlopen(mFilename, RTLD_NOW | RTLD_GLOBAL);
+    if (!mHandle) {
+        LOGE("dlopen failed: %s", ::dlerror());
+        resetInternal();
+        return UNKNOWN_ERROR;
+    }
+
+    // Load the 2 entry points to create and delete instances.
+    const char *err;
+    mNewPlayer = reinterpret_cast<NEW_PLAYER>(dlsym(mHandle,
+                                                    "newPlayer"));
+    err = ::dlerror();
+    if (err || mNewPlayer == NULL) {
+        // if err is NULL the string <null> is inserted in the logs =>
+        // mNewPlayer was NULL.
+        LOGE("dlsym for newPlayer failed %s", err);
+        resetInternal();
+        return UNKNOWN_ERROR;
+    }
+
+    mDeletePlayer = reinterpret_cast<DELETE_PLAYER>(dlsym(mHandle,
+                                                          "deletePlayer"));
+    err = ::dlerror();
+    if (err || mDeletePlayer == NULL) {
+        LOGE("dlsym for deletePlayer failed %s", err);
+        resetInternal();
+        return UNKNOWN_ERROR;
+    }
+
+    mPlayer = (*mNewPlayer)();
+    return mPlayer->setDataSource(mContentUrl);
+}
+
+// Internal cleanup.
+status_t TestPlayerStub::resetInternal()
+{
+    if(mUrl) {
+        free(mUrl);
+        mUrl = NULL;
+    }
+    mFilename = NULL;
+    mContentUrl = NULL;
+
+    if (mPlayer) {
+        LOG_ASSERT(mDeletePlayer != NULL);
+        (*mDeletePlayer)(mPlayer);
+        mPlayer = NULL;
+    }
+
+    if (mHandle) {
+        ::dlclose(mHandle);
+        mHandle = NULL;
+    }
+    return OK;
+}
+
+/* static */ bool TestPlayerStub::canBeUsed(const char *url)
+{
+    return isTestBuild() && isTestUrl(url);
+}
+
+}  // namespace android
diff --git a/media/libmediaplayerservice/TestPlayerStub.h b/media/libmediaplayerservice/TestPlayerStub.h
new file mode 100644
index 0000000..80d53a8
--- /dev/null
+++ b/media/libmediaplayerservice/TestPlayerStub.h
@@ -0,0 +1,119 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_FRAMEWORKS_BASE_MEDIA_LIBMEDIAPLAYERSERVICE_TESTPLAYERSTUB_H__
+#define ANDROID_FRAMEWORKS_BASE_MEDIA_LIBMEDIAPLAYERSERVICE_TESTPLAYERSTUB_H__
+
+#include <media/MediaPlayerInterface.h>
+#include <utils/Errors.h>
+
+namespace android {
+class MediaPlayerBase;  // in media/MediaPlayerInterface.h
+
+// Wrapper around a test media player that gets dynamically loaded.
+//
+// The URL passed to setDataSource has this format:
+//
+//   test:<name of the .so>?url=<url for the real setDataSource impl.>
+//
+// e.g:
+//   test:invoke_test_media_player.so?url=http://youtube.com/
+//   test:invoke_test_media_player.so?url=speedtest
+//
+// TestPlayerStub::setDataSource loads the library in the test url. 2
+// entry points with C linkage are expected. One to create the test
+// player and one to destroy it.
+//
+// extern "C" android::MediaPlayerBase* newPlayer();
+// extern "C" android::status_t deletePlayer(android::MediaPlayerBase *p);
+//
+// Once the test player has been loaded, its setDataSource
+// implementation is called with the value of the 'url' parameter.
+//
+// typical usage in a java test:
+// ============================
+//
+//  MediaPlayer p = new MediaPlayer();
+//  p.setDataSource("test:invoke_mock_media_player.so?url=http://youtube.com");
+//  p.prepare();
+//  ...
+//  p.release();
+
+class TestPlayerStub : public MediaPlayerInterface {
+  public:
+    typedef MediaPlayerBase* (*NEW_PLAYER)();
+    typedef status_t (*DELETE_PLAYER)(MediaPlayerBase *);
+
+    TestPlayerStub();
+    virtual ~TestPlayerStub();
+
+    // Called right after the constructor. Check if the current build
+    // allows test players.
+    virtual status_t initCheck();
+
+    // @param url Should be a test url. See class comment.
+    virtual status_t setDataSource(const char* url);
+
+    // Test player for a file descriptor source is not supported.
+    virtual status_t setDataSource(int, int64_t, int64_t)  {
+        return INVALID_OPERATION;
+    }
+
+
+    // All the methods below wrap the mPlayer instance.
+    virtual status_t setVideoSurface(const android::sp<android::ISurface>& s)  {
+        return mPlayer->setVideoSurface(s);
+    }
+    virtual status_t prepare() {return mPlayer->prepare();}
+    virtual status_t prepareAsync()  {return mPlayer->prepareAsync();}
+    virtual status_t start()  {return mPlayer->start();}
+    virtual status_t stop()  {return mPlayer->stop();}
+    virtual status_t pause()  {return mPlayer->pause();}
+    virtual bool isPlaying() {return mPlayer->isPlaying();}
+    virtual status_t seekTo(int msec) {return mPlayer->seekTo(msec);}
+    virtual status_t getCurrentPosition(int *p)  {
+        return mPlayer->getCurrentPosition(p);
+    }
+    virtual status_t getDuration(int *d)  {return mPlayer->getDuration(d);}
+    virtual status_t reset() {return mPlayer->reset();}
+    virtual status_t setLooping(int b)  {return mPlayer->setLooping(b);}
+    virtual player_type playerType() {return mPlayer->playerType();}
+    virtual status_t invoke(const android::Parcel& in, android::Parcel *out) {
+        return mPlayer->invoke(in, out);
+    }
+
+
+    // @return true if the current build is 'eng' or 'test' and the
+    //              url's scheme is 'test:'
+    static bool canBeUsed(const char *url);
+
+  private:
+    // Release the player, dlclose the library.
+    status_t resetInternal();
+    status_t parseUrl();
+
+    char *mUrl;                // test:foo.so?url=http://bar
+    char *mFilename;           // foo.so
+    char *mContentUrl;         // http://bar
+    void *mHandle;             // returned by dlopen
+    NEW_PLAYER    mNewPlayer;
+    DELETE_PLAYER mDeletePlayer;
+    MediaPlayerBase *mPlayer;  // wrapped player
+};
+
+}  // namespace android
+
+#endif
diff --git a/media/libmediaplayerservice/VorbisPlayer.h b/media/libmediaplayerservice/VorbisPlayer.h
index c30dc1b..4024654 100644
--- a/media/libmediaplayerservice/VorbisPlayer.h
+++ b/media/libmediaplayerservice/VorbisPlayer.h
@@ -53,6 +53,7 @@
     virtual status_t    reset();
     virtual status_t    setLooping(int loop);
     virtual player_type playerType() { return VORBIS_PLAYER; }
+    virtual status_t    invoke(const Parcel& request, Parcel *reply) {return INVALID_OPERATION;}
 
 private:
             status_t    setdatasource(const char *path, int fd, int64_t offset, int64_t length);
@@ -88,4 +89,3 @@
 }; // namespace android
 
 #endif // ANDROID_VORBISPLAYER_H
-
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
new file mode 100644
index 0000000..5944d9c
--- /dev/null
+++ b/media/libstagefright/Android.mk
@@ -0,0 +1,60 @@
+ifeq ($(BUILD_WITH_STAGEFRIGHT),true)
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:=                 \
+        CachingDataSource.cpp     \
+        DataSource.cpp            \
+        FileSource.cpp            \
+        HTTPDataSource.cpp        \
+        HTTPStream.cpp            \
+        MP3Extractor.cpp          \
+        MPEG4Extractor.cpp        \
+        MPEG4Writer.cpp           \
+        MediaBuffer.cpp           \
+        MediaBufferGroup.cpp      \
+        MediaExtractor.cpp        \
+        MediaPlayerImpl.cpp       \
+        MediaSource.cpp           \
+        MetaData.cpp              \
+        MmapSource.cpp            \
+        QComHardwareRenderer.cpp  \
+        SampleTable.cpp           \
+        ShoutcastSource.cpp       \
+        SoftwareRenderer.cpp      \
+        SurfaceRenderer.cpp       \
+        TimeSource.cpp            \
+        TimedEventQueue.cpp       \
+        Utils.cpp                 \
+        AudioPlayer.cpp           \
+        ESDS.cpp                  \
+        OMXClient.cpp             \
+        OMXDecoder.cpp            \
+        string.cpp
+
+LOCAL_C_INCLUDES:= \
+        $(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include \
+        $(TOP)/external/opencore/android
+
+LOCAL_SHARED_LIBRARIES := \
+        libbinder         \
+        libmedia          \
+        libutils          \
+        libcutils         \
+        libui
+
+ifeq ($(TARGET_OS)-$(TARGET_SIMULATOR),linux-true)
+        LOCAL_LDLIBS += -lpthread
+endif
+
+LOCAL_CFLAGS += -Wno-multichar
+
+LOCAL_PRELINK_MODULE:= false
+
+LOCAL_MODULE:= libstagefright
+
+include $(BUILD_SHARED_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
+endif
diff --git a/media/libstagefright/AudioPlayer.cpp b/media/libstagefright/AudioPlayer.cpp
new file mode 100644
index 0000000..17c72b9
--- /dev/null
+++ b/media/libstagefright/AudioPlayer.cpp
@@ -0,0 +1,285 @@
+/*
+ * 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.
+ */
+
+#undef NDEBUG
+#include <assert.h>
+
+#define LOG_TAG "AudioPlayer"
+#include <utils/Log.h>
+
+#include <media/AudioTrack.h>
+#include <media/stagefright/AudioPlayer.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
+
+namespace android {
+
+AudioPlayer::AudioPlayer(const sp<MediaPlayerBase::AudioSink> &audioSink)
+    : mSource(NULL),
+      mAudioTrack(NULL),
+      mInputBuffer(NULL),
+      mSampleRate(0),
+      mLatencyUs(0),
+      mFrameSize(0),
+      mNumFramesPlayed(0),
+      mPositionTimeMediaUs(-1),
+      mPositionTimeRealUs(-1),
+      mSeeking(false),
+      mStarted(false),
+      mAudioSink(audioSink) {
+}
+
+AudioPlayer::~AudioPlayer() {
+    if (mStarted) {
+        stop();
+    }
+}
+
+void AudioPlayer::setSource(MediaSource *source) {
+    assert(mSource == NULL);
+    mSource = source;
+}
+
+void AudioPlayer::start() {
+    assert(!mStarted);
+    assert(mSource != NULL);
+
+    status_t err = mSource->start();
+    assert(err == OK);
+
+    sp<MetaData> format = mSource->getFormat();
+    const char *mime;
+    bool success = format->findCString(kKeyMIMEType, &mime);
+    assert(success);
+    assert(!strcasecmp(mime, "audio/raw"));
+
+    success = format->findInt32(kKeySampleRate, &mSampleRate);
+    assert(success);
+
+    int32_t numChannels;
+    success = format->findInt32(kKeyChannelCount, &numChannels);
+    assert(success);
+
+    if (mAudioSink.get() != NULL) {
+        status_t err = mAudioSink->open(
+                mSampleRate, numChannels, AudioSystem::PCM_16_BIT,
+                DEFAULT_AUDIOSINK_BUFFERCOUNT,
+                &AudioPlayer::AudioSinkCallback, this);
+        assert(err == OK);
+
+        mLatencyUs = (int64_t)mAudioSink->latency() * 1000;
+        mFrameSize = mAudioSink->frameSize();
+
+        mAudioSink->start();
+    } else {
+        mAudioTrack = new AudioTrack(
+                AudioSystem::MUSIC, mSampleRate, AudioSystem::PCM_16_BIT,
+                numChannels, 8192, 0, &AudioCallback, this, 0);
+
+        assert(mAudioTrack->initCheck() == OK);
+
+        mLatencyUs = (int64_t)mAudioTrack->latency() * 1000;
+        mFrameSize = mAudioTrack->frameSize();
+
+        mAudioTrack->start();
+    }
+
+    mStarted = true;
+}
+
+void AudioPlayer::pause() {
+    assert(mStarted);
+
+    if (mAudioSink.get() != NULL) {
+        mAudioSink->pause();
+    } else {
+        mAudioTrack->stop();
+    }
+}
+
+void AudioPlayer::resume() {
+    assert(mStarted);
+
+    if (mAudioSink.get() != NULL) {
+        mAudioSink->start();
+    } else {
+        mAudioTrack->start();
+    }
+}
+
+void AudioPlayer::stop() {
+    assert(mStarted);
+
+    if (mAudioSink.get() != NULL) {
+        mAudioSink->stop();
+    } else {
+        mAudioTrack->stop();
+
+        delete mAudioTrack;
+        mAudioTrack = NULL;
+    }
+    
+    // Make sure to release any buffer we hold onto so that the
+    // source is able to stop().
+    if (mInputBuffer != NULL) {
+        LOGI("AudioPlayer releasing input buffer.");
+
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    mSource->stop();
+    
+    mNumFramesPlayed = 0;
+    mPositionTimeMediaUs = -1;
+    mPositionTimeRealUs = -1;
+    mSeeking = false;
+    mStarted = false;
+}
+
+// static
+void AudioPlayer::AudioCallback(int event, void *user, void *info) {
+    static_cast<AudioPlayer *>(user)->AudioCallback(event, info);
+}
+
+// static
+void AudioPlayer::AudioSinkCallback(
+        MediaPlayerBase::AudioSink *audioSink,
+        void *buffer, size_t size, void *cookie) {
+    AudioPlayer *me = (AudioPlayer *)cookie;
+
+    me->fillBuffer(buffer, size);
+}
+
+void AudioPlayer::AudioCallback(int event, void *info) {
+    if (event != AudioTrack::EVENT_MORE_DATA) {
+        return;
+    }
+
+    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
+    fillBuffer(buffer->raw, buffer->size);
+}
+
+void AudioPlayer::fillBuffer(void *data, size_t size) {
+    if (mNumFramesPlayed == 0) {
+        LOGI("AudioCallback");
+    }
+
+    size_t size_done = 0;
+    size_t size_remaining = size;
+    while (size_remaining > 0) {
+        MediaSource::ReadOptions options;
+
+        {
+            Mutex::Autolock autoLock(mLock);
+
+            if (mSeeking) {
+                options.setSeekTo(mSeekTimeUs);
+
+                if (mInputBuffer != NULL) {
+                    mInputBuffer->release();
+                    mInputBuffer = NULL;
+                }
+                mSeeking = false;
+            }
+        }
+
+        if (mInputBuffer == NULL) {
+            status_t err = mSource->read(&mInputBuffer, &options);
+
+            assert((err == OK && mInputBuffer != NULL)
+                   || (err != OK && mInputBuffer == NULL));
+
+            if (err != OK) {
+                memset((char *)data + size_done, 0, size_remaining);
+                break;
+            }
+
+            int32_t units, scale;
+            bool success =
+                mInputBuffer->meta_data()->findInt32(kKeyTimeUnits, &units);
+            success = success &&
+                mInputBuffer->meta_data()->findInt32(kKeyTimeScale, &scale);
+            assert(success);
+
+            Mutex::Autolock autoLock(mLock);
+            mPositionTimeMediaUs = (int64_t)units * 1000000 / scale;
+            mPositionTimeRealUs =
+                ((mNumFramesPlayed + size_done / 4) * 1000000) / mSampleRate; // XXX
+        }
+
+        if (mInputBuffer->range_length() == 0) {
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+
+            continue;
+        }
+
+        size_t copy = size_remaining;
+        if (copy > mInputBuffer->range_length()) {
+            copy = mInputBuffer->range_length();
+        }
+
+        memcpy((char *)data + size_done,
+               (const char *)mInputBuffer->data() + mInputBuffer->range_offset(),
+               copy);
+
+        mInputBuffer->set_range(mInputBuffer->range_offset() + copy,
+                                mInputBuffer->range_length() - copy);
+                    
+        size_done += copy;
+        size_remaining -= copy;
+    }
+
+    Mutex::Autolock autoLock(mLock);
+    mNumFramesPlayed += size / mFrameSize;
+}
+
+int64_t AudioPlayer::getRealTimeUs() {
+    Mutex::Autolock autoLock(mLock);
+    return getRealTimeUsLocked();
+}
+
+int64_t AudioPlayer::getRealTimeUsLocked() const {
+    return -mLatencyUs + (mNumFramesPlayed * 1000000) / mSampleRate;
+}
+
+int64_t AudioPlayer::getMediaTimeUs() {
+    Mutex::Autolock autoLock(mLock);
+
+    return mPositionTimeMediaUs + (getRealTimeUsLocked() - mPositionTimeRealUs);
+}
+
+bool AudioPlayer::getMediaTimeMapping(
+        int64_t *realtime_us, int64_t *mediatime_us) {
+    Mutex::Autolock autoLock(mLock);
+
+    *realtime_us = mPositionTimeRealUs;
+    *mediatime_us = mPositionTimeMediaUs;
+
+    return mPositionTimeRealUs != -1 || mPositionTimeMediaUs != -1;
+}
+
+status_t AudioPlayer::seekTo(int64_t time_us) {
+    Mutex::Autolock autoLock(mLock);
+
+    mSeeking = true;
+    mSeekTimeUs = time_us;
+
+    return OK;
+}
+
+}
diff --git a/media/libstagefright/CachingDataSource.cpp b/media/libstagefright/CachingDataSource.cpp
new file mode 100644
index 0000000..0fd71d5
--- /dev/null
+++ b/media/libstagefright/CachingDataSource.cpp
@@ -0,0 +1,162 @@
+/*
+ * 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.
+ */
+
+#include <media/stagefright/CachingDataSource.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <stdlib.h>
+#include <string.h>
+
+namespace android {
+
+CachingDataSource::CachingDataSource(
+        DataSource *source, size_t pageSize, int numPages)
+    : mSource(source),
+      mData(malloc(pageSize * numPages)),
+      mPageSize(pageSize),
+      mFirst(NULL),
+      mLast(NULL) {
+    for (int i = 0; i < numPages; ++i) {
+        Page *page = new Page;
+        page->mPrev = mLast;
+        page->mNext = NULL;
+
+        if (mLast == NULL) {
+            mFirst = page;
+        } else {
+            mLast->mNext = page;
+        }
+
+        mLast = page;
+
+        page->mOffset = -1;
+        page->mLength = 0;
+        page->mData = (char *)mData + mPageSize * i;
+    }
+}
+
+CachingDataSource::~CachingDataSource() {
+    Page *page = mFirst;
+    while (page != NULL) {
+        Page *next = page->mNext;
+        delete page;
+        page = next;
+    }
+    mFirst = mLast = NULL;
+
+    free(mData);
+    mData = NULL;
+
+    delete mSource;
+    mSource = NULL;
+}
+
+status_t CachingDataSource::InitCheck() const {
+    return OK;
+}
+
+ssize_t CachingDataSource::read_at(off_t offset, void *data, size_t size) {
+    Mutex::Autolock autoLock(mLock);
+
+    size_t total = 0;
+    while (size > 0) {
+        Page *page = mFirst;
+        while (page != NULL) {
+            if (page->mOffset >= 0 && offset >= page->mOffset
+                && offset < page->mOffset + page->mLength) {
+                break;
+            }
+            page = page->mNext;
+        }
+
+        if (page == NULL) {
+            page = allocate_page();
+            page->mOffset = offset - offset % mPageSize;
+            ssize_t n = mSource->read_at(page->mOffset, page->mData, mPageSize);
+            if (n < 0) {
+                page->mLength = 0;
+            } else {
+                page->mLength = (size_t)n;
+            }
+            mFirst->mPrev = page;
+            page->mNext = mFirst;
+            page->mPrev = NULL;
+            mFirst = page;
+
+            if (n < 0) {
+                return n;
+            }
+
+            if (offset >= page->mOffset + page->mLength) {
+                break;
+            }
+        } else {
+            // Move "page" to the front in LRU order.
+            if (page->mNext != NULL) {
+                page->mNext->mPrev = page->mPrev;
+            } else {
+                mLast = page->mPrev;
+            }
+
+            if (page->mPrev != NULL) {
+                page->mPrev->mNext = page->mNext;
+            } else {
+                mFirst = page->mNext;
+            }
+
+            mFirst->mPrev = page;
+            page->mNext = mFirst;
+            page->mPrev = NULL;
+            mFirst = page;
+        }
+
+        size_t copy = page->mLength - (offset - page->mOffset);
+        if (copy > size) {
+            copy = size;
+        }
+        memcpy(data,(const char *)page->mData + (offset - page->mOffset),
+               copy);
+
+        total += copy;
+
+        if (page->mLength < mPageSize) {
+            // This was the final page. There is no more data beyond it.
+            break;
+        }
+
+        offset += copy;
+        size -= copy;
+        data = (char *)data + copy;
+    }
+
+    return total;
+}
+
+CachingDataSource::Page *CachingDataSource::allocate_page() {
+    // The last page is the least recently used, i.e. oldest.
+
+    Page *page = mLast;
+
+    page->mPrev->mNext = NULL;
+    mLast = page->mPrev;
+    page->mPrev = NULL;
+
+    return page;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/CameraSource.cpp b/media/libstagefright/CameraSource.cpp
new file mode 100644
index 0000000..ee12873
--- /dev/null
+++ b/media/libstagefright/CameraSource.cpp
@@ -0,0 +1,226 @@
+/*
+ * 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.
+ */
+
+#include <sys/time.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <OMX_Component.h>
+
+#include <binder/IServiceManager.h>
+#include <media/stagefright/CameraSource.h>
+#include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/MetaData.h>
+#include <ui/ICameraClient.h>
+#include <ui/ICameraService.h>
+#include <ui/Overlay.h>
+#include <utils/String16.h>
+
+namespace android {
+
+class CameraBuffer : public MediaBuffer {
+public:
+    CameraBuffer(const sp<IMemory> &frame)
+        : MediaBuffer(frame->pointer(), frame->size()),
+          mFrame(frame) {
+    }
+
+    sp<IMemory> releaseFrame() {
+        sp<IMemory> frame = mFrame;
+        mFrame.clear();
+        return frame;
+    }
+
+private:
+    sp<IMemory> mFrame;
+};
+
+class CameraSourceClient : public BnCameraClient {
+public:
+    CameraSourceClient()
+        : mSource(NULL) {
+    }
+
+    virtual void notifyCallback(int32_t msgType, int32_t ext1, int32_t ext2) {
+        assert(mSource != NULL);
+        mSource->notifyCallback(msgType, ext1, ext2);
+    }
+
+    virtual void dataCallback(int32_t msgType, const sp<IMemory> &data) {
+        assert(mSource != NULL);
+        mSource->dataCallback(msgType, data);
+    }
+
+    void setCameraSource(CameraSource *source) {
+        mSource = source;
+    }
+
+private:
+    CameraSource *mSource;
+};
+
+class DummySurface : public BnSurface {
+public:
+    DummySurface() {}
+
+    virtual status_t registerBuffers(const BufferHeap &buffers) {
+        return OK;
+    }
+
+    virtual void postBuffer(ssize_t offset) {
+    }
+
+    virtual void unregisterBuffers() {
+    }
+    
+    virtual sp<OverlayRef> createOverlay(
+            uint32_t w, uint32_t h, int32_t format) {
+        return NULL;
+    }
+};
+
+// static
+CameraSource *CameraSource::Create() {
+    sp<IServiceManager> sm = defaultServiceManager();
+
+    sp<ICameraService> service =
+        interface_cast<ICameraService>(
+                sm->getService(String16("media.camera")));
+
+    sp<CameraSourceClient> client = new CameraSourceClient;
+    sp<ICamera> camera = service->connect(client);
+
+    CameraSource *source = new CameraSource(camera, client);
+    client->setCameraSource(source);
+
+    return source;
+}
+
+CameraSource::CameraSource(
+        const sp<ICamera> &camera, const sp<ICameraClient> &client)
+    : mCamera(camera),
+      mCameraClient(client),
+      mNumFrames(0),
+      mStarted(false) {
+    printf("params: \"%s\"\n", mCamera->getParameters().string());
+}
+
+CameraSource::~CameraSource() {
+    if (mStarted) {
+        stop();
+    }
+
+    mCamera->disconnect();
+}
+
+status_t CameraSource::start(MetaData *) {
+    assert(!mStarted);
+
+    status_t err = mCamera->lock();
+    assert(err == OK);
+
+    err = mCamera->setPreviewDisplay(new DummySurface);
+    assert(err == OK);
+    mCamera->setPreviewCallbackFlag(1);
+    mCamera->startPreview();
+    assert(err == OK);
+
+    mStarted = true;
+
+    return OK;
+}
+
+status_t CameraSource::stop() {
+    assert(mStarted);
+
+    mCamera->stopPreview();
+    mCamera->unlock();
+
+    mStarted = false;
+
+    return OK;
+}
+
+sp<MetaData> CameraSource::getFormat() {
+    sp<MetaData> meta = new MetaData;
+    meta->setCString(kKeyMIMEType, "video/raw");
+    meta->setInt32(kKeyColorFormat, OMX_COLOR_FormatYUV420SemiPlanar);
+    meta->setInt32(kKeyWidth, 480);
+    meta->setInt32(kKeyHeight, 320);
+
+    return meta;
+}
+
+status_t CameraSource::read(
+        MediaBuffer **buffer, const ReadOptions *options) {
+    assert(mStarted);
+
+    *buffer = NULL;
+
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        return ERROR_UNSUPPORTED;
+    }
+
+    sp<IMemory> frame;
+
+    {
+        Mutex::Autolock autoLock(mLock);
+        while (mFrames.empty()) {
+            mFrameAvailableCondition.wait(mLock);
+        }
+
+        frame = *mFrames.begin();
+        mFrames.erase(mFrames.begin());
+    }
+
+    int count = mNumFrames++;
+
+    *buffer = new CameraBuffer(frame);
+
+    (*buffer)->meta_data()->clear();
+    (*buffer)->meta_data()->setInt32(kKeyTimeScale, 15);
+    (*buffer)->meta_data()->setInt32(kKeyTimeUnits, count);
+
+    (*buffer)->add_ref();
+    (*buffer)->setObserver(this);
+
+    return OK;
+}
+
+void CameraSource::notifyCallback(int32_t msgType, int32_t ext1, int32_t ext2) {
+    printf("notifyCallback %d, %d, %d\n", msgType, ext1, ext2);
+}
+
+void CameraSource::dataCallback(int32_t msgType, const sp<IMemory> &data) {
+    Mutex::Autolock autoLock(mLock);
+
+    mFrames.push_back(data);
+    mFrameAvailableCondition.signal();
+}
+
+void CameraSource::signalBufferReturned(MediaBuffer *_buffer) {
+    CameraBuffer *buffer = static_cast<CameraBuffer *>(_buffer);
+
+    mCamera->releaseRecordingFrame(buffer->releaseFrame());
+
+    buffer->setObserver(NULL);
+    buffer->release();
+    buffer = NULL;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/DataSource.cpp b/media/libstagefright/DataSource.cpp
new file mode 100644
index 0000000..6e6b43d
--- /dev/null
+++ b/media/libstagefright/DataSource.cpp
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/MP3Extractor.h>
+#include <media/stagefright/MPEG4Extractor.h>
+#include <utils/String8.h>
+
+namespace android {
+
+status_t DataSource::getSize(off_t *size) {
+    *size = 0;
+
+    return ERROR_UNSUPPORTED;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+Mutex DataSource::gSnifferMutex;
+List<DataSource::SnifferFunc> DataSource::gSniffers;
+
+bool DataSource::sniff(String8 *mimeType, float *confidence) {
+    *mimeType = "";
+    *confidence = 0.0f;
+
+    Mutex::Autolock autoLock(gSnifferMutex);
+    for (List<SnifferFunc>::iterator it = gSniffers.begin();
+         it != gSniffers.end(); ++it) {
+        String8 newMimeType;
+        float newConfidence;
+        if ((*it)(this, &newMimeType, &newConfidence)) {
+            if (newConfidence > *confidence) {
+                *mimeType = newMimeType;
+                *confidence = newConfidence;
+            }
+        }
+    }
+
+    return *confidence > 0.0;
+}
+
+// static
+void DataSource::RegisterSniffer(SnifferFunc func) {
+    Mutex::Autolock autoLock(gSnifferMutex);
+
+    for (List<SnifferFunc>::iterator it = gSniffers.begin();
+         it != gSniffers.end(); ++it) {
+        if (*it == func) {
+            return;
+        }
+    }
+
+    gSniffers.push_back(func);
+}
+
+// static
+void DataSource::RegisterDefaultSniffers() {
+    RegisterSniffer(SniffMP3);
+    RegisterSniffer(SniffMPEG4);
+}
+
+}  // namespace android
diff --git a/media/libstagefright/ESDS.cpp b/media/libstagefright/ESDS.cpp
new file mode 100644
index 0000000..53b92a0
--- /dev/null
+++ b/media/libstagefright/ESDS.cpp
@@ -0,0 +1,196 @@
+/*
+ * 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.
+ */
+
+#include <media/stagefright/ESDS.h>
+
+#include <string.h>
+
+namespace android {
+
+ESDS::ESDS(const void *data, size_t size)
+    : mData(new uint8_t[size]),
+      mSize(size),
+      mInitCheck(NO_INIT),
+      mDecoderSpecificOffset(0),
+      mDecoderSpecificLength(0) {
+    memcpy(mData, data, size);
+
+    mInitCheck = parse();
+}
+
+ESDS::~ESDS() {
+    delete[] mData;
+    mData = NULL;
+}
+
+status_t ESDS::InitCheck() const {
+    return mInitCheck;
+}
+
+status_t ESDS::getCodecSpecificInfo(const void **data, size_t *size) const {
+    if (mInitCheck != OK) {
+        return mInitCheck;
+    }
+
+    *data = &mData[mDecoderSpecificOffset];
+    *size = mDecoderSpecificLength;
+
+    return OK;
+}
+
+status_t ESDS::skipDescriptorHeader(
+        size_t offset, size_t size,
+        uint8_t *tag, size_t *data_offset, size_t *data_size) const {
+    if (size == 0) {
+        return ERROR_MALFORMED;
+    }
+
+    *tag = mData[offset++];
+    --size;
+
+    *data_size = 0;
+    bool more;
+    do {
+        if (size == 0) {
+            return ERROR_MALFORMED;
+        }
+
+        uint8_t x = mData[offset++];
+        --size;
+
+        *data_size = (*data_size << 7) | (x & 0x7f);
+        more = (x & 0x80) != 0;
+    }
+    while (more);
+
+    if (*data_size > size) {
+        return ERROR_MALFORMED;
+    }
+
+    *data_offset = offset;
+
+    return OK;
+}
+
+status_t ESDS::parse() {
+    uint8_t tag;
+    size_t data_offset;
+    size_t data_size;
+    status_t err =
+        skipDescriptorHeader(0, mSize, &tag, &data_offset, &data_size);
+
+    if (err != OK) {
+        return err;
+    }
+
+    if (tag != kTag_ESDescriptor) {
+        return ERROR_MALFORMED;
+    }
+
+    return parseESDescriptor(data_offset, data_size);
+}
+
+status_t ESDS::parseESDescriptor(size_t offset, size_t size) {
+    if (size < 3) {
+        return ERROR_MALFORMED;
+    }
+
+    offset += 2;  // skip ES_ID
+    size -= 2;
+
+    unsigned streamDependenceFlag = mData[offset] & 0x80;
+    unsigned URL_Flag = mData[offset] & 0x40;
+    unsigned OCRstreamFlag = mData[offset] & 0x20;
+
+    ++offset;
+    --size;
+
+    if (streamDependenceFlag) {
+        offset += 2;
+        size -= 2;
+    }
+
+    if (URL_Flag) {
+        if (offset >= size) {
+            return ERROR_MALFORMED;
+        }
+        unsigned URLlength = mData[offset];
+        offset += URLlength + 1;
+        size -= URLlength + 1;
+    }
+
+    if (OCRstreamFlag) {
+        offset += 2;
+        size -= 2;
+    }
+    
+    if (offset >= size) {
+        return ERROR_MALFORMED;
+    }
+
+    uint8_t tag;
+    size_t sub_offset, sub_size;
+    status_t err = skipDescriptorHeader(
+            offset, size, &tag, &sub_offset, &sub_size);
+
+    if (err != OK) {
+        return err;
+    }
+
+    if (tag != kTag_DecoderConfigDescriptor) {
+        return ERROR_MALFORMED;
+    }
+
+    err = parseDecoderConfigDescriptor(sub_offset, sub_size);
+
+    return err;
+}
+
+status_t ESDS::parseDecoderConfigDescriptor(size_t offset, size_t size) {
+    if (size < 13) {
+        return ERROR_MALFORMED;
+    }
+
+    offset += 13;
+    size -= 13;
+
+    if (size == 0) {
+        mDecoderSpecificOffset = 0;
+        mDecoderSpecificLength = 0;
+        return OK;
+    }
+
+    uint8_t tag;
+    size_t sub_offset, sub_size;
+    status_t err = skipDescriptorHeader(
+            offset, size, &tag, &sub_offset, &sub_size);
+
+    if (err != OK) {
+        return err;
+    }
+
+    if (tag != kTag_DecoderSpecificInfo) {
+        return ERROR_MALFORMED;
+    }
+
+    mDecoderSpecificOffset = sub_offset;
+    mDecoderSpecificLength = sub_size;
+
+    return OK;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/FileSource.cpp b/media/libstagefright/FileSource.cpp
new file mode 100644
index 0000000..c26d0a0
--- /dev/null
+++ b/media/libstagefright/FileSource.cpp
@@ -0,0 +1,50 @@
+/*
+ * 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.
+ */
+
+#include <media/stagefright/FileSource.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+namespace android {
+
+FileSource::FileSource(const char *filename)
+    : mFile(fopen(filename, "rb")) {
+}
+
+FileSource::~FileSource() {
+    if (mFile != NULL) {
+        fclose(mFile);
+        mFile = NULL;
+    }
+}
+
+status_t FileSource::InitCheck() const {
+    return mFile != NULL ? OK : NO_INIT;
+}
+
+ssize_t FileSource::read_at(off_t offset, void *data, size_t size) {
+    Mutex::Autolock autoLock(mLock);
+
+    int err = fseeko(mFile, offset, SEEK_SET);
+    assert(err != -1);
+
+    ssize_t result = fread(data, 1, size, mFile);
+
+    return result;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/HTTPDataSource.cpp b/media/libstagefright/HTTPDataSource.cpp
new file mode 100644
index 0000000..d1f8cd4
--- /dev/null
+++ b/media/libstagefright/HTTPDataSource.cpp
@@ -0,0 +1,174 @@
+/*
+ * 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.
+ */
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <stdlib.h>
+
+#include <media/stagefright/HTTPDataSource.h>
+#include <media/stagefright/HTTPStream.h>
+#include <media/stagefright/string.h>
+
+namespace android {
+
+HTTPDataSource::HTTPDataSource(const char *uri)
+    : mHost(NULL),
+      mPort(0),
+      mPath(NULL),
+      mBuffer(malloc(kBufferSize)),
+      mBufferLength(0),
+      mBufferOffset(0) {
+    assert(!strncasecmp("http://", uri, 7));
+
+    string host;
+    string path;
+    int port;
+
+    char *slash = strchr(uri + 7, '/');
+    if (slash == NULL) {
+        host = uri + 7;
+        path = "/";
+    } else {
+        host = string(uri + 7, slash - (uri + 7));
+        path = slash;
+    }
+
+    char *colon = strchr(host.c_str(), ':');
+    if (colon == NULL) {
+        port = 80;
+    } else {
+        char *end;
+        long tmp = strtol(colon + 1, &end, 10);
+        assert(end > colon + 1);
+        assert(tmp > 0 && tmp < 65536);
+        port = tmp;
+
+        host = string(host, 0, colon - host.c_str());
+    }
+
+    LOGI("Connecting to host '%s', port %d, path '%s'",
+         host.c_str(), port, path.c_str());
+
+    mHost = strdup(host.c_str());
+    mPort = port;
+    mPath = strdup(path.c_str());
+
+    status_t err = mHttp.connect(mHost, mPort);
+    assert(err == OK);
+}
+
+HTTPDataSource::HTTPDataSource(const char *host, int port, const char *path)
+    : mHost(strdup(host)),
+      mPort(port),
+      mPath(strdup(path)),
+      mBuffer(malloc(kBufferSize)),
+      mBufferLength(0),
+      mBufferOffset(0) {
+    status_t err = mHttp.connect(mHost, mPort);
+    assert(err == OK);
+}
+
+HTTPDataSource::~HTTPDataSource() {
+    mHttp.disconnect();
+
+    free(mBuffer);
+    mBuffer = NULL;
+
+    free(mPath);
+    mPath = NULL;
+}
+
+ssize_t HTTPDataSource::read_at(off_t offset, void *data, size_t size) {
+    if (offset >= mBufferOffset && offset < mBufferOffset + mBufferLength) {
+        size_t num_bytes_available = mBufferLength - (offset - mBufferOffset);
+
+        size_t copy = num_bytes_available;
+        if (copy > size) {
+            copy = size;
+        }
+
+        memcpy(data, (const char *)mBuffer + (offset - mBufferOffset), copy);
+
+        return copy;
+    }
+
+    mBufferOffset = offset;
+    mBufferLength = 0;
+
+    char host[128];
+    sprintf(host, "Host: %s\r\n", mHost);
+
+    char range[128];
+    sprintf(range, "Range: bytes=%ld-%ld\r\n\r\n",
+            mBufferOffset, mBufferOffset + kBufferSize - 1);
+
+    int http_status;
+
+    status_t err;
+    int attempt = 1;
+    for (;;) {
+        if ((err = mHttp.send("GET ")) != OK
+            || (err = mHttp.send(mPath)) != OK
+            || (err = mHttp.send(" HTTP/1.1\r\n")) != OK
+            || (err = mHttp.send(host)) != OK
+            || (err = mHttp.send(range)) != OK
+            || (err = mHttp.send("\r\n")) != OK
+            || (err = mHttp.receive_header(&http_status)) != OK) {
+
+            if (attempt == 3) {
+                return err;
+            }
+
+            mHttp.connect(mHost, mPort);
+            ++attempt;
+        } else {
+            break;
+        }
+    }
+
+    if ((http_status / 100) != 2) {
+        return UNKNOWN_ERROR;
+    }
+
+    string value;
+    if (!mHttp.find_header_value("Content-Length", &value)) {
+        return UNKNOWN_ERROR;
+    }
+
+    char *end;
+    unsigned long contentLength = strtoul(value.c_str(), &end, 10);
+
+    ssize_t num_bytes_received = mHttp.receive(mBuffer, contentLength);
+
+    if (num_bytes_received <= 0) {
+        return num_bytes_received;
+    }
+
+    mBufferLength = (size_t)num_bytes_received;
+
+    size_t copy = mBufferLength;
+    if (copy > size) {
+        copy = size;
+    }
+
+    memcpy(data, mBuffer, copy);
+
+    return copy;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/HTTPStream.cpp b/media/libstagefright/HTTPStream.cpp
new file mode 100644
index 0000000..29e6f72
--- /dev/null
+++ b/media/libstagefright/HTTPStream.cpp
@@ -0,0 +1,285 @@
+/*
+ * 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.
+ */
+
+#include <sys/socket.h>
+
+#include <arpa/inet.h>
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <media/stagefright/HTTPStream.h>
+
+namespace android {
+
+// static
+const char *HTTPStream::kStatusKey = ":status:";
+
+HTTPStream::HTTPStream()
+    : mState(READY),
+      mSocket(-1) {
+}
+
+HTTPStream::~HTTPStream() {
+    disconnect();
+}
+
+status_t HTTPStream::connect(const char *server, int port) {
+    status_t err = OK;
+
+    if (mState == CONNECTED) {
+        return ERROR_ALREADY_CONNECTED;
+    }
+
+    assert(mSocket == -1);
+    mSocket = socket(AF_INET, SOCK_STREAM, 0);
+    
+    if (mSocket < 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    struct hostent *ent = gethostbyname(server);
+    if (ent == NULL) {
+        err = ERROR_UNKNOWN_HOST;
+        goto exit1;
+    }
+
+    struct sockaddr_in addr;
+    addr.sin_family = AF_INET;
+    addr.sin_port = htons(port);
+    addr.sin_addr.s_addr = *(in_addr_t *)ent->h_addr;
+    memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
+
+    if (::connect(mSocket, (const struct sockaddr *)&addr, sizeof(addr)) < 0) {
+        err = ERROR_CANNOT_CONNECT;
+        goto exit1;
+    }
+
+    mState = CONNECTED;
+
+    return OK;
+
+exit1:
+    close(mSocket);
+    mSocket = -1;
+
+    return err;
+}
+
+status_t HTTPStream::disconnect() {
+    if (mState != CONNECTED) {
+        return ERROR_NOT_CONNECTED;
+    }
+
+    assert(mSocket >= 0);
+    close(mSocket);
+    mSocket = -1;
+
+    mState = READY;
+
+    return OK;
+}
+
+status_t HTTPStream::send(const char *data, size_t size) {
+    if (mState != CONNECTED) {
+        return ERROR_NOT_CONNECTED;
+    }
+
+    while (size > 0) {
+        ssize_t n = ::send(mSocket, data, size, 0);
+
+        if (n < 0) {
+            if (errno == EINTR) {
+                continue;
+            }
+
+            disconnect();
+
+            return ERROR_IO;
+        } else if (n == 0) {
+            disconnect();
+
+            return ERROR_CONNECTION_LOST;
+        }
+
+        size -= (size_t)n;
+        data += (size_t)n;
+    }
+
+    return OK;
+}
+
+status_t HTTPStream::send(const char *data) {
+    return send(data, strlen(data));
+}
+
+status_t HTTPStream::receive_line(char *line, size_t size) {
+    if (mState != CONNECTED) {
+        return ERROR_NOT_CONNECTED;
+    }
+
+    bool saw_CR = false;
+    size_t length = 0;
+
+    for (;;) {
+        char c;
+        ssize_t n = recv(mSocket, &c, 1, 0);
+        if (n < 0) {
+            if (errno == EINTR) {
+                continue;
+            }
+
+            disconnect();
+
+            return ERROR_IO;
+        } else if (n == 0) {
+            disconnect();
+
+            return ERROR_CONNECTION_LOST;
+        }
+
+        if (saw_CR && c == '\n') {
+            // We have a complete line.
+
+            line[length - 1] = '\0';
+            return OK;
+        }
+
+        saw_CR = (c == '\r');
+
+        assert(length + 1 < size);
+        line[length++] = c;
+    }
+}
+
+status_t HTTPStream::receive_header(int *http_status) {
+    *http_status = -1;
+    mHeaders.clear();
+
+    char line[256];
+    status_t err = receive_line(line, sizeof(line));
+    if (err != OK) {
+        return err;
+    }
+
+    mHeaders.add(string(kStatusKey), string(line));
+
+    char *spacePos = strchr(line, ' ');
+    if (spacePos == NULL) {
+        // Malformed response?
+        return UNKNOWN_ERROR;
+    }
+
+    char *status_start = spacePos + 1;
+    char *status_end = status_start;
+    while (isdigit(*status_end)) {
+        ++status_end;
+    }
+
+    if (status_end == status_start) {
+        // Malformed response, status missing?
+        return UNKNOWN_ERROR;
+    }
+
+    memmove(line, status_start, status_end - status_start);
+    line[status_end - status_start] = '\0';
+
+    long tmp = strtol(line, NULL, 10);
+    if (tmp < 0 || tmp > 999) {
+        return UNKNOWN_ERROR;
+    }
+
+    *http_status = (int)tmp;
+
+    for (;;) {
+        err = receive_line(line, sizeof(line));
+        if (err != OK) {
+            return err;
+        }
+
+        if (*line == '\0') {
+            // Empty line signals the end of the header.
+            break;
+        }
+
+        // puts(line);
+
+        char *colonPos = strchr(line, ':');
+        if (colonPos == NULL) {
+            mHeaders.add(string(line), string());
+        } else {
+            char *end_of_key = colonPos;
+            while (end_of_key > line && isspace(end_of_key[-1])) {
+                --end_of_key;
+            }
+
+            char *start_of_value = colonPos + 1;
+            while (isspace(*start_of_value)) {
+                ++start_of_value;
+            }
+
+            *end_of_key = '\0';
+
+            mHeaders.add(string(line), string(start_of_value));
+        }
+    }
+
+    return OK;
+}
+
+ssize_t HTTPStream::receive(void *data, size_t size) {
+    size_t total = 0;
+    while (total < size) {
+        ssize_t n = recv(mSocket, (char *)data + total, size - total, 0);
+
+        if (n < 0) {
+            if (errno == EINTR) {
+                continue;
+            }
+
+            disconnect();
+            return ERROR_IO;
+        } else if (n == 0) {
+            disconnect();
+
+            return ERROR_CONNECTION_LOST;
+        }
+
+        total += (size_t)n;
+    }
+
+    return (ssize_t)total;
+}
+
+bool HTTPStream::find_header_value(const string &key, string *value) const {
+    ssize_t index = mHeaders.indexOfKey(key);
+    if (index < 0) {
+        value->clear();
+        return false;
+    }
+
+    *value = mHeaders.valueAt(index);
+
+    return true;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/MP3Extractor.cpp b/media/libstagefright/MP3Extractor.cpp
new file mode 100644
index 0000000..6b47a38
--- /dev/null
+++ b/media/libstagefright/MP3Extractor.cpp
@@ -0,0 +1,527 @@
+/*
+ * 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_NDEBUG 0
+#define LOG_TAG "MP3Extractor"
+#include <utils/Log.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MP3Extractor.h>
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/Utils.h>
+#include <utils/String8.h>
+
+namespace android {
+
+static bool get_mp3_frame_size(
+        uint32_t header, size_t *frame_size,
+        int *out_sampling_rate = NULL, int *out_channels = NULL,
+        int *out_bitrate = NULL) {
+    *frame_size = 0;
+
+    if (out_sampling_rate) {
+        *out_sampling_rate = 0;
+    }
+
+    if (out_channels) {
+        *out_channels = 0;
+    }
+
+    if (out_bitrate) {
+        *out_bitrate = 0;
+    }
+
+    if ((header & 0xffe00000) != 0xffe00000) {
+        return false;
+    }
+
+    unsigned version = (header >> 19) & 3;
+
+    if (version == 0x01) {
+        return false;
+    }
+    
+    unsigned layer = (header >> 17) & 3;
+
+    if (layer == 0x00) {
+        return false;
+    }
+
+    unsigned protection = (header >> 16) & 1;
+
+    unsigned bitrate_index = (header >> 12) & 0x0f;
+
+    if (bitrate_index == 0 || bitrate_index == 0x0f) {
+        // Disallow "free" bitrate.
+
+        LOGE("We disallow 'free' bitrate for now.");
+        return false;
+    }
+
+    unsigned sampling_rate_index = (header >> 10) & 3;
+
+    if (sampling_rate_index == 3) {
+        return false;
+    }
+
+    static const int kSamplingRateV1[] = { 44100, 48000, 32000 };
+    int sampling_rate = kSamplingRateV1[sampling_rate_index];
+    if (version == 2 /* V2 */) {
+        sampling_rate /= 2;
+    } else if (version == 0 /* V2.5 */) {
+        sampling_rate /= 4;
+    }
+
+    unsigned padding = (header >> 9) & 1;
+
+    if (layer == 3) {
+        // layer I
+
+        static const int kBitrateV1[] = {
+            32, 64, 96, 128, 160, 192, 224, 256,
+            288, 320, 352, 384, 416, 448
+        };
+
+        static const int kBitrateV2[] = {
+            32, 48, 56, 64, 80, 96, 112, 128,
+            144, 160, 176, 192, 224, 256
+        };
+
+        int bitrate =
+            (version == 3 /* V1 */)
+                ? kBitrateV1[bitrate_index - 1]
+                : kBitrateV2[bitrate_index - 1];
+
+        if (out_bitrate) {
+            *out_bitrate = bitrate;
+        }
+
+        *frame_size = (12000 * bitrate / sampling_rate + padding) * 4;
+    } else {
+        // layer II or III
+
+        static const int kBitrateV1L2[] = {
+            32, 48, 56, 64, 80, 96, 112, 128,
+            160, 192, 224, 256, 320, 384
+        };
+
+        static const int kBitrateV1L3[] = {
+            32, 40, 48, 56, 64, 80, 96, 112,
+            128, 160, 192, 224, 256, 320
+        };
+
+        static const int kBitrateV2[] = {
+            8, 16, 24, 32, 40, 48, 56, 64,
+            80, 96, 112, 128, 144, 160
+        };
+
+        int bitrate;
+        if (version == 3 /* V1 */) {
+            bitrate = (layer == 2 /* L2 */)
+                ? kBitrateV1L2[bitrate_index - 1]
+                : kBitrateV1L3[bitrate_index - 1];
+        } else {
+            // V2 (or 2.5)
+
+            bitrate = kBitrateV2[bitrate_index - 1];
+        }
+
+        if (out_bitrate) {
+            *out_bitrate = bitrate;
+        }
+
+        *frame_size = 144000 * bitrate / sampling_rate + padding;
+    }
+
+    if (out_sampling_rate) {
+        *out_sampling_rate = sampling_rate;
+    }
+
+    if (out_channels) {
+        int channel_mode = (header >> 6) & 3;
+
+        *out_channels = (channel_mode == 3) ? 1 : 2;
+    }
+
+    return true;
+}
+
+static bool Resync(
+        DataSource *source, uint32_t match_header,
+        off_t *inout_pos, uint32_t *out_header) {
+    // Everything must match except for
+    // protection, bitrate, padding, private bits and mode extension.
+    const uint32_t kMask = 0xfffe0ccf;
+
+    const size_t kMaxFrameSize = 4096;
+    uint8_t *buffer = new uint8_t[kMaxFrameSize];
+    
+    off_t pos = *inout_pos - kMaxFrameSize;
+    size_t buffer_offset = kMaxFrameSize;
+    size_t buffer_length = kMaxFrameSize;
+    bool valid = false;
+    do {
+        if (buffer_offset + 3 >= buffer_length) {
+            if (buffer_length < kMaxFrameSize) {
+                break;
+            }
+
+            pos += buffer_offset;
+
+            if (pos >= *inout_pos + 128 * 1024) {
+                // Don't scan forever.
+                LOGV("giving up at offset %ld", pos);
+                break;
+            }
+
+            memmove(buffer, &buffer[buffer_offset], buffer_length - buffer_offset);
+            buffer_length = buffer_length - buffer_offset;
+            buffer_offset = 0;
+
+            ssize_t n = source->read_at(
+                    pos, &buffer[buffer_length], kMaxFrameSize - buffer_length);
+
+            if (n <= 0) {
+                break;
+            }
+
+            buffer_length += (size_t)n;
+
+            continue;
+        }
+
+        uint32_t header = U32_AT(&buffer[buffer_offset]);
+
+        if (match_header != 0 && (header & kMask) != (match_header & kMask)) {
+            ++buffer_offset;
+            continue;
+        }
+
+        size_t frame_size;
+        int sample_rate, num_channels, bitrate;
+        if (!get_mp3_frame_size(header, &frame_size,
+                               &sample_rate, &num_channels, &bitrate)) {
+            ++buffer_offset;
+            continue;
+        }
+
+        LOGV("found possible 1st frame at %ld", pos + buffer_offset);
+
+        // We found what looks like a valid frame,
+        // now find its successors.
+
+        off_t test_pos = pos + buffer_offset + frame_size;
+
+        valid = true;
+        for (int j = 0; j < 3; ++j) {
+            uint8_t tmp[4];
+            if (source->read_at(test_pos, tmp, 4) < 4) {
+                valid = false;
+                break;
+            }
+            
+            uint32_t test_header = U32_AT(tmp);
+
+            LOGV("subsequent header is %08x", test_header);
+
+            if ((test_header & kMask) != (header & kMask)) {
+                valid = false;
+                break;
+            }
+
+            size_t test_frame_size;
+            if (!get_mp3_frame_size(test_header, &test_frame_size)) {
+                valid = false;
+                break;
+            }
+
+            LOGV("found subsequent frame #%d at %ld", j + 2, test_pos);
+
+            test_pos += test_frame_size;
+        }
+
+        if (valid) {
+            *inout_pos = pos + buffer_offset;
+
+            if (out_header != NULL) {
+                *out_header = header;
+            }
+        } else {
+            LOGV("no dice, no valid sequence of frames found.");
+        }
+
+        ++buffer_offset;
+
+    } while (!valid);
+
+    delete[] buffer;
+    buffer = NULL;
+
+    return valid;
+}
+
+class MP3Source : public MediaSource {
+public:
+    MP3Source(
+            const sp<MetaData> &meta, DataSource *source,
+            off_t first_frame_pos, uint32_t fixed_header);
+
+    virtual ~MP3Source();
+
+    virtual status_t start(MetaData *params = NULL);
+    virtual status_t stop();
+
+    virtual sp<MetaData> getFormat();
+
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options = NULL);
+
+private:
+    sp<MetaData> mMeta;
+    DataSource *mDataSource;
+    off_t mFirstFramePos;
+    uint32_t mFixedHeader;
+    off_t mCurrentPos;
+    int64_t mCurrentTimeUs;
+    bool mStarted;
+
+    MediaBufferGroup *mGroup;
+
+    MP3Source(const MP3Source &);
+    MP3Source &operator=(const MP3Source &);
+};
+
+MP3Extractor::MP3Extractor(DataSource *source)
+    : mDataSource(source),
+      mFirstFramePos(-1),
+      mFixedHeader(0) {
+    off_t pos = 0;
+    uint32_t header;
+    bool success = Resync(mDataSource, 0, &pos, &header);
+    assert(success);
+
+    if (success) {
+        mFirstFramePos = pos;
+        mFixedHeader = header;
+
+        size_t frame_size;
+        int sample_rate;
+        int num_channels;
+        int bitrate;
+        get_mp3_frame_size(
+                header, &frame_size, &sample_rate, &num_channels, &bitrate);
+
+        mMeta = new MetaData;
+
+        mMeta->setCString(kKeyMIMEType, "audio/mpeg");
+        mMeta->setInt32(kKeySampleRate, sample_rate);
+        mMeta->setInt32(kKeyBitRate, bitrate);
+        mMeta->setInt32(kKeyChannelCount, num_channels);
+
+        off_t fileSize;
+        if (mDataSource->getSize(&fileSize) == OK) {
+            mMeta->setInt32(
+                    kKeyDuration,
+                    8 * (fileSize - mFirstFramePos) / bitrate);
+            mMeta->setInt32(kKeyTimeScale, 1000);
+        }
+    }
+}
+
+MP3Extractor::~MP3Extractor() {
+    delete mDataSource;
+    mDataSource = NULL;
+}
+
+status_t MP3Extractor::countTracks(int *num_tracks) {
+    *num_tracks = mFirstFramePos < 0 ? 0 : 1;
+
+    return OK;
+}
+
+status_t MP3Extractor::getTrack(int index, MediaSource **source) {
+    if (mFirstFramePos < 0 || index != 0) {
+        return ERROR_OUT_OF_RANGE;
+    }
+
+    *source = new MP3Source(
+            mMeta, mDataSource, mFirstFramePos, mFixedHeader);
+
+    return OK;
+}
+
+sp<MetaData> MP3Extractor::getTrackMetaData(int index) {
+    if (mFirstFramePos < 0 || index != 0) {
+        return NULL;
+    }
+
+    return mMeta;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+MP3Source::MP3Source(
+        const sp<MetaData> &meta, DataSource *source,
+        off_t first_frame_pos, uint32_t fixed_header)
+    : mMeta(meta),
+      mDataSource(source),
+      mFirstFramePos(first_frame_pos),
+      mFixedHeader(fixed_header),
+      mCurrentPos(0),
+      mCurrentTimeUs(0),
+      mStarted(false),
+      mGroup(NULL) {
+}
+
+MP3Source::~MP3Source() {
+    if (mStarted) {
+        stop();
+    }
+}
+
+status_t MP3Source::start(MetaData *) {
+    assert(!mStarted);
+
+    mGroup = new MediaBufferGroup;
+
+    const size_t kMaxFrameSize = 32768;
+    mGroup->add_buffer(new MediaBuffer(kMaxFrameSize));
+
+    mCurrentPos = mFirstFramePos;
+    mCurrentTimeUs = 0;
+
+    mStarted = true;
+
+    return OK;
+}
+
+status_t MP3Source::stop() {
+    assert(mStarted);
+
+    delete mGroup;
+    mGroup = NULL;
+
+    mStarted = false;
+
+    return OK;
+}
+
+sp<MetaData> MP3Source::getFormat() {
+    return mMeta;
+}
+
+status_t MP3Source::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    if (options != NULL && options->getSeekTo(&seekTimeUs)) {
+        int32_t bitrate;
+        if (!mMeta->findInt32(kKeyBitRate, &bitrate)) {
+            // bitrate is in kbits/sec.
+            LOGI("no bitrate");
+
+            return ERROR_UNSUPPORTED;
+        }
+
+        mCurrentTimeUs = seekTimeUs;
+        mCurrentPos = mFirstFramePos + seekTimeUs * bitrate / 1000000 * 125;
+    }
+
+    MediaBuffer *buffer;
+    status_t err = mGroup->acquire_buffer(&buffer);
+    if (err != OK) {
+        return err;
+    }
+
+    size_t frame_size;
+    for (;;) {
+        ssize_t n = mDataSource->read_at(mCurrentPos, buffer->data(), 4);
+        if (n < 4) {
+            buffer->release();
+            buffer = NULL;
+
+            return ERROR_END_OF_STREAM;
+        }
+
+        uint32_t header = U32_AT((const uint8_t *)buffer->data());
+        
+        if (get_mp3_frame_size(header, &frame_size)) {
+            break;
+        }
+
+        // Lost sync.
+        LOGW("lost sync!\n");
+
+        off_t pos = mCurrentPos;
+        if (!Resync(mDataSource, mFixedHeader, &pos, NULL)) {
+            LOGE("Unable to resync. Signalling end of stream.");
+
+            buffer->release();
+            buffer = NULL;
+
+            return ERROR_END_OF_STREAM;
+        }
+
+        mCurrentPos = pos;
+
+        // Try again with the new position.
+    }
+
+    assert(frame_size <= buffer->size());
+
+    ssize_t n = mDataSource->read_at(mCurrentPos, buffer->data(), frame_size);
+    if (n < (ssize_t)frame_size) {
+        buffer->release();
+        buffer = NULL;
+
+        return ERROR_END_OF_STREAM;
+    }
+
+    buffer->set_range(0, frame_size);
+
+    buffer->meta_data()->setInt32(kKeyTimeUnits, mCurrentTimeUs / 1000);
+    buffer->meta_data()->setInt32(kKeyTimeScale, 1000);
+
+    mCurrentPos += frame_size;
+    mCurrentTimeUs += 1152 * 1000000 / 44100;
+
+    *out = buffer;
+
+    return OK;
+}
+
+bool SniffMP3(DataSource *source, String8 *mimeType, float *confidence) {
+    off_t pos = 0;
+    uint32_t header;
+    if (!Resync(source, 0, &pos, &header)) {
+        return false;
+    }
+
+    *mimeType = "audio/mpeg";
+    *confidence = 0.3f;
+
+    return true;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/MPEG4Extractor.cpp b/media/libstagefright/MPEG4Extractor.cpp
new file mode 100644
index 0000000..caaec06
--- /dev/null
+++ b/media/libstagefright/MPEG4Extractor.cpp
@@ -0,0 +1,937 @@
+/*
+ * 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 "MPEG4Extractor"
+#include <utils/Log.h>
+
+#include <arpa/inet.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <ctype.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MPEG4Extractor.h>
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/SampleTable.h>
+#include <media/stagefright/Utils.h>
+#include <utils/String8.h>
+
+namespace android {
+
+class MPEG4Source : public MediaSource {
+public:
+    // Caller retains ownership of both "dataSource" and "sampleTable".
+    MPEG4Source(const sp<MetaData> &format, DataSource *dataSource,
+                SampleTable *sampleTable);
+
+    virtual ~MPEG4Source();
+
+    virtual status_t start(MetaData *params = NULL);
+    virtual status_t stop();
+
+    virtual sp<MetaData> getFormat();
+
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options = NULL);
+
+private:
+    sp<MetaData> mFormat;
+    DataSource *mDataSource;
+    int32_t mTimescale;
+    SampleTable *mSampleTable;
+    uint32_t mCurrentSampleIndex;
+
+    bool mIsAVC;
+    bool mStarted;
+
+    MediaBufferGroup *mGroup;
+
+    MediaBuffer *mBuffer;
+    size_t mBufferOffset;
+    size_t mBufferSizeRemaining;
+
+    bool mNeedsNALFraming;
+
+    MPEG4Source(const MPEG4Source &);
+    MPEG4Source &operator=(const MPEG4Source &);
+};
+
+static void hexdump(const void *_data, size_t size) {
+    const uint8_t *data = (const uint8_t *)_data;
+    size_t offset = 0;
+    while (offset < size) {
+        printf("0x%04x  ", offset);
+
+        size_t n = size - offset;
+        if (n > 16) {
+            n = 16;
+        }
+
+        for (size_t i = 0; i < 16; ++i) {
+            if (i == 8) {
+                printf(" ");
+            }
+
+            if (offset + i < size) {
+                printf("%02x ", data[offset + i]);
+            } else {
+                printf("   ");
+            }
+        }
+
+        printf(" ");
+
+        for (size_t i = 0; i < n; ++i) {
+            if (isprint(data[offset + i])) {
+                printf("%c", data[offset + i]);
+            } else {
+                printf(".");
+            }
+        }
+
+        printf("\n");
+
+        offset += 16;
+    }
+}
+
+static const char *const FourCC2MIME(uint32_t fourcc) {
+    switch (fourcc) {
+        case FOURCC('m', 'p', '4', 'a'):
+            return "audio/mp4a-latm";
+
+        case FOURCC('s', 'a', 'm', 'r'):
+            return "audio/3gpp";
+
+        case FOURCC('m', 'p', '4', 'v'):
+            return "video/mp4v-es";
+
+        case FOURCC('s', '2', '6', '3'):
+            return "video/3gpp";
+
+        case FOURCC('a', 'v', 'c', '1'):
+            return "video/avc";
+
+        default:
+            assert(!"should not be here.");
+            return NULL;
+    }
+}
+
+MPEG4Extractor::MPEG4Extractor(DataSource *source)
+    : mDataSource(source),
+      mHaveMetadata(false),
+      mFirstTrack(NULL),
+      mLastTrack(NULL) {
+}
+
+MPEG4Extractor::~MPEG4Extractor() {
+    Track *track = mFirstTrack;
+    while (track) {
+        Track *next = track->next;
+
+        delete track->sampleTable;
+        track->sampleTable = NULL;
+
+        delete track;
+        track = next;
+    }
+    mFirstTrack = mLastTrack = NULL;
+
+    delete mDataSource;
+    mDataSource = NULL;
+}
+
+status_t MPEG4Extractor::countTracks(int *num_tracks) {
+    status_t err;
+    if ((err = readMetaData()) != OK) {
+        return err;
+    }
+
+    *num_tracks = 0;
+    Track *track = mFirstTrack;
+    while (track) {
+        ++*num_tracks;
+        track = track->next;
+    }
+
+    return OK;
+}
+
+sp<MetaData> MPEG4Extractor::getTrackMetaData(int index) {
+    if (index < 0) {
+        return NULL;
+    }
+
+    status_t err;
+    if ((err = readMetaData()) != OK) {
+        return NULL;
+    }
+
+    Track *track = mFirstTrack;
+    while (index > 0) {
+        if (track == NULL) {
+            return NULL;
+        }
+
+        track = track->next;
+        --index;
+    }
+
+    return track->meta;
+}
+
+status_t MPEG4Extractor::readMetaData() {
+    if (mHaveMetadata) {
+        return OK;
+    }
+
+    off_t offset = 0;
+    status_t err;
+    while ((err = parseChunk(&offset, 0)) == OK) {
+    }
+    
+    if (mHaveMetadata) {
+        return OK;
+    }
+
+    return err;
+}
+
+static void MakeFourCCString(uint32_t x, char *s) {
+    s[0] = x >> 24;
+    s[1] = (x >> 16) & 0xff;
+    s[2] = (x >> 8) & 0xff;
+    s[3] = x & 0xff;
+    s[4] = '\0';
+}
+
+status_t MPEG4Extractor::parseChunk(off_t *offset, int depth) {
+    uint32_t hdr[2];
+    if (mDataSource->read_at(*offset, hdr, 8) < 8) {
+        return ERROR_IO;
+    }
+    uint64_t chunk_size = ntohl(hdr[0]);
+    uint32_t chunk_type = ntohl(hdr[1]);
+    off_t data_offset = *offset + 8;
+
+    if (chunk_size == 1) {
+        if (mDataSource->read_at(*offset + 8, &chunk_size, 8) < 8) {
+            return ERROR_IO;
+        }
+        chunk_size = ntoh64(chunk_size);
+        data_offset += 8;
+    }
+
+    char chunk[5];
+    MakeFourCCString(chunk_type, chunk);
+
+#if 0
+    static const char kWhitespace[] = "                                        ";
+    const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth];
+    printf("%sfound chunk '%s' of size %lld\n", indent, chunk, chunk_size);
+
+    char buffer[256];
+    if (chunk_size <= sizeof(buffer)) {
+        if (mDataSource->read_at(*offset, buffer, chunk_size) < chunk_size) {
+            return ERROR_IO;
+        }
+
+        hexdump(buffer, chunk_size);
+    }
+#endif
+
+    off_t chunk_data_size = *offset + chunk_size - data_offset;
+
+    switch(chunk_type) {
+        case FOURCC('m', 'o', 'o', 'v'):
+        case FOURCC('t', 'r', 'a', 'k'):
+        case FOURCC('m', 'd', 'i', 'a'):
+        case FOURCC('m', 'i', 'n', 'f'):
+        case FOURCC('d', 'i', 'n', 'f'):
+        case FOURCC('s', 't', 'b', 'l'):
+        case FOURCC('m', 'v', 'e', 'x'):
+        case FOURCC('m', 'o', 'o', 'f'):
+        case FOURCC('t', 'r', 'a', 'f'):
+        case FOURCC('m', 'f', 'r', 'a'):
+        case FOURCC('s', 'k', 'i' ,'p'):
+        {
+            off_t stop_offset = *offset + chunk_size;
+            *offset = data_offset;
+            while (*offset < stop_offset) {
+                status_t err = parseChunk(offset, depth + 1);
+                if (err != OK) {
+                    return err;
+                }
+            }
+            assert(*offset == stop_offset);
+
+            if (chunk_type == FOURCC('m', 'o', 'o', 'v')) {
+                mHaveMetadata = true;
+
+                return UNKNOWN_ERROR;  // Return a dummy error.
+            }
+            break;
+        }
+
+        case FOURCC('t', 'k', 'h', 'd'):
+        {
+            assert(chunk_data_size >= 4);
+
+            uint8_t version;
+            if (mDataSource->read_at(data_offset, &version, 1) < 1) {
+                return ERROR_IO;
+            }
+
+            uint64_t ctime, mtime, duration;
+            int32_t id;
+            uint32_t width, height;
+
+            if (version == 1) {
+                if (chunk_data_size != 36 + 60) {
+                    return ERROR_MALFORMED;
+                }
+
+                uint8_t buffer[36 + 60];
+                if (mDataSource->read_at(
+                            data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
+                    return ERROR_IO;
+                }
+
+                ctime = U64_AT(&buffer[4]);
+                mtime = U64_AT(&buffer[12]);
+                id = U32_AT(&buffer[20]);
+                duration = U64_AT(&buffer[28]);
+                width = U32_AT(&buffer[88]);
+                height = U32_AT(&buffer[92]);
+            } else if (version == 0) {
+                if (chunk_data_size != 24 + 60) {
+                    return ERROR_MALFORMED;
+                }
+
+                uint8_t buffer[24 + 60];
+                if (mDataSource->read_at(
+                            data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
+                    return ERROR_IO;
+                }
+                ctime = U32_AT(&buffer[4]);
+                mtime = U32_AT(&buffer[8]);
+                id = U32_AT(&buffer[12]);
+                duration = U32_AT(&buffer[20]);
+                width = U32_AT(&buffer[76]);
+                height = U32_AT(&buffer[80]);
+            }
+
+            Track *track = new Track;
+            track->next = NULL;
+            if (mLastTrack) {
+                mLastTrack->next = track;
+            } else {
+                mFirstTrack = track;
+            }
+            mLastTrack = track;
+
+            track->meta = new MetaData;
+            track->timescale = 0;
+            track->sampleTable = new SampleTable(mDataSource);
+            track->meta->setCString(kKeyMIMEType, "application/octet-stream");
+
+            *offset += chunk_size;
+            break;
+        }
+
+        case FOURCC('m', 'd', 'h', 'd'):
+        {
+            if (chunk_data_size < 4) {
+                return ERROR_MALFORMED;
+            }
+
+            uint8_t version;
+            if (mDataSource->read_at(
+                        data_offset, &version, sizeof(version))
+                    < (ssize_t)sizeof(version)) {
+                return ERROR_IO;
+            }
+
+            off_t timescale_offset;
+
+            if (version == 1) {
+                timescale_offset = data_offset + 4 + 16;
+            } else if (version == 0) {
+                timescale_offset = data_offset + 4 + 8;
+            } else {
+                return ERROR_IO;
+            }
+
+            uint32_t timescale;
+            if (mDataSource->read_at(
+                        timescale_offset, &timescale, sizeof(timescale))
+                    < (ssize_t)sizeof(timescale)) {
+                return ERROR_IO;
+            }
+
+            mLastTrack->timescale = ntohl(timescale);
+            mLastTrack->meta->setInt32(kKeyTimeScale, mLastTrack->timescale);
+
+            int64_t duration;
+            if (version == 1) {
+                if (mDataSource->read_at(
+                            timescale_offset + 4, &duration, sizeof(duration))
+                        < (ssize_t)sizeof(duration)) {
+                    return ERROR_IO;
+                }
+                duration = ntoh64(duration);
+            } else {
+                int32_t duration32;
+                if (mDataSource->read_at(
+                            timescale_offset + 4, &duration32, sizeof(duration32))
+                        < (ssize_t)sizeof(duration32)) {
+                    return ERROR_IO;
+                }
+                duration = ntohl(duration32);
+            }
+            mLastTrack->meta->setInt32(kKeyDuration, duration);
+
+            *offset += chunk_size;
+            break;
+        }
+
+        case FOURCC('h', 'd', 'l', 'r'):
+        {
+            if (chunk_data_size < 25) {
+                return ERROR_MALFORMED;
+            }
+
+            uint8_t buffer[24];
+            if (mDataSource->read_at(data_offset, buffer, 24) < 24) {
+                return ERROR_IO;
+            }
+
+            if (U32_AT(buffer) != 0) {
+                // Should be version 0, flags 0.
+                return ERROR_MALFORMED;
+            }
+
+            if (U32_AT(&buffer[4]) != 0) {
+                // pre_defined should be 0.
+                return ERROR_MALFORMED;
+            }
+
+            mHandlerType = U32_AT(&buffer[8]);
+            *offset += chunk_size;
+            break;
+        }
+
+        case FOURCC('s', 't', 's', 'd'):
+        {
+            if (chunk_data_size < 8) {
+                return ERROR_MALFORMED;
+            }
+
+            uint8_t buffer[8];
+            assert(chunk_data_size >= (off_t)sizeof(buffer));
+            if (mDataSource->read_at(
+                        data_offset, buffer, 8) < 8) {
+                return ERROR_IO;
+            }
+
+            if (U32_AT(buffer) != 0) {
+                // Should be version 0, flags 0.
+                return ERROR_MALFORMED;
+            }
+
+            uint32_t entry_count = U32_AT(&buffer[4]);
+
+            if (entry_count > 1) {
+                // For now we only support a single type of media per track.
+                return ERROR_UNSUPPORTED;
+            }
+
+            off_t stop_offset = *offset + chunk_size;
+            *offset = data_offset + 8;
+            for (uint32_t i = 0; i < entry_count; ++i) {
+                status_t err = parseChunk(offset, depth + 1);
+                if (err != OK) {
+                    return err;
+                }
+            }
+            assert(*offset == stop_offset);
+            break;
+        }
+
+        case FOURCC('m', 'p', '4', 'a'):
+        case FOURCC('s', 'a', 'm', 'r'):
+        {
+            if (mHandlerType != FOURCC('s', 'o', 'u', 'n')) {
+                return ERROR_MALFORMED;
+            }
+
+            uint8_t buffer[8 + 20];
+            if (chunk_data_size < (ssize_t)sizeof(buffer)) {
+                // Basic AudioSampleEntry size.
+                return ERROR_MALFORMED;
+            }
+
+            if (mDataSource->read_at(
+                        data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
+                return ERROR_IO;
+            }
+
+            uint16_t data_ref_index = U16_AT(&buffer[6]);
+            uint16_t num_channels = U16_AT(&buffer[16]);
+
+            if (!strcasecmp("audio/3gpp", FourCC2MIME(chunk_type))) {
+                // AMR audio is always mono.
+                num_channels = 1;
+            }
+
+            uint16_t sample_size = U16_AT(&buffer[18]);
+            uint32_t sample_rate = U32_AT(&buffer[24]) >> 16;
+
+            printf("*** coding='%s' %d channels, size %d, rate %d\n",
+                   chunk, num_channels, sample_size, sample_rate);
+
+            mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
+            mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
+            mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
+
+            off_t stop_offset = *offset + chunk_size;
+            *offset = data_offset + sizeof(buffer);
+            while (*offset < stop_offset) {
+                status_t err = parseChunk(offset, depth + 1);
+                if (err != OK) {
+                    return err;
+                }
+            }
+            assert(*offset == stop_offset);
+            break;
+        }
+
+        case FOURCC('m', 'p', '4', 'v'):
+        case FOURCC('s', '2', '6', '3'):
+        case FOURCC('a', 'v', 'c', '1'):
+        {
+            if (mHandlerType != FOURCC('v', 'i', 'd', 'e')) {
+                return ERROR_MALFORMED;
+            }
+
+            uint8_t buffer[78];
+            if (chunk_data_size < (ssize_t)sizeof(buffer)) {
+                // Basic VideoSampleEntry size.
+                return ERROR_MALFORMED;
+            }
+
+            if (mDataSource->read_at(
+                        data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
+                return ERROR_IO;
+            }
+
+            uint16_t data_ref_index = U16_AT(&buffer[6]);
+            uint16_t width = U16_AT(&buffer[6 + 18]);
+            uint16_t height = U16_AT(&buffer[6 + 20]);
+
+            printf("*** coding='%s' width=%d height=%d\n",
+                   chunk, width, height);
+
+            mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
+            mLastTrack->meta->setInt32(kKeyWidth, width);
+            mLastTrack->meta->setInt32(kKeyHeight, height);
+
+            off_t stop_offset = *offset + chunk_size;
+            *offset = data_offset + sizeof(buffer);
+            while (*offset < stop_offset) {
+                status_t err = parseChunk(offset, depth + 1);
+                if (err != OK) {
+                    return err;
+                }
+            }
+            assert(*offset == stop_offset);
+            break;
+        }
+
+        case FOURCC('s', 't', 'c', 'o'):
+        case FOURCC('c', 'o', '6', '4'):
+        {
+            status_t err =
+                mLastTrack->sampleTable->setChunkOffsetParams(
+                        chunk_type, data_offset, chunk_data_size);
+
+            if (err != OK) {
+                return err;
+            }
+
+            *offset += chunk_size;
+            break;
+        }
+
+        case FOURCC('s', 't', 's', 'c'):
+        {
+            status_t err =
+                mLastTrack->sampleTable->setSampleToChunkParams(
+                        data_offset, chunk_data_size);
+
+            if (err != OK) {
+                return err;
+            }
+
+            *offset += chunk_size;
+            break;
+        }
+
+        case FOURCC('s', 't', 's', 'z'):
+        case FOURCC('s', 't', 'z', '2'):
+        {
+            status_t err =
+                mLastTrack->sampleTable->setSampleSizeParams(
+                        chunk_type, data_offset, chunk_data_size);
+
+            if (err != OK) {
+                return err;
+            }
+
+            *offset += chunk_size;
+            break;
+        }
+
+        case FOURCC('s', 't', 't', 's'):
+        {
+            status_t err =
+                mLastTrack->sampleTable->setTimeToSampleParams(
+                        data_offset, chunk_data_size);
+
+            if (err != OK) {
+                return err;
+            }
+
+            *offset += chunk_size;
+            break;
+        }
+
+        case FOURCC('s', 't', 's', 's'):
+        {
+            status_t err =
+                mLastTrack->sampleTable->setSyncSampleParams(
+                        data_offset, chunk_data_size);
+
+            if (err != OK) {
+                return err;
+            }
+
+            *offset += chunk_size;
+            break;
+        }
+
+        case FOURCC('e', 's', 'd', 's'):
+        {
+            if (chunk_data_size < 4) {
+                return ERROR_MALFORMED;
+            }
+
+            uint8_t buffer[256];
+            if (chunk_data_size > (off_t)sizeof(buffer)) {
+                return ERROR_BUFFER_TOO_SMALL;
+            }
+
+            if (mDataSource->read_at(
+                        data_offset, buffer, chunk_data_size) < chunk_data_size) {
+                return ERROR_IO;
+            }
+
+            if (U32_AT(buffer) != 0) {
+                // Should be version 0, flags 0.
+                return ERROR_MALFORMED;
+            }
+
+            mLastTrack->meta->setData(
+                    kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4);
+
+            *offset += chunk_size;
+            break;
+        }
+
+        case FOURCC('a', 'v', 'c', 'C'):
+        {
+            char buffer[256];
+            if (chunk_data_size > (off_t)sizeof(buffer)) {
+                return ERROR_BUFFER_TOO_SMALL;
+            }
+
+            if (mDataSource->read_at(
+                        data_offset, buffer, chunk_data_size) < chunk_data_size) {
+                return ERROR_IO;
+            }
+
+            mLastTrack->meta->setData(
+                    kKeyAVCC, kTypeAVCC, buffer, chunk_data_size);
+
+            *offset += chunk_size;
+            break;
+        }
+
+        default:
+        {
+            *offset += chunk_size;
+            break;
+        }
+    }
+
+    return OK;
+}
+
+status_t MPEG4Extractor::getTrack(int index, MediaSource **source) {
+    *source = NULL;
+
+    if (index < 0) {
+        return ERROR_OUT_OF_RANGE;
+    }
+
+    status_t err;
+    if ((err = readMetaData()) != OK) {
+        return err;
+    }
+
+    Track *track = mFirstTrack;
+    while (index > 0) {
+        if (track == NULL) {
+            return ERROR_OUT_OF_RANGE;
+        }
+
+        track = track->next;
+        --index;
+    }
+
+    *source = new MPEG4Source(
+            track->meta, mDataSource, track->sampleTable);
+
+    return OK;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+MPEG4Source::MPEG4Source(
+        const sp<MetaData> &format,
+        DataSource *dataSource, SampleTable *sampleTable)
+    : mFormat(format),
+      mDataSource(dataSource),
+      mTimescale(0),
+      mSampleTable(sampleTable),
+      mCurrentSampleIndex(0),
+      mIsAVC(false),
+      mStarted(false),
+      mGroup(NULL),
+      mBuffer(NULL),
+      mBufferOffset(0),
+      mBufferSizeRemaining(0),
+      mNeedsNALFraming(false) {
+    const char *mime;
+    bool success = mFormat->findCString(kKeyMIMEType, &mime);
+    assert(success);
+
+    success = mFormat->findInt32(kKeyTimeScale, &mTimescale);
+    assert(success);
+
+    mIsAVC = !strcasecmp(mime, "video/avc");
+}
+
+MPEG4Source::~MPEG4Source() {
+    if (mStarted) {
+        stop();
+    }
+}
+
+status_t MPEG4Source::start(MetaData *params) {
+    assert(!mStarted);
+
+    int32_t val;
+    if (mIsAVC && params && params->findInt32(kKeyNeedsNALFraming, &val)
+        && val != 0) {
+        mNeedsNALFraming = true;
+    } else {
+        mNeedsNALFraming = false;
+    }
+
+    mGroup = new MediaBufferGroup;
+
+    size_t max_size;
+    status_t err = mSampleTable->getMaxSampleSize(&max_size);
+    assert(err == OK);
+
+    // Add padding for de-framing of AVC content just in case.
+    mGroup->add_buffer(new MediaBuffer(max_size + 2));
+
+    mStarted = true;
+
+    return OK;
+}
+
+status_t MPEG4Source::stop() {
+    assert(mStarted);
+
+    if (mBuffer != NULL) {
+        mBuffer->release();
+        mBuffer = NULL;
+    }
+
+    delete mGroup;
+    mGroup = NULL;
+
+    mStarted = false;
+    mCurrentSampleIndex = 0;
+
+    return OK;
+}
+
+sp<MetaData> MPEG4Source::getFormat() {
+    return mFormat;
+}
+
+status_t MPEG4Source::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    assert(mStarted);
+
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        uint32_t sampleIndex;
+        status_t err = mSampleTable->findClosestSample(
+                seekTimeUs * mTimescale / 1000000,
+                &sampleIndex, SampleTable::kSyncSample_Flag);
+
+        if (err != OK) {
+            return err;
+        }
+
+        mCurrentSampleIndex = sampleIndex;
+        if (mBuffer != NULL) {
+            mBuffer->release();
+            mBuffer = NULL;
+        }
+
+        // fall through
+    }
+
+    if (mBuffer == NULL) {
+        off_t offset;
+        size_t size;
+        status_t err = mSampleTable->getSampleOffsetAndSize(
+                mCurrentSampleIndex, &offset, &size);
+
+        if (err != OK) {
+            return err;
+        }
+
+        uint32_t dts;
+        err = mSampleTable->getDecodingTime(mCurrentSampleIndex, &dts);
+
+        if (err != OK) {
+            return err;
+        }
+
+        err = mGroup->acquire_buffer(&mBuffer);
+        if (err != OK) {
+            assert(mBuffer == NULL);
+            return err;
+        }
+
+        assert(mBuffer->size() + 2 >= size);
+
+        ssize_t num_bytes_read =
+            mDataSource->read_at(offset, (uint8_t *)mBuffer->data() + 2, size);
+
+        if (num_bytes_read < (ssize_t)size) {
+            mBuffer->release();
+            mBuffer = NULL;
+
+            return err;
+        }
+
+        mBuffer->set_range(2, size);
+        mBuffer->meta_data()->clear();
+        mBuffer->meta_data()->setInt32(kKeyTimeUnits, dts);
+        mBuffer->meta_data()->setInt32(kKeyTimeScale, mTimescale);
+
+        ++mCurrentSampleIndex;
+
+        mBufferOffset = 2;
+        mBufferSizeRemaining = size;
+    }
+
+    if (!mIsAVC) {
+        *out = mBuffer;
+        mBuffer = NULL;
+
+        return OK;
+    }
+
+    uint8_t *data = (uint8_t *)mBuffer->data() + mBufferOffset;
+    assert(mBufferSizeRemaining >= 2);
+
+    size_t nal_length = (data[0] << 8) | data[1];
+    assert(mBufferSizeRemaining >= 2 + nal_length);
+
+    if (mNeedsNALFraming) {
+        // Insert marker.
+        data[-2] = data[-1] = data[0] = 0;
+        data[1] = 1;
+
+        mBuffer->set_range(mBufferOffset - 2, nal_length + 4);
+    } else {
+        mBuffer->set_range(mBufferOffset + 2, nal_length);
+    }
+
+    mBufferOffset += nal_length + 2;
+    mBufferSizeRemaining -= nal_length + 2;
+
+    if (mBufferSizeRemaining > 0) {
+        *out = mBuffer->clone();
+    } else {
+        *out = mBuffer;
+        mBuffer = NULL;
+    }
+
+    return OK;
+}
+
+bool SniffMPEG4(DataSource *source, String8 *mimeType, float *confidence) {
+    uint8_t header[8];
+
+    ssize_t n = source->read_at(4, header, sizeof(header));
+    if (n < (ssize_t)sizeof(header)) {
+        return false;
+    }
+
+    if (!memcmp(header, "ftyp3gp", 7) || !memcmp(header, "ftypmp42", 8)
+        || !memcmp(header, "ftypisom", 8) || !memcmp(header, "ftypM4V ", 8)) {
+        *mimeType = "video/mp4";
+        *confidence = 0.1;
+
+        return true;
+    }
+
+    return false;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp
new file mode 100644
index 0000000..6bdf282
--- /dev/null
+++ b/media/libstagefright/MPEG4Writer.cpp
@@ -0,0 +1,641 @@
+/*
+ * 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.
+ */
+
+#include <arpa/inet.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <ctype.h>
+#include <pthread.h>
+
+#include <media/stagefright/MPEG4Writer.h>
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/Utils.h>
+
+namespace android {
+
+class MPEG4Writer::Track {
+public:
+    Track(MPEG4Writer *owner, const sp<MetaData> &meta, MediaSource *source);
+    ~Track();
+
+    void start();
+    void stop();
+
+    int64_t getDuration() const;
+    void writeTrackHeader(int32_t trackID);
+
+private:
+    MPEG4Writer *mOwner;
+    sp<MetaData> mMeta;
+    MediaSource *mSource;
+    volatile bool mDone;
+
+    pthread_t mThread;
+
+    struct SampleInfo {
+        size_t size;
+        off_t offset;
+        int64_t timestamp;
+    };
+    List<SampleInfo> mSampleInfos;
+
+    void *mCodecSpecificData;
+    size_t mCodecSpecificDataSize;
+
+    static void *ThreadWrapper(void *me);
+    void threadEntry();
+
+    Track(const Track &);
+    Track &operator=(const Track &);
+};
+
+MPEG4Writer::MPEG4Writer(const char *filename)
+    : mFile(fopen(filename, "wb")),
+      mOffset(0),
+      mMdatOffset(0) {
+    assert(mFile != NULL);
+}
+
+MPEG4Writer::~MPEG4Writer() {
+    stop();
+
+    for (List<Track *>::iterator it = mTracks.begin();
+         it != mTracks.end(); ++it) {
+        delete *it;
+    }
+    mTracks.clear();
+}
+
+void MPEG4Writer::addSource(const sp<MetaData> &meta, MediaSource *source) {
+    Track *track = new Track(this, meta, source);
+    mTracks.push_back(track);
+}
+
+void MPEG4Writer::start() {
+    if (mFile == NULL) {
+        return;
+    }
+
+    beginBox("ftyp");
+      writeFourcc("isom");
+      writeInt32(0);
+      writeFourcc("isom");
+    endBox();
+
+    mMdatOffset = mOffset;
+    write("\x00\x00\x00\x01mdat????????", 16);
+
+    for (List<Track *>::iterator it = mTracks.begin();
+         it != mTracks.end(); ++it) {
+        (*it)->start();
+    }
+}
+
+void MPEG4Writer::stop() {
+    if (mFile == NULL) {
+        return;
+    }
+
+    int64_t max_duration = 0;
+    for (List<Track *>::iterator it = mTracks.begin();
+         it != mTracks.end(); ++it) {
+        (*it)->stop();
+
+        int64_t duration = (*it)->getDuration();
+        if (duration > max_duration) {
+            max_duration = duration;
+        }
+    }
+
+    // Fix up the size of the 'mdat' chunk.
+    fseek(mFile, mMdatOffset + 8, SEEK_SET);
+    int64_t size = mOffset - mMdatOffset;
+    size = hton64(size);
+    fwrite(&size, 1, 8, mFile);
+    fseek(mFile, mOffset, SEEK_SET);
+
+    time_t now = time(NULL);
+
+    beginBox("moov");
+
+      beginBox("mvhd");
+        writeInt32(0);             // version=0, flags=0
+        writeInt32(now);           // creation time
+        writeInt32(now);           // modification time
+        writeInt32(1000);          // timescale
+        writeInt32(max_duration);
+        writeInt32(0x10000);       // rate
+        writeInt16(0x100);         // volume
+        writeInt16(0);             // reserved
+        writeInt32(0);             // reserved
+        writeInt32(0);             // reserved
+        writeInt32(0x10000);       // matrix
+        writeInt32(0);
+        writeInt32(0);
+        writeInt32(0);
+        writeInt32(0x10000);
+        writeInt32(0);
+        writeInt32(0);
+        writeInt32(0);
+        writeInt32(0x40000000);
+        writeInt32(0);             // predefined
+        writeInt32(0);             // predefined
+        writeInt32(0);             // predefined
+        writeInt32(0);             // predefined
+        writeInt32(0);             // predefined
+        writeInt32(0);             // predefined
+        writeInt32(mTracks.size() + 1);  // nextTrackID
+      endBox();  // mvhd
+
+      int32_t id = 1;
+      for (List<Track *>::iterator it = mTracks.begin();
+           it != mTracks.end(); ++it, ++id) {
+          (*it)->writeTrackHeader(id);
+      }
+    endBox();  // moov
+
+    assert(mBoxes.empty());
+
+    fclose(mFile);
+    mFile = NULL;
+}
+
+off_t MPEG4Writer::addSample(MediaBuffer *buffer) {
+    Mutex::Autolock autoLock(mLock);
+
+    off_t old_offset = mOffset;
+
+    fwrite((const uint8_t *)buffer->data() + buffer->range_offset(),
+           1, buffer->range_length(), mFile);
+
+    mOffset += buffer->range_length();
+
+    return old_offset;
+}
+
+void MPEG4Writer::beginBox(const char *fourcc) {
+    assert(strlen(fourcc) == 4);
+
+    mBoxes.push_back(mOffset);
+
+    writeInt32(0);
+    writeFourcc(fourcc);
+}
+
+void MPEG4Writer::endBox() {
+    assert(!mBoxes.empty());
+
+    off_t offset = *--mBoxes.end();
+    mBoxes.erase(--mBoxes.end());
+
+    fseek(mFile, offset, SEEK_SET);
+    writeInt32(mOffset - offset);
+    mOffset -= 4;
+    fseek(mFile, mOffset, SEEK_SET);
+}
+
+void MPEG4Writer::writeInt8(int8_t x) {
+    fwrite(&x, 1, 1, mFile);
+    ++mOffset;
+}
+
+void MPEG4Writer::writeInt16(int16_t x) {
+    x = htons(x);
+    fwrite(&x, 1, 2, mFile);
+    mOffset += 2;
+}
+
+void MPEG4Writer::writeInt32(int32_t x) {
+    x = htonl(x);
+    fwrite(&x, 1, 4, mFile);
+    mOffset += 4;
+}
+
+void MPEG4Writer::writeInt64(int64_t x) {
+    x = hton64(x);
+    fwrite(&x, 1, 8, mFile);
+    mOffset += 8;
+}
+
+void MPEG4Writer::writeCString(const char *s) {
+    size_t n = strlen(s);
+
+    fwrite(s, 1, n + 1, mFile);
+    mOffset += n + 1;
+}
+
+void MPEG4Writer::writeFourcc(const char *s) {
+    assert(strlen(s) == 4);
+    fwrite(s, 1, 4, mFile);
+    mOffset += 4;
+}
+
+void MPEG4Writer::write(const void *data, size_t size) {
+    fwrite(data, 1, size, mFile);
+    mOffset += size;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+MPEG4Writer::Track::Track(
+        MPEG4Writer *owner, const sp<MetaData> &meta, MediaSource *source)
+    : mOwner(owner),
+      mMeta(meta),
+      mSource(source),
+      mDone(false),
+      mCodecSpecificData(NULL),
+      mCodecSpecificDataSize(0) {
+}
+
+MPEG4Writer::Track::~Track() {
+    stop();
+
+    if (mCodecSpecificData != NULL) {
+        free(mCodecSpecificData);
+        mCodecSpecificData = NULL;
+    }
+}
+
+void MPEG4Writer::Track::start() {
+    mSource->start();
+
+    pthread_attr_t attr;
+    pthread_attr_init(&attr);
+    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
+
+    mDone = false;
+
+    int err = pthread_create(&mThread, &attr, ThreadWrapper, this);
+    assert(err == 0);
+
+    pthread_attr_destroy(&attr);
+}
+
+void MPEG4Writer::Track::stop() {
+    if (mDone) {
+        return;
+    }
+
+    mDone = true;
+
+    void *dummy;
+    pthread_join(mThread, &dummy);
+
+    mSource->stop();
+}
+
+// static
+void *MPEG4Writer::Track::ThreadWrapper(void *me) {
+    Track *track = static_cast<Track *>(me);
+
+    track->threadEntry();
+
+    return NULL;
+}
+
+void MPEG4Writer::Track::threadEntry() {
+    bool is_mpeg4 = false;
+    sp<MetaData> meta = mSource->getFormat();
+    const char *mime;
+    meta->findCString(kKeyMIMEType, &mime);
+    is_mpeg4 = !strcasecmp(mime, "video/mp4v-es");
+
+    MediaBuffer *buffer;
+    while (!mDone && mSource->read(&buffer) == OK) {
+        if (buffer->range_length() == 0) {
+            buffer->release();
+            buffer = NULL;
+
+            continue;
+        }
+
+        if (mCodecSpecificData == NULL && is_mpeg4) {
+            const uint8_t *data =
+                (const uint8_t *)buffer->data() + buffer->range_offset();
+
+            const size_t size = buffer->range_length();
+
+            size_t offset = 0;
+            while (offset + 3 < size) {
+                if (data[offset] == 0x00 && data[offset + 1] == 0x00
+                    && data[offset + 2] == 0x01 && data[offset + 3] == 0xb6) {
+                    break;
+                }
+
+                ++offset;
+            }
+
+            assert(offset + 3 < size);
+
+            mCodecSpecificDataSize = offset;
+            mCodecSpecificData = malloc(offset);
+            memcpy(mCodecSpecificData, data, offset);
+
+            buffer->set_range(buffer->range_offset() + offset, size - offset);
+        }
+
+        off_t offset = mOwner->addSample(buffer);
+
+        SampleInfo info;
+        info.size = buffer->range_length();
+        info.offset = offset;
+
+        int32_t units, scale;
+        bool success =
+            buffer->meta_data()->findInt32(kKeyTimeUnits, &units);
+        assert(success);
+        success =
+            buffer->meta_data()->findInt32(kKeyTimeScale, &scale);
+        assert(success);
+
+        info.timestamp = (int64_t)units * 1000 / scale;
+
+        mSampleInfos.push_back(info);
+
+        buffer->release();
+        buffer = NULL;
+    }
+}
+
+int64_t MPEG4Writer::Track::getDuration() const {
+    return 10000;  // XXX
+}
+
+void MPEG4Writer::Track::writeTrackHeader(int32_t trackID) {
+    const char *mime;
+    bool success = mMeta->findCString(kKeyMIMEType, &mime);
+    assert(success);
+
+    bool is_audio = !strncasecmp(mime, "audio/", 6);
+
+    time_t now = time(NULL);
+
+    mOwner->beginBox("trak");
+
+      mOwner->beginBox("tkhd");
+        mOwner->writeInt32(0);             // version=0, flags=0
+        mOwner->writeInt32(now);           // creation time
+        mOwner->writeInt32(now);           // modification time
+        mOwner->writeInt32(trackID);
+        mOwner->writeInt32(0);             // reserved
+        mOwner->writeInt32(getDuration());
+        mOwner->writeInt32(0);             // reserved
+        mOwner->writeInt32(0);             // reserved
+        mOwner->writeInt16(0);             // layer
+        mOwner->writeInt16(0);             // alternate group
+        mOwner->writeInt16(is_audio ? 0x100 : 0);  // volume
+        mOwner->writeInt16(0);             // reserved
+
+        mOwner->writeInt32(0x10000);       // matrix
+        mOwner->writeInt32(0);
+        mOwner->writeInt32(0);
+        mOwner->writeInt32(0);
+        mOwner->writeInt32(0x10000);
+        mOwner->writeInt32(0);
+        mOwner->writeInt32(0);
+        mOwner->writeInt32(0);
+        mOwner->writeInt32(0x40000000);
+
+        if (is_audio) {
+            mOwner->writeInt32(0);
+            mOwner->writeInt32(0);
+        } else {
+            int32_t width, height;
+            bool success = mMeta->findInt32(kKeyWidth, &width);
+            success = success && mMeta->findInt32(kKeyHeight, &height);
+            assert(success);
+
+            mOwner->writeInt32(width);
+            mOwner->writeInt32(height);
+        }
+      mOwner->endBox();  // tkhd
+
+      mOwner->beginBox("mdia");
+
+        mOwner->beginBox("mdhd");
+          mOwner->writeInt32(0);             // version=0, flags=0
+          mOwner->writeInt32(now);           // creation time
+          mOwner->writeInt32(now);           // modification time
+          mOwner->writeInt32(1000);          // timescale
+          mOwner->writeInt32(getDuration());
+          mOwner->writeInt16(0);             // language code XXX
+          mOwner->writeInt16(0);             // predefined
+        mOwner->endBox();
+
+        mOwner->beginBox("hdlr");
+          mOwner->writeInt32(0);             // version=0, flags=0
+          mOwner->writeInt32(0);             // predefined
+          mOwner->writeFourcc(is_audio ? "soun" : "vide");
+          mOwner->writeInt32(0);             // reserved
+          mOwner->writeInt32(0);             // reserved
+          mOwner->writeInt32(0);             // reserved
+          mOwner->writeCString("");          // name
+        mOwner->endBox();
+
+        mOwner->beginBox("minf");
+
+          mOwner->beginBox("dinf");
+            mOwner->beginBox("dref");
+              mOwner->writeInt32(0);  // version=0, flags=0
+              mOwner->writeInt32(1);
+              mOwner->beginBox("url ");
+                mOwner->writeInt32(1);  // version=0, flags=1
+              mOwner->endBox();  // url
+            mOwner->endBox();  // dref
+          mOwner->endBox();  // dinf
+
+          if (is_audio) {
+              mOwner->beginBox("smhd");
+              mOwner->writeInt32(0);           // version=0, flags=0
+              mOwner->writeInt16(0);           // balance
+              mOwner->writeInt16(0);           // reserved
+              mOwner->endBox();
+          } else {
+              mOwner->beginBox("vmhd");
+              mOwner->writeInt32(0x00000001);  // version=0, flags=1
+              mOwner->writeInt16(0);           // graphics mode
+              mOwner->writeInt16(0);           // opcolor
+              mOwner->writeInt16(0);
+              mOwner->writeInt16(0);
+              mOwner->endBox();
+          }
+        mOwner->endBox();  // minf
+
+        mOwner->beginBox("stbl");
+
+          mOwner->beginBox("stsd");
+            mOwner->writeInt32(0);               // version=0, flags=0
+            mOwner->writeInt32(1);               // entry count
+            if (is_audio) {
+                mOwner->beginBox("xxxx");          // audio format XXX
+                  mOwner->writeInt32(0);           // reserved
+                  mOwner->writeInt16(0);           // reserved
+                  mOwner->writeInt16(0);           // data ref index
+                  mOwner->writeInt32(0);           // reserved
+                  mOwner->writeInt32(0);           // reserved
+                  mOwner->writeInt16(2);           // channel count
+                  mOwner->writeInt16(16);          // sample size
+                  mOwner->writeInt16(0);           // predefined
+                  mOwner->writeInt16(0);           // reserved
+
+                  int32_t samplerate;
+                  bool success = mMeta->findInt32(kKeySampleRate, &samplerate);
+                  assert(success);
+
+                  mOwner->writeInt32(samplerate << 16);
+                mOwner->endBox();
+            } else {
+                if (!strcasecmp("video/mp4v-es", mime)) {
+                    mOwner->beginBox("mp4v");
+                } else if (!strcasecmp("video/3gpp", mime)) {
+                    mOwner->beginBox("s263");
+                } else {
+                    assert(!"should not be here, unknown mime type.");
+                }
+
+                  mOwner->writeInt32(0);           // reserved
+                  mOwner->writeInt16(0);           // reserved
+                  mOwner->writeInt16(0);           // data ref index
+                  mOwner->writeInt16(0);           // predefined
+                  mOwner->writeInt16(0);           // reserved
+                  mOwner->writeInt32(0);           // predefined
+                  mOwner->writeInt32(0);           // predefined
+                  mOwner->writeInt32(0);           // predefined
+
+                  int32_t width, height;
+                  bool success = mMeta->findInt32(kKeyWidth, &width);
+                  success = success && mMeta->findInt32(kKeyHeight, &height);
+                  assert(success);
+
+                  mOwner->writeInt16(width);
+                  mOwner->writeInt16(height);
+                  mOwner->writeInt32(0x480000);    // horiz resolution
+                  mOwner->writeInt32(0x480000);    // vert resolution
+                  mOwner->writeInt32(0);           // reserved
+                  mOwner->writeInt16(1);           // frame count
+                  mOwner->write("                                ", 32);
+                  mOwner->writeInt16(0x18);        // depth
+                  mOwner->writeInt16(-1);          // predefined
+
+                  assert(23 + mCodecSpecificDataSize < 128);
+
+                  if (!strcasecmp("video/mp4v-es", mime)) {
+                      mOwner->beginBox("esds");
+
+                        mOwner->writeInt32(0);           // version=0, flags=0
+
+                        mOwner->writeInt8(0x03);  // ES_DescrTag
+                        mOwner->writeInt8(23 + mCodecSpecificDataSize);
+                        mOwner->writeInt16(0x0000);  // ES_ID
+                        mOwner->writeInt8(0x1f);
+
+                        mOwner->writeInt8(0x04);  // DecoderConfigDescrTag
+                        mOwner->writeInt8(15 + mCodecSpecificDataSize);
+                        mOwner->writeInt8(0x20);  // objectTypeIndication ISO/IEC 14492-2
+                        mOwner->writeInt8(0x11);  // streamType VisualStream
+
+                        static const uint8_t kData[] = {
+                            0x01, 0x77, 0x00,
+                            0x00, 0x03, 0xe8, 0x00,
+                            0x00, 0x03, 0xe8, 0x00
+                        };
+                        mOwner->write(kData, sizeof(kData));
+                        
+                        mOwner->writeInt8(0x05);  // DecoderSpecificInfoTag
+
+                        mOwner->writeInt8(mCodecSpecificDataSize);
+                        mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
+
+                        static const uint8_t kData2[] = {
+                            0x06,  // SLConfigDescriptorTag
+                            0x01,
+                            0x02
+                        };
+                        mOwner->write(kData2, sizeof(kData2));
+
+                      mOwner->endBox();  // esds
+                  } else if (!strcasecmp("video/3gpp", mime)) {
+                      mOwner->beginBox("d263");
+
+                          mOwner->writeInt32(0);  // vendor
+                          mOwner->writeInt8(0);   // decoder version
+                          mOwner->writeInt8(10);  // level: 10
+                          mOwner->writeInt8(0);   // profile: 0
+
+                      mOwner->endBox();  // d263
+                  }
+                mOwner->endBox();  // mp4v or s263
+            }
+          mOwner->endBox();  // stsd
+
+          mOwner->beginBox("stts");
+            mOwner->writeInt32(0);  // version=0, flags=0
+            mOwner->writeInt32(mSampleInfos.size() - 1);
+
+            List<SampleInfo>::iterator it = mSampleInfos.begin();
+            int64_t last = (*it).timestamp;
+            ++it;
+            while (it != mSampleInfos.end()) {
+                mOwner->writeInt32(1);
+                mOwner->writeInt32((*it).timestamp - last);
+
+                last = (*it).timestamp;
+
+                ++it;
+            }
+          mOwner->endBox();  // stts
+
+          mOwner->beginBox("stsz");
+            mOwner->writeInt32(0);  // version=0, flags=0
+            mOwner->writeInt32(0);  // default sample size
+            mOwner->writeInt32(mSampleInfos.size());
+            for (List<SampleInfo>::iterator it = mSampleInfos.begin();
+                 it != mSampleInfos.end(); ++it) {
+                mOwner->writeInt32((*it).size);
+            }
+          mOwner->endBox();  // stsz
+
+          mOwner->beginBox("stsc");
+            mOwner->writeInt32(0);  // version=0, flags=0
+            mOwner->writeInt32(mSampleInfos.size());
+            int32_t n = 1;
+            for (List<SampleInfo>::iterator it = mSampleInfos.begin();
+                 it != mSampleInfos.end(); ++it, ++n) {
+                mOwner->writeInt32(n);
+                mOwner->writeInt32(1);
+                mOwner->writeInt32(1);
+            }
+          mOwner->endBox();  // stsc
+
+          mOwner->beginBox("co64");
+            mOwner->writeInt32(0);  // version=0, flags=0
+            mOwner->writeInt32(mSampleInfos.size());
+            for (List<SampleInfo>::iterator it = mSampleInfos.begin();
+                 it != mSampleInfos.end(); ++it, ++n) {
+                mOwner->writeInt64((*it).offset);
+            }
+          mOwner->endBox();  // co64
+
+        mOwner->endBox();  // stbl
+      mOwner->endBox();  // mdia
+    mOwner->endBox();  // trak
+}
+
+}  // namespace android
diff --git a/media/libstagefright/MediaBuffer.cpp b/media/libstagefright/MediaBuffer.cpp
new file mode 100644
index 0000000..cd78dbd
--- /dev/null
+++ b/media/libstagefright/MediaBuffer.cpp
@@ -0,0 +1,174 @@
+/*
+ * 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 "MediaBuffer"
+#include <utils/Log.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <errno.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MetaData.h>
+
+namespace android {
+
+// XXX make this truly atomic.
+static int atomic_add(int *value, int delta) {
+    int prev_value = *value;
+    *value += delta;
+
+    return prev_value;
+}
+
+MediaBuffer::MediaBuffer(void *data, size_t size)
+    : mObserver(NULL),
+      mNextBuffer(NULL),
+      mRefCount(0),
+      mData(data),
+      mSize(size),
+      mRangeOffset(0),
+      mRangeLength(size),
+      mOwnsData(false),
+      mMetaData(new MetaData),
+      mOriginal(NULL) {
+}
+
+MediaBuffer::MediaBuffer(size_t size)
+    : mObserver(NULL),
+      mNextBuffer(NULL),
+      mRefCount(0),
+      mData(malloc(size)),
+      mSize(size),
+      mRangeOffset(0),
+      mRangeLength(size),
+      mOwnsData(true),
+      mMetaData(new MetaData),
+      mOriginal(NULL) {
+}
+
+void MediaBuffer::release() {
+    if (mObserver == NULL) {
+        assert(mRefCount == 0);
+        delete this;
+        return;
+    }
+
+    int prevCount = atomic_add(&mRefCount, -1);
+    if (prevCount == 1) {
+        if (mObserver == NULL) {
+            delete this;
+            return;
+        }
+
+        mObserver->signalBufferReturned(this);
+    }
+    assert(prevCount > 0);
+}
+
+void MediaBuffer::claim() {
+    assert(mObserver != NULL);
+    assert(mRefCount == 1);
+
+    mRefCount = 0;
+}
+
+void MediaBuffer::add_ref() {
+    atomic_add(&mRefCount, 1);
+}
+
+void *MediaBuffer::data() const {
+    return mData;
+}
+
+size_t MediaBuffer::size() const {
+    return mSize;
+}
+
+size_t MediaBuffer::range_offset() const {
+    return mRangeOffset;
+}
+
+size_t MediaBuffer::range_length() const {
+    return mRangeLength;
+}
+
+void MediaBuffer::set_range(size_t offset, size_t length) {
+    if (offset < 0 || offset + length > mSize) {
+        LOGE("offset = %d, length = %d, mSize = %d", offset, length, mSize);
+    }
+    assert(offset >= 0 && offset + length <= mSize);
+
+    mRangeOffset = offset;
+    mRangeLength = length;
+}
+
+sp<MetaData> MediaBuffer::meta_data() {
+    return mMetaData;
+}
+
+void MediaBuffer::reset() {
+    mMetaData->clear();
+    set_range(0, mSize);
+}
+
+MediaBuffer::~MediaBuffer() {
+    assert(mObserver == NULL);
+
+    if (mOwnsData && mData != NULL) {
+        free(mData);
+        mData = NULL;
+    }
+
+    if (mOriginal != NULL) {
+        mOriginal->release();
+        mOriginal = NULL;
+    }
+}
+
+void MediaBuffer::setObserver(MediaBufferObserver *observer) {
+    assert(observer == NULL || mObserver == NULL);
+    mObserver = observer;
+}
+
+void MediaBuffer::setNextBuffer(MediaBuffer *buffer) {
+    mNextBuffer = buffer;
+}
+
+MediaBuffer *MediaBuffer::nextBuffer() {
+    return mNextBuffer;
+}
+
+int MediaBuffer::refcount() const {
+    return mRefCount;
+}
+
+MediaBuffer *MediaBuffer::clone() {
+    MediaBuffer *buffer = new MediaBuffer(mData, mSize);
+    buffer->set_range(mRangeOffset, mRangeLength);
+    buffer->mMetaData = new MetaData(*mMetaData.get());
+
+    add_ref();
+    buffer->mOriginal = this;
+
+    return buffer;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/MediaBufferGroup.cpp b/media/libstagefright/MediaBufferGroup.cpp
new file mode 100644
index 0000000..aec7722
--- /dev/null
+++ b/media/libstagefright/MediaBufferGroup.cpp
@@ -0,0 +1,88 @@
+/*
+ * 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 "MediaBufferGroup"
+#include <utils/Log.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaBufferGroup.h>
+
+namespace android {
+
+MediaBufferGroup::MediaBufferGroup()
+    : mFirstBuffer(NULL),
+      mLastBuffer(NULL) {
+}
+
+MediaBufferGroup::~MediaBufferGroup() {
+    MediaBuffer *next;
+    for (MediaBuffer *buffer = mFirstBuffer; buffer != NULL;
+         buffer = next) {
+        next = buffer->nextBuffer();
+
+        assert(buffer->refcount() == 0);
+
+        buffer->setObserver(NULL);
+        buffer->release();
+    }
+}
+
+void MediaBufferGroup::add_buffer(MediaBuffer *buffer) {
+    Mutex::Autolock autoLock(mLock);
+
+    buffer->setObserver(this);
+
+    if (mLastBuffer) {
+        mLastBuffer->setNextBuffer(buffer);
+    } else {
+        mFirstBuffer = buffer;
+    }
+
+    mLastBuffer = buffer;
+}
+
+status_t MediaBufferGroup::acquire_buffer(MediaBuffer **out) {
+    Mutex::Autolock autoLock(mLock);
+
+    for (;;) {
+        for (MediaBuffer *buffer = mFirstBuffer;
+             buffer != NULL; buffer = buffer->nextBuffer()) {
+            if (buffer->refcount() == 0) {
+                buffer->add_ref();
+                buffer->reset();
+
+                *out = buffer;
+                goto exit;
+            }
+        }
+
+        // All buffers are in use. Block until one of them is returned to us.
+        mCondition.wait(mLock);
+    }
+
+exit:
+    return OK;
+}
+
+void MediaBufferGroup::signalBufferReturned(MediaBuffer *) {
+    Mutex::Autolock autoLock(mLock);
+    mCondition.signal();
+}
+
+}  // namespace android
diff --git a/media/libstagefright/MediaExtractor.cpp b/media/libstagefright/MediaExtractor.cpp
new file mode 100644
index 0000000..bc66794
--- /dev/null
+++ b/media/libstagefright/MediaExtractor.cpp
@@ -0,0 +1,54 @@
+/*
+ * 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_NDEBUG 0
+#define LOG_TAG "MediaExtractor"
+#include <utils/Log.h>
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MP3Extractor.h>
+#include <media/stagefright/MPEG4Extractor.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <utils/String8.h>
+
+namespace android {
+
+// static
+MediaExtractor *MediaExtractor::Create(DataSource *source, const char *mime) {
+    String8 tmp;
+    if (mime == NULL) {
+        float confidence;
+        if (!source->sniff(&tmp, &confidence)) {
+            LOGE("FAILED to autodetect media content.");
+
+            return NULL;
+        }
+
+        mime = tmp.string();
+        LOGI("Autodetected media content as '%s' with confidence %.2f",
+             mime, confidence);
+    }
+
+    if (!strcasecmp(mime, "video/mp4") || !strcasecmp(mime, "audio/mp4")) {
+        return new MPEG4Extractor(source);
+    } else if (!strcasecmp(mime, "audio/mpeg")) {
+        return new MP3Extractor(source);
+    }
+
+    return NULL;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/MediaPlayerImpl.cpp b/media/libstagefright/MediaPlayerImpl.cpp
new file mode 100644
index 0000000..78fcdee
--- /dev/null
+++ b/media/libstagefright/MediaPlayerImpl.cpp
@@ -0,0 +1,693 @@
+/*
+ * 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_NDEBUG 0
+#define LOG_TAG "MediaPlayerImpl"
+#include "utils/Log.h"
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <OMX_Component.h>
+
+#include <unistd.h>
+
+#include <media/stagefright/AudioPlayer.h>
+#include <media/stagefright/CachingDataSource.h>
+// #include <media/stagefright/CameraSource.h>
+#include <media/stagefright/HTTPDataSource.h>
+#include <media/stagefright/HTTPStream.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <media/stagefright/MediaPlayerImpl.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/MmapSource.h>
+#include <media/stagefright/OMXDecoder.h>
+#include <media/stagefright/QComHardwareRenderer.h>
+#include <media/stagefright/ShoutcastSource.h>
+#include <media/stagefright/SoftwareRenderer.h>
+#include <media/stagefright/SurfaceRenderer.h>
+#include <media/stagefright/TimeSource.h>
+#include <ui/PixelFormat.h>
+#include <ui/Surface.h>
+
+namespace android {
+
+MediaPlayerImpl::MediaPlayerImpl(const char *uri)
+    : mInitCheck(NO_INIT),
+      mExtractor(NULL), 
+      mTimeSource(NULL),
+      mAudioSource(NULL),
+      mAudioDecoder(NULL),
+      mAudioPlayer(NULL),
+      mVideoSource(NULL),
+      mVideoDecoder(NULL),
+      mVideoWidth(0),
+      mVideoHeight(0),
+      mVideoPosition(0),
+      mDuration(0),
+      mPlaying(false),
+      mPaused(false),
+      mRenderer(NULL),
+      mSeeking(false),
+      mFrameSize(0),
+      mUseSoftwareColorConversion(false) {
+    LOGI("MediaPlayerImpl(%s)", uri);
+    DataSource::RegisterDefaultSniffers();
+
+    status_t err = mClient.connect();
+    if (err != OK) {
+        LOGE("Failed to connect to OMXClient.");
+        return;
+    }
+
+    if (!strncasecmp("shoutcast://", uri, 12)) {
+        setAudioSource(makeShoutcastSource(uri));
+#if 0
+    } else if (!strncasecmp("camera:", uri, 7)) {
+        mVideoWidth = 480;
+        mVideoHeight = 320;
+        mVideoDecoder = CameraSource::Create();
+#endif
+    } else {
+        DataSource *source = NULL;
+        if (!strncasecmp("file://", uri, 7)) {
+            source = new MmapSource(uri + 7);
+        } else if (!strncasecmp("http://", uri, 7)) {
+            source = new HTTPDataSource(uri);
+            source = new CachingDataSource(source, 64 * 1024, 10);
+        } else {
+            // Assume it's a filename.
+            source = new MmapSource(uri);
+        }
+
+        mExtractor = MediaExtractor::Create(source);
+
+        if (mExtractor == NULL) {
+            return;
+        }
+    }
+
+    init();
+
+    mInitCheck = OK;
+}
+
+MediaPlayerImpl::MediaPlayerImpl(int fd, int64_t offset, int64_t length)
+    : mInitCheck(NO_INIT),
+      mExtractor(NULL), 
+      mTimeSource(NULL),
+      mAudioSource(NULL),
+      mAudioDecoder(NULL),
+      mAudioPlayer(NULL),
+      mVideoSource(NULL),
+      mVideoDecoder(NULL),
+      mVideoWidth(0),
+      mVideoHeight(0),
+      mVideoPosition(0),
+      mDuration(0),
+      mPlaying(false),
+      mPaused(false),
+      mRenderer(NULL),
+      mSeeking(false),
+      mFrameSize(0),
+      mUseSoftwareColorConversion(false) {
+    LOGI("MediaPlayerImpl(%d, %lld, %lld)", fd, offset, length);
+    DataSource::RegisterDefaultSniffers();
+
+    status_t err = mClient.connect();
+    if (err != OK) {
+        LOGE("Failed to connect to OMXClient.");
+        return;
+    }
+
+    mExtractor = MediaExtractor::Create(
+            new MmapSource(fd, offset, length));
+
+    if (mExtractor == NULL) {
+        return;
+    }
+
+    init();
+
+    mInitCheck = OK;
+}
+
+status_t MediaPlayerImpl::initCheck() const {
+    return mInitCheck;
+}
+
+MediaPlayerImpl::~MediaPlayerImpl() {
+    stop();
+    setSurface(NULL);
+
+    LOGV("Shutting down audio.");
+    delete mAudioDecoder;
+    mAudioDecoder = NULL;
+
+    delete mAudioSource;
+    mAudioSource = NULL;
+
+    LOGV("Shutting down video.");
+    delete mVideoDecoder;
+    mVideoDecoder = NULL;
+
+    delete mVideoSource;
+    mVideoSource = NULL;
+
+    delete mExtractor;
+    mExtractor = NULL;
+
+    if (mInitCheck == OK) {
+        mClient.disconnect();
+    }
+
+    LOGV("~MediaPlayerImpl done.");
+}
+
+void MediaPlayerImpl::play() {
+    LOGI("play");
+
+    if (mPlaying) {
+        if (mPaused) {
+            if (mAudioSource != NULL) {
+                mAudioPlayer->resume();
+            }
+            mPaused = false;
+        }
+        return;
+    }
+
+    mPlaying = true;
+
+    if (mAudioSource != NULL) {
+        mAudioPlayer = new AudioPlayer(mAudioSink);
+        mAudioPlayer->setSource(mAudioDecoder);
+        mAudioPlayer->start();
+        mTimeSource = mAudioPlayer;
+    } else {
+        mTimeSource = new SystemTimeSource;
+    }
+
+    if (mVideoDecoder != NULL) {
+        pthread_attr_t attr;
+        pthread_attr_init(&attr);
+        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
+
+        pthread_create(&mVideoThread, &attr, VideoWrapper, this);
+
+        pthread_attr_destroy(&attr);
+    }
+}
+
+void MediaPlayerImpl::pause() {
+    if (!mPlaying || mPaused) {
+        return;
+    }
+
+    if (mAudioSource != NULL) {
+        mAudioPlayer->pause();
+    }
+
+    mPaused = true;
+}
+
+void MediaPlayerImpl::stop() {
+    if (!mPlaying) {
+        return;
+    }
+
+    mPlaying = false;
+
+    if (mVideoDecoder != NULL) {
+        void *dummy;
+        pthread_join(mVideoThread, &dummy);
+    }
+
+    if (mAudioSource != NULL) {
+        mAudioPlayer->stop();
+
+        delete mAudioPlayer;
+        mAudioPlayer = NULL;
+    } else {
+        delete mTimeSource;
+    }
+
+    mTimeSource = NULL;
+}
+
+// static
+void *MediaPlayerImpl::VideoWrapper(void *me) {
+    ((MediaPlayerImpl *)me)->videoEntry();
+
+    return NULL;
+}
+
+void MediaPlayerImpl::videoEntry() {
+    bool firstFrame = true;
+    bool eof = false;
+
+    status_t err = mVideoDecoder->start();
+    assert(err == OK);
+
+    while (mPlaying) {
+        MediaBuffer *buffer;
+
+        MediaSource::ReadOptions options;
+        bool seeking = false;
+
+        {
+            Mutex::Autolock autoLock(mLock);
+            if (mSeeking) {
+                LOGI("seek-options to %lld", mSeekTimeUs);
+                options.setSeekTo(mSeekTimeUs);
+
+                mSeeking = false;
+                seeking = true;
+                eof = false;
+            }
+        }
+
+        if (eof || mPaused) {
+            usleep(100000);
+            continue;
+        }
+
+        status_t err = mVideoDecoder->read(&buffer, &options);
+        assert((err == OK && buffer != NULL) || (err != OK && buffer == NULL));
+
+        if (err == ERROR_END_OF_STREAM || err != OK) {
+            eof = true;
+            continue;
+        }
+
+        if (buffer->range_length() == 0) {
+            // The final buffer is empty.
+            buffer->release();
+            continue;
+        }
+
+        int32_t units, scale;
+        bool success =
+            buffer->meta_data()->findInt32(kKeyTimeUnits, &units);
+        assert(success);
+        success =
+            buffer->meta_data()->findInt32(kKeyTimeScale, &scale);
+        assert(success);
+
+        int64_t pts_us = (int64_t)units * 1000000 / scale;
+        {
+            Mutex::Autolock autoLock(mLock);
+            mVideoPosition = pts_us;
+        }
+
+        if (seeking && mAudioPlayer != NULL) {
+            // Now that we know where exactly video seeked (taking sync-samples
+            // into account), we will seek the audio track to the same time.
+            mAudioPlayer->seekTo(pts_us);
+        }
+
+        if (firstFrame || seeking) {
+            mTimeSourceDeltaUs = mTimeSource->getRealTimeUs() - pts_us;
+            firstFrame = false;
+        }
+
+        displayOrDiscardFrame(buffer, pts_us);
+    }
+
+    mVideoDecoder->stop();
+}
+
+void MediaPlayerImpl::displayOrDiscardFrame(
+        MediaBuffer *buffer, int64_t pts_us) {
+    for (;;) {
+        if (!mPlaying || mPaused) {
+            buffer->release();
+            buffer = NULL;
+
+            return;
+        }
+
+        int64_t realtime_us, mediatime_us;
+        if (mAudioPlayer != NULL
+            && mAudioPlayer->getMediaTimeMapping(&realtime_us, &mediatime_us)) {
+            mTimeSourceDeltaUs = realtime_us - mediatime_us;
+        }
+
+        int64_t now_us = mTimeSource->getRealTimeUs();
+        now_us -= mTimeSourceDeltaUs;
+
+        int64_t delay_us = pts_us - now_us;
+
+        if (delay_us < -15000) {
+            // We're late.
+
+            LOGI("we're late by %lld ms, dropping a frame\n",
+                 -delay_us / 1000);
+
+            buffer->release();
+            buffer = NULL;
+            return;
+        } else if (delay_us > 100000) {
+            LOGI("we're much too early (by %lld ms)\n",
+                 delay_us / 1000);
+            usleep(100000);
+            continue;
+        } else if (delay_us > 0) {
+            usleep(delay_us);
+        }
+
+        break;
+    }
+
+    {
+        Mutex::Autolock autoLock(mLock);
+        if (mRenderer != NULL) {
+            sendFrameToISurface(buffer);
+        }
+    }
+
+    buffer->release();
+    buffer = NULL;
+}
+
+void MediaPlayerImpl::init() {
+    if (mExtractor != NULL) {
+        int num_tracks;
+        assert(mExtractor->countTracks(&num_tracks) == OK);
+
+        mDuration = 0;
+
+        for (int i = 0; i < num_tracks; ++i) {
+            const sp<MetaData> meta = mExtractor->getTrackMetaData(i);
+            assert(meta != NULL);
+
+            const char *mime;
+            if (!meta->findCString(kKeyMIMEType, &mime)) {
+                continue;
+            }
+
+            bool is_audio = false;
+            bool is_acceptable = false;
+            if (!strncasecmp(mime, "audio/", 6)) {
+                is_audio = true;
+                is_acceptable = (mAudioSource == NULL);
+            } else if (!strncasecmp(mime, "video/", 6)) {
+                is_acceptable = (mVideoSource == NULL);
+            }
+
+            if (!is_acceptable) {
+                continue;
+            }
+
+            MediaSource *source;
+            if (mExtractor->getTrack(i, &source) != OK) {
+                continue;
+            }
+
+            int32_t units, scale;
+            if (meta->findInt32(kKeyDuration, &units)
+                && meta->findInt32(kKeyTimeScale, &scale)) {
+                int64_t duration_us = (int64_t)units * 1000000 / scale;
+                if (duration_us > mDuration) {
+                    mDuration = duration_us;
+                }
+            }
+
+            if (is_audio) {
+                setAudioSource(source);
+            } else {
+                setVideoSource(source);
+            }
+        }
+    }
+}
+
+void MediaPlayerImpl::setAudioSource(MediaSource *source) {
+    mAudioSource = source;
+
+    sp<MetaData> meta = source->getFormat();
+
+    mAudioDecoder = OMXDecoder::Create(&mClient, meta);
+    mAudioDecoder->setSource(source);
+}
+
+void MediaPlayerImpl::setVideoSource(MediaSource *source) {
+    LOGI("setVideoSource");
+    mVideoSource = source;
+
+    sp<MetaData> meta = source->getFormat();
+
+    bool success = meta->findInt32(kKeyWidth, &mVideoWidth);
+    assert(success);
+
+    success = meta->findInt32(kKeyHeight, &mVideoHeight);
+    assert(success);
+
+    mVideoDecoder = OMXDecoder::Create(&mClient, meta);
+    ((OMXDecoder *)mVideoDecoder)->setSource(source);
+
+    if (mISurface.get() != NULL || mSurface.get() != NULL) {
+        depopulateISurface();
+        populateISurface();
+    }
+}
+
+void MediaPlayerImpl::setSurface(const sp<Surface> &surface) {
+    LOGI("setSurface %p", surface.get());
+    Mutex::Autolock autoLock(mLock);
+
+    depopulateISurface();
+
+    mSurface = surface;
+    mISurface = NULL;
+
+    if (mSurface.get() != NULL) {
+        populateISurface();
+    }
+}
+
+void MediaPlayerImpl::setISurface(const sp<ISurface> &isurface) {
+    LOGI("setISurface %p", isurface.get());
+    Mutex::Autolock autoLock(mLock);
+
+    depopulateISurface();
+
+    mSurface = NULL;
+    mISurface = isurface;
+
+    if (mISurface.get() != NULL) {
+        populateISurface();
+    }
+}
+
+MediaSource *MediaPlayerImpl::makeShoutcastSource(const char *uri) {
+    if (strncasecmp(uri, "shoutcast://", 12)) {
+        return NULL;
+    }
+
+    string host;
+    string path;
+    int port;
+
+    char *slash = strchr(uri + 12, '/');
+    if (slash == NULL) {
+        host = uri + 12;
+        path = "/";
+    } else {
+        host = string(uri + 12, slash - (uri + 12));
+        path = slash;
+    }
+
+    char *colon = strchr(host.c_str(), ':');
+    if (colon == NULL) {
+        port = 80;
+    } else {
+        char *end;
+        long tmp = strtol(colon + 1, &end, 10);
+        assert(end > colon + 1);
+        assert(tmp > 0 && tmp < 65536);
+        port = tmp;
+
+        host = string(host, 0, colon - host.c_str());
+    }
+
+    LOGI("Connecting to host '%s', port %d, path '%s'",
+         host.c_str(), port, path.c_str());
+
+    HTTPStream *http = new HTTPStream;
+    int http_status;
+
+    for (;;) {
+        status_t err = http->connect(host.c_str(), port);
+        assert(err == OK);
+
+        err = http->send("GET ");
+        err = http->send(path.c_str());
+        err = http->send(" HTTP/1.1\r\n");
+        err = http->send("Host: ");
+        err = http->send(host.c_str());
+        err = http->send("\r\n");
+        err = http->send("Icy-MetaData: 1\r\n\r\n");
+
+        assert(OK == http->receive_header(&http_status));
+
+        if (http_status == 301 || http_status == 302) {
+            string location;
+            assert(http->find_header_value("Location", &location));
+
+            assert(string(location, 0, 7) == "http://");
+            location.erase(0, 7);
+            string::size_type slashPos = location.find('/');
+            if (slashPos == string::npos) {
+                slashPos = location.size();
+                location += '/';
+            }
+
+            http->disconnect();
+
+            LOGI("Redirecting to %s\n", location.c_str());
+
+            host = string(location, 0, slashPos);
+
+            string::size_type colonPos = host.find(':');
+            if (colonPos != string::npos) {
+                const char *start = host.c_str() + colonPos + 1;
+                char *end;
+                long tmp = strtol(start, &end, 10);
+                assert(end > start && *end == '\0');
+
+                port = (tmp >= 0 && tmp < 65536) ? (int)tmp : 80;
+            } else {
+                port = 80;
+            }
+
+            path = string(location, slashPos);
+
+            continue;
+        }
+
+        break;
+    }
+
+    if (http_status != 200) {
+        LOGE("Connection failed: http_status = %d", http_status);
+        return NULL;
+    }
+
+    MediaSource *source = new ShoutcastSource(http);
+
+    return source;
+}
+
+bool MediaPlayerImpl::isPlaying() const {
+    return mPlaying && !mPaused;
+}
+
+int64_t MediaPlayerImpl::getDuration() {
+    return mDuration;
+}
+
+int64_t MediaPlayerImpl::getPosition() {
+    int64_t position = 0;
+    if (mVideoSource != NULL) {
+        Mutex::Autolock autoLock(mLock);
+        position = mVideoPosition;
+    } else if (mAudioPlayer != NULL) {
+        position = mAudioPlayer->getMediaTimeUs();
+    }
+
+    return position;
+}
+
+status_t MediaPlayerImpl::seekTo(int64_t time) {
+    LOGI("seekTo %lld", time);
+
+    if (mPaused) {
+        return UNKNOWN_ERROR;
+    }
+
+    if (mVideoSource == NULL && mAudioPlayer != NULL) {
+        mAudioPlayer->seekTo(time);
+    } else {
+        Mutex::Autolock autoLock(mLock);
+        mSeekTimeUs = time;
+        mSeeking = true;
+    }
+
+    return OK;
+}
+
+void MediaPlayerImpl::populateISurface() {
+    if (mVideoSource == NULL) {
+        return;
+    }
+
+    sp<MetaData> meta = mVideoDecoder->getFormat();
+
+    int32_t format;
+    const char *component;
+    int32_t decodedWidth, decodedHeight;
+    bool success = meta->findInt32(kKeyColorFormat, &format);
+    success = success && meta->findCString(kKeyDecoderComponent, &component);
+    success = success && meta->findInt32(kKeyWidth, &decodedWidth);
+    success = success && meta->findInt32(kKeyHeight, &decodedHeight);
+    assert(success);
+
+    if (mSurface.get() != NULL) {
+        mRenderer =
+            new SurfaceRenderer(
+                    mSurface, mVideoWidth, mVideoHeight,
+                    decodedWidth, decodedHeight);
+    } else if (format == OMX_COLOR_FormatYUV420Planar
+        && !strncasecmp(component, "OMX.qcom.video.decoder.", 23)) {
+        mRenderer =
+            new QComHardwareRenderer(
+                    mISurface, mVideoWidth, mVideoHeight,
+                    decodedWidth, decodedHeight);
+    } else {
+        LOGW("Using software renderer.");
+        mRenderer = new SoftwareRenderer(
+                mISurface, mVideoWidth, mVideoHeight,
+                decodedWidth, decodedHeight);
+    }
+}
+
+void MediaPlayerImpl::depopulateISurface() {
+    delete mRenderer;
+    mRenderer = NULL;
+}
+
+void MediaPlayerImpl::sendFrameToISurface(MediaBuffer *buffer) {
+    void *platformPrivate;
+    if (!buffer->meta_data()->findPointer(
+                kKeyPlatformPrivate, &platformPrivate)) {
+        platformPrivate = NULL;
+    }
+
+    mRenderer->render(
+        (const uint8_t *)buffer->data() + buffer->range_offset(),
+        buffer->range_length(),
+        platformPrivate);
+}
+
+void MediaPlayerImpl::setAudioSink(
+        const sp<MediaPlayerBase::AudioSink> &audioSink) {
+    LOGI("setAudioSink %p", audioSink.get());
+    mAudioSink = audioSink;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/MediaSource.cpp b/media/libstagefright/MediaSource.cpp
new file mode 100644
index 0000000..ec89b74
--- /dev/null
+++ b/media/libstagefright/MediaSource.cpp
@@ -0,0 +1,60 @@
+/*
+ * 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.
+ */
+
+#include <media/stagefright/MediaSource.h>
+
+namespace android {
+
+MediaSource::MediaSource() {}
+
+MediaSource::~MediaSource() {}
+
+////////////////////////////////////////////////////////////////////////////////
+
+MediaSource::ReadOptions::ReadOptions() {
+    reset();
+}
+
+void MediaSource::ReadOptions::reset() {
+    mOptions = 0;
+    mSeekTimeUs = 0;
+    mLatenessUs = 0;
+}
+
+void MediaSource::ReadOptions::setSeekTo(int64_t time_us) {
+    mOptions |= kSeekTo_Option;
+    mSeekTimeUs = time_us;
+}
+
+void MediaSource::ReadOptions::clearSeekTo() {
+    mOptions &= ~kSeekTo_Option;
+    mSeekTimeUs = 0;
+}
+
+bool MediaSource::ReadOptions::getSeekTo(int64_t *time_us) const {
+    *time_us = mSeekTimeUs;
+    return (mOptions & kSeekTo_Option) != 0;
+}
+
+void MediaSource::ReadOptions::setLateBy(int64_t lateness_us) {
+    mLatenessUs = lateness_us;
+}
+
+int64_t MediaSource::ReadOptions::getLateBy() const {
+    return mLatenessUs;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/MetaData.cpp b/media/libstagefright/MetaData.cpp
new file mode 100644
index 0000000..5d23732b
--- /dev/null
+++ b/media/libstagefright/MetaData.cpp
@@ -0,0 +1,232 @@
+/*
+ * 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.
+ */
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <media/stagefright/MetaData.h>
+
+namespace android {
+
+MetaData::MetaData() {
+}
+
+MetaData::MetaData(const MetaData &from)
+    : RefBase(),
+      mItems(from.mItems) {
+}
+
+MetaData::~MetaData() {
+    clear();
+}
+
+void MetaData::clear() {
+    mItems.clear();
+}
+
+bool MetaData::remove(uint32_t key) {
+    ssize_t i = mItems.indexOfKey(key);
+
+    if (i < 0) {
+        return false;
+    }
+
+    mItems.removeItemsAt(i);
+
+    return true;
+}
+
+bool MetaData::setCString(uint32_t key, const char *value) {
+    return setData(key, TYPE_C_STRING, value, strlen(value) + 1);
+}
+
+bool MetaData::setInt32(uint32_t key, int32_t value) {
+    return setData(key, TYPE_INT32, &value, sizeof(value));
+}
+
+bool MetaData::setFloat(uint32_t key, float value) {
+    return setData(key, TYPE_FLOAT, &value, sizeof(value));
+}
+
+bool MetaData::setPointer(uint32_t key, void *value) {
+    return setData(key, TYPE_POINTER, &value, sizeof(value));
+}
+
+bool MetaData::findCString(uint32_t key, const char **value) {
+    uint32_t type;
+    const void *data;
+    size_t size;
+    if (!findData(key, &type, &data, &size) || type != TYPE_C_STRING) {
+        return false;
+    }
+
+    *value = (const char *)data;
+
+    return true;
+}
+
+bool MetaData::findInt32(uint32_t key, int32_t *value) {
+    uint32_t type;
+    const void *data;
+    size_t size;
+    if (!findData(key, &type, &data, &size) || type != TYPE_INT32) {
+        return false;
+    }
+
+    assert(size == sizeof(*value));
+
+    *value = *(int32_t *)data;
+
+    return true;
+}
+
+bool MetaData::findFloat(uint32_t key, float *value) {
+    uint32_t type;
+    const void *data;
+    size_t size;
+    if (!findData(key, &type, &data, &size) || type != TYPE_FLOAT) {
+        return false;
+    }
+
+    assert(size == sizeof(*value));
+
+    *value = *(float *)data;
+
+    return true;
+}
+
+bool MetaData::findPointer(uint32_t key, void **value) {
+    uint32_t type;
+    const void *data;
+    size_t size;
+    if (!findData(key, &type, &data, &size) || type != TYPE_POINTER) {
+        return false;
+    }
+
+    assert(size == sizeof(*value));
+
+    *value = *(void **)data;
+
+    return true;
+}
+
+bool MetaData::setData(
+        uint32_t key, uint32_t type, const void *data, size_t size) {
+    bool overwrote_existing = true;
+
+    ssize_t i = mItems.indexOfKey(key);
+    if (i < 0) {
+        typed_data item;
+        i = mItems.add(key, item);
+
+        overwrote_existing = false;
+    }
+
+    typed_data &item = mItems.editValueAt(i);
+
+    item.setData(type, data, size);
+
+    return overwrote_existing;
+}
+
+bool MetaData::findData(uint32_t key, uint32_t *type,
+                        const void **data, size_t *size) const {
+    ssize_t i = mItems.indexOfKey(key);
+
+    if (i < 0) {
+        return false;
+    }
+
+    const typed_data &item = mItems.valueAt(i);
+
+    item.getData(type, data, size);
+
+    return true;
+}
+
+MetaData::typed_data::typed_data()
+    : mType(0),
+      mSize(0) {
+}
+
+MetaData::typed_data::~typed_data() {
+    clear();
+}
+
+MetaData::typed_data::typed_data(const typed_data &from)
+    : mType(from.mType),
+      mSize(0) {
+    allocateStorage(from.mSize);
+    memcpy(storage(), from.storage(), mSize);
+}
+
+MetaData::typed_data &MetaData::typed_data::operator=(
+        const MetaData::typed_data &from) {
+    if (this != &from) {
+        clear();
+        mType = from.mType;
+        allocateStorage(from.mSize);
+        memcpy(storage(), from.storage(), mSize);
+    }
+
+    return *this;
+}
+
+void MetaData::typed_data::clear() {
+    freeStorage();
+
+    mType = 0;
+}
+
+void MetaData::typed_data::setData(
+        uint32_t type, const void *data, size_t size) {
+    clear();
+
+    mType = type;
+    allocateStorage(size);
+    memcpy(storage(), data, size);
+}
+
+void MetaData::typed_data::getData(
+        uint32_t *type, const void **data, size_t *size) const {
+    *type = mType;
+    *size = mSize;
+    *data = storage();
+}
+
+void MetaData::typed_data::allocateStorage(size_t size) {
+    mSize = size;
+
+    if (usesReservoir()) {
+        return;
+    }
+
+    u.ext_data = malloc(mSize);
+}
+
+void MetaData::typed_data::freeStorage() {
+    if (!usesReservoir()) {
+        if (u.ext_data) {
+            free(u.ext_data);
+        }
+    }
+
+    mSize = 0;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/MmapSource.cpp b/media/libstagefright/MmapSource.cpp
new file mode 100644
index 0000000..7cb861c
--- /dev/null
+++ b/media/libstagefright/MmapSource.cpp
@@ -0,0 +1,112 @@
+/*
+ * 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_NDEBUG 0
+#define LOG_TAG "MmapSource"
+#include <utils/Log.h>
+
+#include <sys/mman.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <media/stagefright/MmapSource.h>
+
+namespace android {
+
+MmapSource::MmapSource(const char *filename)
+    : mFd(open(filename, O_RDONLY)),
+      mBase(NULL),
+      mSize(0) {
+    LOGV("MmapSource '%s'", filename);
+    assert(mFd >= 0);
+
+    off_t size = lseek(mFd, 0, SEEK_END);
+    mSize = (size_t)size;
+
+    mBase = mmap(0, mSize, PROT_READ, MAP_FILE | MAP_SHARED, mFd, 0);
+
+    if (mBase == (void *)-1) {
+        mBase = NULL;
+
+        close(mFd);
+        mFd = -1;
+    }
+}
+
+MmapSource::MmapSource(int fd, int64_t offset, int64_t length)
+    : mFd(fd),
+      mBase(NULL),
+      mSize(length) {
+    LOGV("MmapSource fd:%d offset:%lld length:%lld", fd, offset, length);
+    assert(fd >= 0);
+
+    mBase = mmap(0, mSize, PROT_READ, MAP_FILE | MAP_SHARED, mFd, offset);
+
+    if (mBase == (void *)-1) {
+        mBase = NULL;
+
+        close(mFd);
+        mFd = -1;
+    }
+
+}
+
+MmapSource::~MmapSource() {
+    if (mFd != -1) {
+        munmap(mBase, mSize);
+        mBase = NULL;
+        mSize = 0;
+
+        close(mFd);
+        mFd = -1;
+    }
+}
+
+status_t MmapSource::InitCheck() const {
+    return mFd == -1 ? NO_INIT : OK;
+}
+
+ssize_t MmapSource::read_at(off_t offset, void *data, size_t size) {
+    LOGV("read_at offset:%ld data:%p size:%d", offset, data, size);
+    assert(offset >= 0);
+
+    size_t avail = 0;
+    if (offset >= 0 && offset < (off_t)mSize) {
+        avail = mSize - offset;
+    }
+
+    if (size > avail) {
+        size = avail;
+    }
+
+    memcpy(data, (const uint8_t *)mBase + offset, size);
+
+    return (ssize_t)size;
+}
+
+status_t MmapSource::getSize(off_t *size) {
+    *size = mSize;
+
+    return OK;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/OMXClient.cpp b/media/libstagefright/OMXClient.cpp
new file mode 100644
index 0000000..1bc8a44
--- /dev/null
+++ b/media/libstagefright/OMXClient.cpp
@@ -0,0 +1,369 @@
+/*
+ * 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_NDEBUG 0
+#define LOG_TAG "OMXClient"
+#include <utils/Log.h>
+
+#include <sys/socket.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <binder/IServiceManager.h>
+#include <media/IMediaPlayerService.h>
+#include <media/IOMX.h>
+#include <media/stagefright/OMXClient.h>
+
+namespace android {
+
+OMXClient::OMXClient()
+    : mSock(-1) {
+}
+
+OMXClient::~OMXClient() {
+    disconnect();
+}
+
+status_t OMXClient::connect() {
+    Mutex::Autolock autoLock(mLock);
+
+    if (mSock >= 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    sp<IServiceManager> sm = defaultServiceManager();
+    sp<IBinder> binder = sm->getService(String16("media.player"));
+    sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
+
+    assert(service.get() != NULL);
+
+    mOMX = service->createOMX();
+    assert(mOMX.get() != NULL);
+
+#if IOMX_USES_SOCKETS
+    status_t result = mOMX->connect(&mSock);
+    if (result != OK) {
+        mSock = -1;
+
+        mOMX = NULL;
+        return result;
+    }
+
+    pthread_attr_t attr;
+    pthread_attr_init(&attr);
+    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
+
+    int err = pthread_create(&mThread, &attr, ThreadWrapper, this);
+    assert(err == 0);
+
+    pthread_attr_destroy(&attr);
+#else
+    mReflector = new OMXClientReflector(this);
+#endif
+
+    return OK;
+}
+
+void OMXClient::disconnect() {
+    {
+        Mutex::Autolock autoLock(mLock);
+
+        if (mSock < 0) {
+            return;
+        }
+
+        assert(mObservers.isEmpty());
+    }
+
+#if IOMX_USES_SOCKETS
+    omx_message msg;
+    msg.type = omx_message::DISCONNECT;
+    ssize_t n = send(mSock, &msg, sizeof(msg), 0);
+    assert(n > 0 && static_cast<size_t>(n) == sizeof(msg));
+
+    void *dummy;
+    pthread_join(mThread, &dummy);
+#else
+    mReflector->reset();
+    mReflector.clear();
+#endif
+}
+
+#if IOMX_USES_SOCKETS
+// static
+void *OMXClient::ThreadWrapper(void *me) {
+    ((OMXClient *)me)->threadEntry();
+
+    return NULL;
+}
+
+void OMXClient::threadEntry() {
+    bool done = false;
+    while (!done) {
+        omx_message msg;
+        ssize_t n = recv(mSock, &msg, sizeof(msg), 0);
+
+        if (n <= 0) {
+            break;
+        }
+
+        done = onOMXMessage(msg);
+    }
+
+    Mutex::Autolock autoLock(mLock);
+    close(mSock);
+    mSock = -1;
+}
+#endif
+
+status_t OMXClient::fillBuffer(IOMX::node_id node, IOMX::buffer_id buffer) {
+#if !IOMX_USES_SOCKETS
+    mOMX->fill_buffer(node, buffer);
+#else
+    if (mSock < 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    omx_message msg;
+    msg.type = omx_message::FILL_BUFFER;
+    msg.u.buffer_data.node = node;
+    msg.u.buffer_data.buffer = buffer;
+
+    ssize_t n = send(mSock, &msg, sizeof(msg), 0);
+    assert(n > 0 && static_cast<size_t>(n) == sizeof(msg));
+#endif
+
+    return OK;
+}
+
+status_t OMXClient::emptyBuffer(
+        IOMX::node_id node, IOMX::buffer_id buffer,
+        OMX_U32 range_offset, OMX_U32 range_length,
+        OMX_U32 flags, OMX_TICKS timestamp) {
+#if !IOMX_USES_SOCKETS
+    mOMX->empty_buffer(
+            node, buffer, range_offset, range_length, flags, timestamp);
+#else
+    if (mSock < 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    // XXX I don't like all this copying...
+
+    omx_message msg;
+    msg.type = omx_message::EMPTY_BUFFER;
+    msg.u.extended_buffer_data.node = node;
+    msg.u.extended_buffer_data.buffer = buffer;
+    msg.u.extended_buffer_data.range_offset = range_offset;
+    msg.u.extended_buffer_data.range_length = range_length;
+    msg.u.extended_buffer_data.flags = flags;
+    msg.u.extended_buffer_data.timestamp = timestamp;
+
+    ssize_t n = send(mSock, &msg, sizeof(msg), 0);
+    assert(n > 0 && static_cast<size_t>(n) == sizeof(msg));
+#endif
+
+    return OK;
+}
+
+status_t OMXClient::send_command(
+        IOMX::node_id node, OMX_COMMANDTYPE cmd, OMX_S32 param) {
+#if !IOMX_USES_SOCKETS
+    return mOMX->send_command(node, cmd, param);
+#else
+    if (mSock < 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    omx_message msg;
+    msg.type = omx_message::SEND_COMMAND;
+    msg.u.send_command_data.node = node;
+    msg.u.send_command_data.cmd = cmd;
+    msg.u.send_command_data.param = param;
+
+    ssize_t n = send(mSock, &msg, sizeof(msg), 0);
+    assert(n > 0 && static_cast<size_t>(n) == sizeof(msg));
+#endif
+
+    return OK;
+}
+
+status_t OMXClient::registerObserver(
+        IOMX::node_id node, OMXObserver *observer) {
+    Mutex::Autolock autoLock(&mLock);
+
+    ssize_t index = mObservers.indexOfKey(node);
+    if (index >= 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    mObservers.add(node, observer);
+    observer->start();
+
+#if !IOMX_USES_SOCKETS
+    mOMX->observe_node(node, mReflector);
+#endif
+
+    return OK;
+}
+
+void OMXClient::unregisterObserver(IOMX::node_id node) {
+    Mutex::Autolock autoLock(mLock);
+
+    ssize_t index = mObservers.indexOfKey(node);
+    assert(index >= 0);
+
+    if (index < 0) {
+        return;
+    }
+
+    OMXObserver *observer = mObservers.valueAt(index);
+    observer->stop();
+    mObservers.removeItemsAt(index);
+}
+
+bool OMXClient::onOMXMessage(const omx_message &msg) {
+    bool done = false;
+
+    switch (msg.type) {
+        case omx_message::EVENT:
+        {
+            LOGV("OnEvent node:%p event:%d data1:%ld data2:%ld",
+                 msg.u.event_data.node,
+                 msg.u.event_data.event,
+                 msg.u.event_data.data1,
+                 msg.u.event_data.data2);
+
+            break;
+        }
+
+        case omx_message::FILL_BUFFER_DONE:
+        {
+            LOGV("FillBufferDone %p", msg.u.extended_buffer_data.buffer);
+            break;
+        }
+
+        case omx_message::EMPTY_BUFFER_DONE:
+        {
+            LOGV("EmptyBufferDone %p", msg.u.buffer_data.buffer);
+            break;
+        }
+
+#if IOMX_USES_SOCKETS
+        case omx_message::DISCONNECTED:
+        {
+            LOGV("Disconnected");
+            done = true;
+            break;
+        }
+#endif
+
+        default:
+            LOGE("received unknown omx_message type %d", msg.type);
+            break;
+    }
+
+    Mutex::Autolock autoLock(mLock);
+    ssize_t index = mObservers.indexOfKey(msg.u.buffer_data.node);
+
+    if (index >= 0) {
+        mObservers.editValueAt(index)->postMessage(msg);
+    }
+
+    return done;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+OMXObserver::OMXObserver() {
+}
+
+OMXObserver::~OMXObserver() {
+}
+
+void OMXObserver::start() {
+    pthread_attr_t attr;
+    pthread_attr_init(&attr);
+    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
+
+    int err = pthread_create(&mThread, &attr, ThreadWrapper, this);
+    assert(err == 0);
+
+    pthread_attr_destroy(&attr);
+}
+
+void OMXObserver::stop() {
+    omx_message msg;
+    msg.type = omx_message::QUIT_OBSERVER;
+    postMessage(msg);
+
+    void *dummy;
+    pthread_join(mThread, &dummy);
+}
+
+void OMXObserver::postMessage(const omx_message &msg) {
+    Mutex::Autolock autoLock(mLock);
+    mQueue.push_back(msg);
+    mQueueNotEmpty.signal();
+}
+
+// static
+void *OMXObserver::ThreadWrapper(void *me) {
+    static_cast<OMXObserver *>(me)->threadEntry();
+
+    return NULL;
+}
+
+void OMXObserver::threadEntry() {
+    for (;;) {
+        omx_message msg;
+
+        {
+            Mutex::Autolock autoLock(mLock);
+            while (mQueue.empty()) {
+                mQueueNotEmpty.wait(mLock);
+            }
+
+            msg = *mQueue.begin();
+            mQueue.erase(mQueue.begin());
+        }
+
+        if (msg.type == omx_message::QUIT_OBSERVER) {
+            break;
+        }
+
+        onOMXMessage(msg);
+    }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+OMXClientReflector::OMXClientReflector(OMXClient *client)
+    : mClient(client) {
+}
+
+void OMXClientReflector::on_message(const omx_message &msg) {
+    if (mClient != NULL) {
+        mClient->onOMXMessage(msg);
+    }
+}
+
+void OMXClientReflector::reset() {
+    mClient = NULL;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/OMXDecoder.cpp b/media/libstagefright/OMXDecoder.cpp
new file mode 100644
index 0000000..c059a9d
--- /dev/null
+++ b/media/libstagefright/OMXDecoder.cpp
@@ -0,0 +1,1329 @@
+/*
+ * 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_NDEBUG 0
+#define LOG_TAG "OMXDecoder"
+#include <utils/Log.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <OMX_Component.h>
+
+#include <media/stagefright/ESDS.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/OMXDecoder.h>
+
+namespace android {
+
+class OMXMediaBuffer : public MediaBuffer {
+public:
+    OMXMediaBuffer(IOMX::buffer_id buffer_id, const sp<IMemory> &mem)
+        : MediaBuffer(mem->pointer(),
+                      mem->size()),
+          mBufferID(buffer_id),
+          mMem(mem) {
+    }
+
+    IOMX::buffer_id buffer_id() const { return mBufferID; }
+
+private:
+    IOMX::buffer_id mBufferID;
+    sp<IMemory> mMem;
+
+    OMXMediaBuffer(const OMXMediaBuffer &);
+    OMXMediaBuffer &operator=(const OMXMediaBuffer &);
+};
+
+struct CodecInfo {
+    const char *mime;
+    const char *codec;
+};
+
+static const CodecInfo kDecoderInfo[] = {
+    { "audio/mpeg", "OMX.PV.mp3dec" },
+    { "audio/3gpp", "OMX.PV.amrdec" },
+    { "audio/mp4a-latm", "OMX.PV.aacdec" },
+    { "video/mp4v-es", "OMX.qcom.video.decoder.mpeg4" },
+    { "video/mp4v-es", "OMX.PV.mpeg4dec" },
+    { "video/3gpp", "OMX.qcom.video.decoder.h263" },
+    { "video/3gpp", "OMX.PV.h263dec" },
+    { "video/avc", "OMX.qcom.video.decoder.avc" },
+    { "video/avc", "OMX.PV.avcdec" },
+};
+
+static const CodecInfo kEncoderInfo[] = {
+    { "audio/3gpp", "OMX.PV.amrencnb" },
+    { "audio/mp4a-latm", "OMX.PV.aacenc" },
+    { "video/mp4v-es", "OMX.qcom.video.encoder.mpeg4" },
+    { "video/mp4v-es", "OMX.PV.mpeg4enc" },
+    { "video/3gpp", "OMX.qcom.video.encoder.h263" },
+    { "video/3gpp", "OMX.PV.h263enc" },
+    { "video/avc", "OMX.PV.avcenc" },
+};
+
+static const char *GetCodec(const CodecInfo *info, size_t numInfos,
+                            const char *mime, int index) {
+    assert(index >= 0);
+    for(size_t i = 0; i < numInfos; ++i) {
+        if (!strcasecmp(mime, info[i].mime)) {
+            if (index == 0) {
+                return info[i].codec;
+            }
+
+            --index;
+        }
+    }
+
+    return NULL;
+}
+
+// static
+OMXDecoder *OMXDecoder::Create(OMXClient *client, const sp<MetaData> &meta) {
+    const char *mime;
+    bool success = meta->findCString(kKeyMIMEType, &mime);
+    assert(success);
+
+    sp<IOMX> omx = client->interface();
+
+    const char *codec = NULL;
+    IOMX::node_id node = 0;
+    for (int index = 0;; ++index) {
+        codec = GetCodec(
+                kDecoderInfo, sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]),
+                mime, index);
+
+        if (!codec) {
+            return NULL;
+        }
+
+        LOGI("Attempting to allocate OMX node '%s'", codec);
+
+        status_t err = omx->allocate_node(codec, &node);
+        if (err == OK) {
+            break;
+        }
+    }
+
+    OMXDecoder *decoder = new OMXDecoder(client, node, mime, codec);
+
+    uint32_t type;
+    const void *data;
+    size_t size;
+    if (meta->findData(kKeyESDS, &type, &data, &size)) {
+        ESDS esds((const char *)data, size);
+        assert(esds.InitCheck() == OK);
+        
+        const void *codec_specific_data;
+        size_t codec_specific_data_size;
+        esds.getCodecSpecificInfo(
+                &codec_specific_data, &codec_specific_data_size);
+
+        printf("found codec specific data of size %d\n",
+               codec_specific_data_size);
+
+        decoder->addCodecSpecificData(
+                codec_specific_data, codec_specific_data_size);
+    } else if (meta->findData(kKeyAVCC, &type, &data, &size)) {
+        printf("found avcc of size %d\n", size);
+
+        const uint8_t *ptr = (const uint8_t *)data + 6;
+        size -= 6;
+        while (size >= 2) {
+            size_t length = ptr[0] << 8 | ptr[1];
+
+            ptr += 2;
+            size -= 2;
+
+            // printf("length = %d, size = %d\n", length, size);
+
+            assert(size >= length);
+
+            decoder->addCodecSpecificData(ptr, length);
+
+            ptr += length;
+            size -= length;
+
+            if (size <= 1) {
+                break;
+            }
+
+            ptr++;  // XXX skip trailing 0x01 byte???
+            --size;
+        }
+    }
+
+    return decoder;
+}
+
+// static
+OMXDecoder *OMXDecoder::CreateEncoder(
+        OMXClient *client, const sp<MetaData> &meta) {
+    const char *mime;
+    bool success = meta->findCString(kKeyMIMEType, &mime);
+    assert(success);
+
+    sp<IOMX> omx = client->interface();
+
+    const char *codec = NULL;
+    IOMX::node_id node = 0;
+    for (int index = 0;; ++index) {
+        codec = GetCodec(
+                kEncoderInfo, sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]),
+                mime, index);
+
+        if (!codec) {
+            return NULL;
+        }
+
+        LOGI("Attempting to allocate OMX node '%s'", codec);
+
+        status_t err = omx->allocate_node(codec, &node);
+        if (err == OK) {
+            break;
+        }
+    }
+
+    OMXDecoder *encoder = new OMXDecoder(client, node, mime, codec);
+
+    return encoder;
+}
+
+OMXDecoder::OMXDecoder(OMXClient *client, IOMX::node_id node,
+                       const char *mime, const char *codec)
+    : mClient(client),
+      mOMX(mClient->interface()),
+      mNode(node),
+      mComponentName(strdup(codec)),
+      mIsMP3(!strcasecmp(mime, "audio/mpeg")),
+      mSource(NULL),
+      mCodecSpecificDataIterator(mCodecSpecificData.begin()),
+      mState(OMX_StateLoaded),
+      mPortStatusMask(kPortStatusActive << 2 | kPortStatusActive),
+      mShutdownInitiated(false),
+      mDealer(new MemoryDealer(3 * 1024 * 1024)),
+      mSeeking(false),
+      mStarted(false),
+      mErrorCondition(OK),
+      mReachedEndOfInput(false) {
+    mClient->registerObserver(mNode, this);
+
+    mBuffers.push();  // input buffers
+    mBuffers.push();  // output buffers
+}
+
+OMXDecoder::~OMXDecoder() {
+    if (mStarted) {
+        stop();
+    }
+
+    for (List<CodecSpecificData>::iterator it = mCodecSpecificData.begin();
+         it != mCodecSpecificData.end(); ++it) {
+        free((*it).data);
+    }
+    mCodecSpecificData.clear();
+
+    mClient->unregisterObserver(mNode);
+
+    status_t err = mOMX->free_node(mNode);
+    assert(err == OK);
+    mNode = 0;
+
+    free(mComponentName);
+    mComponentName = NULL;
+}
+
+void OMXDecoder::setSource(MediaSource *source) {
+    Mutex::Autolock autoLock(mLock);
+
+    assert(mSource == NULL);
+
+    mSource = source;
+    setup();
+}
+
+status_t OMXDecoder::start(MetaData *) {
+    assert(!mStarted);
+
+    // mDealer->dump("Decoder Dealer");
+
+    sp<MetaData> params = new MetaData;
+    if (!strcmp(mComponentName, "OMX.qcom.video.decoder.avc")) {
+        params->setInt32(kKeyNeedsNALFraming, true);
+    }
+
+    status_t err = mSource->start(params.get());
+
+    if (err != OK) {
+        return err;
+    }
+
+    postStart();
+
+    mStarted = true;
+
+    return OK;
+}
+
+status_t OMXDecoder::stop() {
+    assert(mStarted);
+
+    LOGI("Initiating OMX Node shutdown, busy polling.");
+    initiateShutdown();
+
+    // Important: initiateShutdown must be called first, _then_ release
+    // buffers we're holding onto.
+    while (!mOutputBuffers.empty()) {
+        MediaBuffer *buffer = *mOutputBuffers.begin();
+        mOutputBuffers.erase(mOutputBuffers.begin());
+
+        LOGV("releasing buffer %p.", buffer->data());
+
+        buffer->release();
+        buffer = NULL;
+    }
+
+    int attempt = 1;
+    while (mState != OMX_StateLoaded && attempt < 10) {
+        usleep(100000);
+
+        ++attempt;
+    }
+
+    if (mState != OMX_StateLoaded) {
+        LOGE("!!! OMX Node '%s' did NOT shutdown cleanly !!!", mComponentName);
+    } else {
+        LOGI("OMX Node '%s' has shutdown cleanly.", mComponentName);
+    }
+
+    mSource->stop();
+
+    mCodecSpecificDataIterator = mCodecSpecificData.begin();
+    mShutdownInitiated = false;
+    mSeeking = false;
+    mStarted = false;
+    mErrorCondition = OK;
+    mReachedEndOfInput = false;
+
+    return OK;
+}
+
+sp<MetaData> OMXDecoder::getFormat() {
+    return mOutputFormat;
+}
+
+status_t OMXDecoder::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    assert(mStarted);
+
+    *out = NULL;
+
+    Mutex::Autolock autoLock(mLock);
+
+    if (mErrorCondition != OK && mErrorCondition != ERROR_END_OF_STREAM) {
+        // Errors are sticky.
+        return mErrorCondition;
+    }
+
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        LOGI("[%s] seeking to %lld us", mComponentName, seekTimeUs);
+
+        mErrorCondition = OK;
+        mReachedEndOfInput = false;
+
+        setPortStatus(kPortIndexInput, kPortStatusFlushing);
+        setPortStatus(kPortIndexOutput, kPortStatusFlushing);
+
+        mSeeking = true;
+        mSeekTimeUs = seekTimeUs;
+
+        while (!mOutputBuffers.empty()) {
+            OMXMediaBuffer *buffer =
+                static_cast<OMXMediaBuffer *>(*mOutputBuffers.begin());
+
+            // We could have used buffer->release() instead, but we're
+            // holding the lock and signalBufferReturned attempts to acquire
+            // the lock.
+            buffer->claim();
+            mBuffers.editItemAt(
+                    kPortIndexOutput).push_back(buffer->buffer_id());
+            buffer = NULL;
+
+            mOutputBuffers.erase(mOutputBuffers.begin());
+        }
+
+        status_t err = mOMX->send_command(mNode, OMX_CommandFlush, -1);
+        assert(err == OK);
+
+        // Once flushing is completed buffers will again be scheduled to be
+        // filled/emptied.
+    }
+
+    while (mErrorCondition == OK && mOutputBuffers.empty()) {
+        mOutputBufferAvailable.wait(mLock);
+    }
+
+    if (!mOutputBuffers.empty()) {
+        MediaBuffer *buffer = *mOutputBuffers.begin();
+        mOutputBuffers.erase(mOutputBuffers.begin());
+
+        *out = buffer;
+
+        return OK;
+    } else {
+        assert(mErrorCondition != OK);
+        return mErrorCondition;
+    }
+}
+
+void OMXDecoder::addCodecSpecificData(const void *data, size_t size) {
+    CodecSpecificData specific;
+    specific.data = malloc(size);
+    memcpy(specific.data, data, size);
+    specific.size = size;
+
+    mCodecSpecificData.push_back(specific);
+    mCodecSpecificDataIterator = mCodecSpecificData.begin();
+}
+
+void OMXDecoder::onOMXMessage(const omx_message &msg) {
+    Mutex::Autolock autoLock(mLock);
+
+    switch (msg.type) {
+        case omx_message::START:
+        {
+            onStart();
+            break;
+        }
+
+        case omx_message::EVENT:
+        {
+            onEvent(msg.u.event_data.event, msg.u.event_data.data1,
+                    msg.u.event_data.data2);
+            break;
+        }
+
+        case omx_message::EMPTY_BUFFER_DONE:
+        {
+            onEmptyBufferDone(msg.u.buffer_data.buffer);
+            break;
+        }
+
+        case omx_message::FILL_BUFFER_DONE:
+        case omx_message::INITIAL_FILL_BUFFER:
+        {
+            onFillBufferDone(msg);
+            break;
+        }
+
+        default:
+            LOGE("received unknown omx_message type %d", msg.type);
+            break;
+    }
+}
+
+void OMXDecoder::setAMRFormat() {
+    OMX_AUDIO_PARAM_AMRTYPE def;
+    def.nSize = sizeof(def);
+    def.nVersion.s.nVersionMajor = 1;
+    def.nVersion.s.nVersionMinor = 1;
+    def.nPortIndex = kPortIndexInput;
+
+    status_t err =
+        mOMX->get_parameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
+
+    assert(err == NO_ERROR);
+
+    def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
+    def.eAMRBandMode = OMX_AUDIO_AMRBandModeNB0;
+
+    err = mOMX->set_parameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
+    assert(err == NO_ERROR);
+}
+
+void OMXDecoder::setAACFormat() {
+    OMX_AUDIO_PARAM_AACPROFILETYPE def;
+    def.nSize = sizeof(def);
+    def.nVersion.s.nVersionMajor = 1;
+    def.nVersion.s.nVersionMinor = 1;
+    def.nPortIndex = kPortIndexInput;
+
+    status_t err =
+        mOMX->get_parameter(mNode, OMX_IndexParamAudioAac, &def, sizeof(def));
+    assert(err == NO_ERROR);
+
+    def.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4ADTS;
+
+    err = mOMX->set_parameter(mNode, OMX_IndexParamAudioAac, &def, sizeof(def));
+    assert(err == NO_ERROR);
+}
+
+void OMXDecoder::setVideoOutputFormat(OMX_U32 width, OMX_U32 height) {
+    LOGI("setVideoOutputFormat width=%ld, height=%ld", width, height);
+
+    OMX_PARAM_PORTDEFINITIONTYPE def;
+    OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
+
+    bool is_encoder = strstr(mComponentName, ".encoder.") != NULL;  // XXX
+
+    def.nSize = sizeof(def);
+    def.nVersion.s.nVersionMajor = 1;
+    def.nVersion.s.nVersionMinor = 1;
+    def.nPortIndex = is_encoder ? kPortIndexOutput : kPortIndexInput;
+
+    status_t err = mOMX->get_parameter(
+            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
+
+    assert(err == NO_ERROR);
+
+#if 1
+    // XXX Need a (much) better heuristic to compute input buffer sizes.
+    const size_t X = 64 * 1024;
+    if (def.nBufferSize < X) {
+        def.nBufferSize = X;
+    }
+#endif
+
+    assert(def.eDomain == OMX_PortDomainVideo);
+    
+    video_def->nFrameWidth = width;
+    video_def->nFrameHeight = height;
+    // video_def.eCompressionFormat = OMX_VIDEO_CodingAVC;
+    video_def->eColorFormat = OMX_COLOR_FormatUnused;
+
+    err = mOMX->set_parameter(
+            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
+    assert(err == NO_ERROR);
+
+    ////////////////////////////////////////////////////////////////////////////
+
+    def.nSize = sizeof(def);
+    def.nVersion.s.nVersionMajor = 1;
+    def.nVersion.s.nVersionMinor = 1;
+    def.nPortIndex = is_encoder ? kPortIndexInput : kPortIndexOutput;
+
+    err = mOMX->get_parameter(
+            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
+    assert(err == NO_ERROR);
+
+    assert(def.eDomain == OMX_PortDomainVideo);
+    
+    def.nBufferSize =
+        (((width + 15) & -16) * ((height + 15) & -16) * 3) / 2;  // YUV420
+
+    video_def->nFrameWidth = width;
+    video_def->nFrameHeight = height;
+    video_def->nStride = width;
+    // video_def->nSliceHeight = height;
+    video_def->eCompressionFormat = OMX_VIDEO_CodingUnused;
+//    video_def->eColorFormat = OMX_COLOR_FormatYUV420Planar;
+
+    err = mOMX->set_parameter(
+            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
+    assert(err == NO_ERROR);
+}
+
+void OMXDecoder::setup() {
+    const sp<MetaData> &meta = mSource->getFormat();
+
+    const char *mime;
+    bool success = meta->findCString(kKeyMIMEType, &mime);
+    assert(success);
+
+    if (!strcasecmp(mime, "audio/3gpp")) {
+        setAMRFormat();
+    } else if (!strcasecmp(mime, "audio/mp4a-latm")) {
+        setAACFormat();
+    } else if (!strncasecmp(mime, "video/", 6)) {
+        int32_t width, height;
+        bool success = meta->findInt32(kKeyWidth, &width);
+        success = success && meta->findInt32(kKeyHeight, &height);
+        assert(success);
+
+        setVideoOutputFormat(width, height);
+    }
+
+    // dumpPortDefinition(0);
+    // dumpPortDefinition(1);
+
+    mOutputFormat = new MetaData;
+    mOutputFormat->setCString(kKeyDecoderComponent, mComponentName);
+
+    OMX_PARAM_PORTDEFINITIONTYPE def;
+    def.nSize = sizeof(def);
+    def.nVersion.s.nVersionMajor = 1;
+    def.nVersion.s.nVersionMinor = 1;
+    def.nPortIndex = kPortIndexOutput;
+
+    status_t err = mOMX->get_parameter(
+            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
+    assert(err == NO_ERROR);
+
+    switch (def.eDomain) {
+        case OMX_PortDomainAudio:
+        {
+            OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio;
+
+            assert(audio_def->eEncoding == OMX_AUDIO_CodingPCM);
+
+            OMX_AUDIO_PARAM_PCMMODETYPE params;
+            params.nSize = sizeof(params);
+            params.nVersion.s.nVersionMajor = 1;
+            params.nVersion.s.nVersionMinor = 1;
+            params.nPortIndex = kPortIndexOutput;
+
+            err = mOMX->get_parameter(
+                    mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
+            assert(err == OK);
+
+            assert(params.eNumData == OMX_NumericalDataSigned);
+            assert(params.nBitPerSample == 16);
+            assert(params.ePCMMode == OMX_AUDIO_PCMModeLinear);
+
+            int32_t numChannels, sampleRate;
+            meta->findInt32(kKeyChannelCount, &numChannels);
+            meta->findInt32(kKeySampleRate, &sampleRate);
+
+            mOutputFormat->setCString(kKeyMIMEType, "audio/raw");
+            mOutputFormat->setInt32(kKeyChannelCount, numChannels);
+            mOutputFormat->setInt32(kKeySampleRate, sampleRate);
+            break;
+        }
+
+        case OMX_PortDomainVideo:
+        {
+            OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
+
+            if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) {
+                mOutputFormat->setCString(kKeyMIMEType, "video/raw");
+            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) {
+                mOutputFormat->setCString(kKeyMIMEType, "video/mp4v-es");
+            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) {
+                mOutputFormat->setCString(kKeyMIMEType, "video/3gpp");
+            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) {
+                mOutputFormat->setCString(kKeyMIMEType, "video/avc");
+            } else {
+                assert(!"Unknown compression format.");
+            }
+
+            if (!strcmp(mComponentName, "OMX.PV.avcdec")) {
+                // This component appears to be lying to me.
+                mOutputFormat->setInt32(
+                        kKeyWidth, (video_def->nFrameWidth + 15) & -16);
+                mOutputFormat->setInt32(
+                        kKeyHeight, (video_def->nFrameHeight + 15) & -16);
+            } else {
+                mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth);
+                mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight);
+            }
+
+            mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat);
+            break;
+        }
+
+        default:
+        {
+            assert(!"should not be here, neither audio nor video.");
+            break;
+        }
+    }
+}
+
+void OMXDecoder::onStart() {
+    bool needs_qcom_hack =
+        !strncmp(mComponentName, "OMX.qcom.video.", 15);
+
+    if (!needs_qcom_hack) {
+        status_t err =
+            mOMX->send_command(mNode, OMX_CommandStateSet, OMX_StateIdle);
+        assert(err == NO_ERROR);
+    }
+
+    allocateBuffers(kPortIndexInput);
+    allocateBuffers(kPortIndexOutput);
+
+    if (needs_qcom_hack) {
+        // XXX this should happen before AllocateBuffers, but qcom's
+        // h264 vdec disagrees.
+        status_t err =
+            mOMX->send_command(mNode, OMX_CommandStateSet, OMX_StateIdle);
+        assert(err == NO_ERROR);
+    }
+}
+
+void OMXDecoder::allocateBuffers(OMX_U32 port_index) {
+    assert(mBuffers[port_index].empty());
+
+    OMX_U32 num_buffers;
+    OMX_U32 buffer_size;
+
+    OMX_PARAM_PORTDEFINITIONTYPE def;
+    def.nSize = sizeof(def);
+    def.nVersion.s.nVersionMajor = 1;
+    def.nVersion.s.nVersionMinor = 1;
+    def.nVersion.s.nRevision = 0;
+    def.nVersion.s.nStep = 0;
+    def.nPortIndex = port_index;
+
+    status_t err = mOMX->get_parameter(
+            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
+    assert(err == NO_ERROR);
+
+    num_buffers = def.nBufferCountActual;
+    buffer_size = def.nBufferSize;
+
+    LOGV("[%s] port %ld: allocating %ld buffers of size %ld each\n",
+           mComponentName, port_index, num_buffers, buffer_size);
+
+    for (OMX_U32 i = 0; i < num_buffers; ++i) {
+        sp<IMemory> mem = mDealer->allocate(buffer_size);
+        assert(mem.get() != NULL);
+
+        IOMX::buffer_id buffer;
+        status_t err;
+
+        if (port_index == kPortIndexInput
+            && !strncmp(mComponentName, "OMX.qcom.video.encoder.", 23)) {
+            // qcom's H.263 encoder appears to want to allocate its own input
+            // buffers.
+            err = mOMX->allocate_buffer_with_backup(mNode, port_index, mem, &buffer);
+            if (err != OK) {
+                LOGE("[%s] allocate_buffer_with_backup failed with error %d",
+                     mComponentName, err);
+            }
+        } else if (port_index == kPortIndexOutput
+            && !strncmp(mComponentName, "OMX.qcom.video.decoder.", 23)) {
+#if 1
+            err = mOMX->allocate_buffer_with_backup(mNode, port_index, mem, &buffer);
+#else
+            // XXX This is fine as long as we are either running the player
+            // inside the media server process or we are using the
+            // QComHardwareRenderer to output the frames.
+            err = mOMX->allocate_buffer(mNode, port_index, buffer_size, &buffer);
+#endif
+            if (err != OK) {
+                LOGE("[%s] allocate_buffer_with_backup failed with error %d",
+                     mComponentName, err);
+            }
+        } else {
+            err = mOMX->use_buffer(mNode, port_index, mem, &buffer);
+            if (err != OK) {
+                LOGE("[%s] use_buffer failed with error %d",
+                     mComponentName, err);
+            }
+        }
+        assert(err == OK);
+
+        LOGV("allocated %s buffer %p.",
+             port_index == kPortIndexInput ? "INPUT" : "OUTPUT",
+             buffer);
+
+        mBuffers.editItemAt(port_index).push_back(buffer);
+        mBufferMap.add(buffer, mem);
+
+        if (port_index == kPortIndexOutput) {
+            OMXMediaBuffer *media_buffer = new OMXMediaBuffer(buffer, mem);
+            media_buffer->setObserver(this);
+
+            mMediaBufferMap.add(buffer, media_buffer);
+        }
+    }
+
+    LOGV("allocate %s buffers done.",
+         port_index == kPortIndexInput ? "INPUT" : "OUTPUT");
+}
+
+void OMXDecoder::onEvent(
+        OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
+    LOGV("[%s] onEvent event=%d, data1=%ld, data2=%ld",
+         mComponentName, event, data1, data2);
+
+    switch (event) {
+        case OMX_EventCmdComplete: {
+            onEventCmdComplete(
+                    static_cast<OMX_COMMANDTYPE>(data1), data2);
+
+            break;
+        }
+
+        case OMX_EventPortSettingsChanged: {
+            onEventPortSettingsChanged(data1);
+            break;
+        }
+
+        case OMX_EventBufferFlag: {
+            // initiateShutdown();
+            break;
+        }
+
+        default:
+            break;
+    }
+}
+
+void OMXDecoder::onEventCmdComplete(OMX_COMMANDTYPE type, OMX_U32 data) {
+    switch (type) {
+        case OMX_CommandStateSet: {
+            OMX_STATETYPE state = static_cast<OMX_STATETYPE>(data);
+            onStateChanged(state);
+            break;
+        }
+
+        case OMX_CommandPortDisable: {
+            OMX_U32 port_index = data;
+            assert(getPortStatus(port_index) == kPortStatusDisabled);
+
+            status_t err =
+                mOMX->send_command(mNode, OMX_CommandPortEnable, port_index);
+
+            allocateBuffers(port_index);
+
+            break;
+        }
+
+        case OMX_CommandPortEnable: {
+            OMX_U32 port_index = data;
+            assert(getPortStatus(port_index) ==kPortStatusDisabled);
+            setPortStatus(port_index, kPortStatusActive);
+
+            assert(port_index == kPortIndexOutput);
+
+            BufferList *obuffers = &mBuffers.editItemAt(kPortIndexOutput);
+            while (!obuffers->empty()) {
+                IOMX::buffer_id buffer = *obuffers->begin();
+                obuffers->erase(obuffers->begin());
+
+                status_t err = mClient->fillBuffer(mNode, buffer);
+                assert(err == NO_ERROR);
+            }
+
+            break;
+        }
+
+        case OMX_CommandFlush: {
+            OMX_U32 port_index = data;
+            LOGV("Port %ld flush complete.", port_index);
+            assert(getPortStatus(port_index) == kPortStatusFlushing);
+
+            setPortStatus(port_index, kPortStatusActive);
+            BufferList *buffers = &mBuffers.editItemAt(port_index);
+            while (!buffers->empty()) {
+                IOMX::buffer_id buffer = *buffers->begin();
+                buffers->erase(buffers->begin());
+
+                if (port_index == kPortIndexInput) {
+                    postEmptyBufferDone(buffer);
+                } else {
+                    postInitialFillBuffer(buffer);
+                }
+            }
+            break;
+        }
+
+        default:
+            break;
+    }
+}
+
+void OMXDecoder::onEventPortSettingsChanged(OMX_U32 port_index) {
+    assert(getPortStatus(port_index) == kPortStatusActive);
+    setPortStatus(port_index, kPortStatusDisabled);
+
+    status_t err =
+        mOMX->send_command(mNode, OMX_CommandPortDisable, port_index);
+    assert(err == NO_ERROR);
+}
+
+void OMXDecoder::onStateChanged(OMX_STATETYPE to) {
+    if (mState == OMX_StateLoaded) {
+        assert(to == OMX_StateIdle);
+
+        mState = to;
+
+        status_t err =
+            mOMX->send_command(mNode, OMX_CommandStateSet, OMX_StateExecuting);
+        assert(err == NO_ERROR);
+    } else if (mState == OMX_StateIdle) {
+        if (to == OMX_StateExecuting) {
+            mState = to;
+
+            BufferList *ibuffers = &mBuffers.editItemAt(kPortIndexInput);
+            while (!ibuffers->empty()) {
+                IOMX::buffer_id buffer = *ibuffers->begin();
+                ibuffers->erase(ibuffers->begin());
+
+                postEmptyBufferDone(buffer);
+            }
+
+            BufferList *obuffers = &mBuffers.editItemAt(kPortIndexOutput);
+            while (!obuffers->empty()) {
+                IOMX::buffer_id buffer = *obuffers->begin();
+                obuffers->erase(obuffers->begin());
+
+                postInitialFillBuffer(buffer);
+            }
+        } else {
+            assert(to == OMX_StateLoaded);
+
+            mState = to;
+
+            setPortStatus(kPortIndexInput, kPortStatusActive);
+            setPortStatus(kPortIndexOutput, kPortStatusActive);
+        }
+    } else if (mState == OMX_StateExecuting) {
+        assert(to == OMX_StateIdle);
+
+        mState = to;
+
+        LOGV("Executing->Idle complete, initiating Idle->Loaded");
+        status_t err =
+            mClient->send_command(mNode, OMX_CommandStateSet, OMX_StateLoaded);
+        assert(err == NO_ERROR);
+
+        BufferList *ibuffers = &mBuffers.editItemAt(kPortIndexInput);
+        for (BufferList::iterator it = ibuffers->begin();
+             it != ibuffers->end(); ++it) {
+            freeInputBuffer(*it);
+        }
+        ibuffers->clear();
+
+        BufferList *obuffers = &mBuffers.editItemAt(kPortIndexOutput);
+        for (BufferList::iterator it = obuffers->begin();
+             it != obuffers->end(); ++it) {
+            freeOutputBuffer(*it);
+        }
+        obuffers->clear();
+    }
+}
+
+void OMXDecoder::initiateShutdown() {
+    Mutex::Autolock autoLock(mLock);
+
+    if (mShutdownInitiated) {
+        return;
+    }
+    
+    if (mState == OMX_StateLoaded) {
+        return;
+    }
+
+    assert(mState == OMX_StateExecuting);
+
+    mShutdownInitiated = true;
+
+    status_t err =
+        mClient->send_command(mNode, OMX_CommandStateSet, OMX_StateIdle);
+    assert(err == NO_ERROR);
+
+    setPortStatus(kPortIndexInput, kPortStatusShutdown);
+    setPortStatus(kPortIndexOutput, kPortStatusShutdown);
+}
+
+void OMXDecoder::setPortStatus(OMX_U32 port_index, PortStatus status) {
+    int shift = 2 * port_index;
+
+    mPortStatusMask &= ~(3 << shift);
+    mPortStatusMask |= status << shift;
+}
+
+OMXDecoder::PortStatus OMXDecoder::getPortStatus(
+        OMX_U32 port_index) const {
+    int shift = 2 * port_index;
+
+    return static_cast<PortStatus>((mPortStatusMask >> shift) & 3);
+}
+
+void OMXDecoder::onEmptyBufferDone(IOMX::buffer_id buffer) {
+    LOGV("[%s] onEmptyBufferDone (%p)", mComponentName, buffer);
+
+    status_t err;
+    switch (getPortStatus(kPortIndexInput)) {
+        case kPortStatusDisabled:
+            freeInputBuffer(buffer);
+            err = NO_ERROR;
+            break;
+
+        case kPortStatusShutdown:
+            LOGV("We're shutting down, enqueue INPUT buffer %p.", buffer);
+            mBuffers.editItemAt(kPortIndexInput).push_back(buffer);
+            err = NO_ERROR;
+            break;
+
+        case kPortStatusFlushing:
+            LOGV("We're currently flushing, enqueue INPUT buffer %p.", buffer);
+            mBuffers.editItemAt(kPortIndexInput).push_back(buffer);
+            err = NO_ERROR;
+            break;
+
+        default:
+            onRealEmptyBufferDone(buffer);
+            err = NO_ERROR;
+            break;
+    }
+    assert(err == NO_ERROR);
+}
+
+void OMXDecoder::onFillBufferDone(const omx_message &msg) {
+    IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
+
+    LOGV("[%s] onFillBufferDone (%p)", mComponentName, buffer);
+
+    status_t err;
+    switch (getPortStatus(kPortIndexOutput)) {
+        case kPortStatusDisabled:
+            freeOutputBuffer(buffer);
+            err = NO_ERROR;
+            break;
+        case kPortStatusShutdown:
+            LOGV("We're shutting down, enqueue OUTPUT buffer %p.", buffer);
+            mBuffers.editItemAt(kPortIndexOutput).push_back(buffer);
+            err = NO_ERROR;
+            break;
+
+        case kPortStatusFlushing:
+            LOGV("We're currently flushing, enqueue OUTPUT buffer %p.", buffer);
+            mBuffers.editItemAt(kPortIndexOutput).push_back(buffer);
+            err = NO_ERROR;
+            break;
+
+        default:
+        {
+            if (msg.type == omx_message::INITIAL_FILL_BUFFER) {
+                err = mClient->fillBuffer(mNode, buffer);
+            } else {
+                LOGV("[%s] Filled OUTPUT buffer %p, flags=0x%08lx.",
+                     mComponentName, buffer, msg.u.extended_buffer_data.flags);
+
+                onRealFillBufferDone(msg);
+                err = NO_ERROR;
+            }
+            break;
+        }
+    }
+    assert(err == NO_ERROR);
+}
+
+void OMXDecoder::onRealEmptyBufferDone(IOMX::buffer_id buffer) {
+    if (mReachedEndOfInput) {
+        // We already sent the EOS notification.
+
+        mBuffers.editItemAt(kPortIndexInput).push_back(buffer);
+        return;
+    }
+
+    const sp<IMemory> mem = mBufferMap.valueFor(buffer);
+    assert(mem.get() != NULL);
+
+    static const uint8_t kNALStartCode[4] = { 0x00, 0x00, 0x00, 0x01 };
+
+    if (mCodecSpecificDataIterator != mCodecSpecificData.end()) {
+        List<CodecSpecificData>::iterator it = mCodecSpecificDataIterator;
+
+        size_t range_length = 0;
+
+        if (!strcmp(mComponentName, "OMX.qcom.video.decoder.avc")) {
+            assert((*mCodecSpecificDataIterator).size + 4 <= mem->size());
+
+            memcpy(mem->pointer(), kNALStartCode, 4);
+
+            memcpy((uint8_t *)mem->pointer() + 4, (*it).data, (*it).size);
+            range_length = (*it).size + 4;
+        } else {
+            assert((*mCodecSpecificDataIterator).size <= mem->size());
+
+            memcpy((uint8_t *)mem->pointer(), (*it).data, (*it).size);
+            range_length = (*it).size;
+        }
+
+        ++mCodecSpecificDataIterator;
+
+        status_t err = mClient->emptyBuffer(
+                mNode, buffer, 0, range_length, 
+                OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG,
+                0);
+
+        assert(err == NO_ERROR);
+
+        return;
+    }
+
+    LOGV("[%s] waiting for input data", mComponentName);
+
+    MediaBuffer *input_buffer;
+    for (;;) {
+        status_t err;
+
+        if (mSeeking) {
+            MediaSource::ReadOptions options;
+            options.setSeekTo(mSeekTimeUs);
+
+            mSeeking = false;
+
+            err = mSource->read(&input_buffer, &options);
+        } else {
+            err = mSource->read(&input_buffer);
+        }
+        assert((err == OK && input_buffer != NULL)
+               || (err != OK && input_buffer == NULL));
+
+        if (err == ERROR_END_OF_STREAM) {
+            LOGE("[%s] Reached end of stream.", mComponentName);
+            mReachedEndOfInput = true;
+        } else {
+            LOGV("[%s] got input data", mComponentName);
+        }
+
+        if (err != OK) {
+            status_t err2 = mClient->emptyBuffer(
+                    mNode, buffer, 0, 0, OMX_BUFFERFLAG_EOS, 0);
+
+            assert(err2 == NO_ERROR);
+            return;
+        }
+
+        if (mSeeking) {
+            input_buffer->release();
+            input_buffer = NULL;
+
+            continue;
+        }
+
+        break;
+    }
+
+    const uint8_t *src_data =
+        (const uint8_t *)input_buffer->data() + input_buffer->range_offset();
+
+    size_t src_length = input_buffer->range_length();
+    if (src_length == 195840) {
+        // When feeding the output of the AVC decoder into the H263 encoder,
+        // buffer sizes mismatch if width % 16 != 0 || height % 16 != 0.
+        src_length = 194400;  // XXX HACK
+    } else if (src_length == 115200) {
+        src_length = 114240;  // XXX HACK
+    }
+
+    if (src_length > mem->size()) {
+        LOGE("src_length=%d > mem->size() = %d\n",
+             src_length, mem->size());
+    }
+
+    assert(src_length <= mem->size());
+    memcpy(mem->pointer(), src_data, src_length);
+
+    OMX_U32 flags = 0;
+    if (!mIsMP3) {
+        // Only mp3 audio data may be streamed, all other data is assumed
+        // to be fed into the decoder at frame boundaries.
+        flags |= OMX_BUFFERFLAG_ENDOFFRAME;
+    }
+
+    int32_t units, scale;
+    bool success =
+        input_buffer->meta_data()->findInt32(kKeyTimeUnits, &units);
+
+    success = success &&
+        input_buffer->meta_data()->findInt32(kKeyTimeScale, &scale);
+
+    OMX_TICKS timestamp = 0;
+
+    if (success) {
+        // XXX units should be microseconds but PV treats them as milliseconds.
+        timestamp = ((OMX_S64)units * 1000) / scale;
+    }
+
+    input_buffer->release();
+    input_buffer = NULL;
+
+    LOGV("[%s] Calling EmptyBuffer on buffer %p",
+         mComponentName, buffer);
+
+    status_t err2 = mClient->emptyBuffer(
+            mNode, buffer, 0, src_length, flags, timestamp);
+    assert(err2 == OK);
+}
+
+void OMXDecoder::onRealFillBufferDone(const omx_message &msg) {
+    OMXMediaBuffer *media_buffer =
+        mMediaBufferMap.valueFor(msg.u.extended_buffer_data.buffer);
+
+    media_buffer->set_range(
+            msg.u.extended_buffer_data.range_offset,
+            msg.u.extended_buffer_data.range_length);
+
+    media_buffer->add_ref();
+
+    media_buffer->meta_data()->clear();
+
+    media_buffer->meta_data()->setInt32(
+            kKeyTimeUnits, msg.u.extended_buffer_data.timestamp);
+    media_buffer->meta_data()->setInt32(kKeyTimeScale, 1000);
+
+    if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) {
+        media_buffer->meta_data()->setInt32(kKeyIsSyncFrame, true);
+    }
+
+    media_buffer->meta_data()->setPointer(
+            kKeyPlatformPrivate,
+            msg.u.extended_buffer_data.platform_private);
+
+    if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) {
+        mErrorCondition = ERROR_END_OF_STREAM;
+    }
+
+    mOutputBuffers.push_back(media_buffer);
+    mOutputBufferAvailable.signal();
+}
+
+void OMXDecoder::signalBufferReturned(MediaBuffer *_buffer) {
+    Mutex::Autolock autoLock(mLock);
+
+    OMXMediaBuffer *media_buffer = static_cast<OMXMediaBuffer *>(_buffer);
+
+    IOMX::buffer_id buffer = media_buffer->buffer_id();
+
+    PortStatus outputStatus = getPortStatus(kPortIndexOutput);
+    if (outputStatus == kPortStatusShutdown
+            || outputStatus == kPortStatusFlushing) {
+        mBuffers.editItemAt(kPortIndexOutput).push_back(buffer);
+    } else {
+        LOGV("[%s] Calling FillBuffer on buffer %p.", mComponentName, buffer);
+
+        status_t err = mClient->fillBuffer(mNode, buffer);
+        assert(err == NO_ERROR);
+    }
+}
+
+void OMXDecoder::freeInputBuffer(IOMX::buffer_id buffer) {
+    LOGV("freeInputBuffer %p", buffer);
+
+    status_t err = mOMX->free_buffer(mNode, kPortIndexInput, buffer);
+    assert(err == NO_ERROR);
+    mBufferMap.removeItem(buffer);
+
+    LOGV("freeInputBuffer %p done", buffer);
+}
+
+void OMXDecoder::freeOutputBuffer(IOMX::buffer_id buffer) {
+    LOGV("freeOutputBuffer %p", buffer);
+
+    status_t err = mOMX->free_buffer(mNode, kPortIndexOutput, buffer);
+    assert(err == NO_ERROR);
+    mBufferMap.removeItem(buffer);
+
+    ssize_t index = mMediaBufferMap.indexOfKey(buffer);
+    assert(index >= 0);
+    MediaBuffer *mbuffer = mMediaBufferMap.editValueAt(index);
+    mMediaBufferMap.removeItemsAt(index);
+    mbuffer->setObserver(NULL);
+    mbuffer->release();
+    mbuffer = NULL;
+
+    LOGV("freeOutputBuffer %p done", buffer);
+}
+
+void OMXDecoder::dumpPortDefinition(OMX_U32 port_index) {
+    OMX_PARAM_PORTDEFINITIONTYPE def;
+    def.nSize = sizeof(def);
+    def.nVersion.s.nVersionMajor = 1;
+    def.nVersion.s.nVersionMinor = 1;
+    def.nPortIndex = port_index;
+
+    status_t err = mOMX->get_parameter(
+            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
+    assert(err == NO_ERROR);
+
+    LOGI("DumpPortDefinition on port %ld", port_index);
+    LOGI("nBufferCountActual = %ld, nBufferCountMin = %ld, nBufferSize = %ld",
+         def.nBufferCountActual, def.nBufferCountMin, def.nBufferSize);
+    switch (def.eDomain) {
+        case OMX_PortDomainAudio:
+        {
+            LOGI("eDomain = AUDIO");
+
+            if (port_index == kPortIndexOutput) {
+                OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio;
+                assert(audio_def->eEncoding == OMX_AUDIO_CodingPCM);
+
+                OMX_AUDIO_PARAM_PCMMODETYPE params;
+                params.nSize = sizeof(params);
+                params.nVersion.s.nVersionMajor = 1;
+                params.nVersion.s.nVersionMinor = 1;
+                params.nPortIndex = port_index;
+
+                err = mOMX->get_parameter(
+                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
+                assert(err == OK);
+
+                assert(params.nChannels == 1 || params.bInterleaved);
+                assert(params.eNumData == OMX_NumericalDataSigned);
+                assert(params.nBitPerSample == 16);
+                assert(params.ePCMMode == OMX_AUDIO_PCMModeLinear);
+
+                LOGI("nChannels = %ld, nSamplingRate = %ld",
+                     params.nChannels, params.nSamplingRate);
+            }
+
+            break;
+        }
+
+        case OMX_PortDomainVideo:
+        {
+            LOGI("eDomain = VIDEO");
+
+            OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
+            LOGI("nFrameWidth = %ld, nFrameHeight = %ld, nStride = %ld, "
+                 "nSliceHeight = %ld",
+                 video_def->nFrameWidth, video_def->nFrameHeight,
+                 video_def->nStride, video_def->nSliceHeight);
+            LOGI("nBitrate = %ld, xFrameRate = %.2f",
+                 video_def->nBitrate, video_def->xFramerate / 65536.0f);
+            LOGI("eCompressionFormat = %d, eColorFormat = %d",
+                 video_def->eCompressionFormat, video_def->eColorFormat);
+
+            break;
+        }
+
+        default:
+            LOGI("eDomain = UNKNOWN");
+            break;
+    }
+}
+
+void OMXDecoder::postStart() {
+    omx_message msg;
+    msg.type = omx_message::START;
+    postMessage(msg);
+}
+
+void OMXDecoder::postEmptyBufferDone(IOMX::buffer_id buffer) {
+    omx_message msg;
+    msg.type = omx_message::EMPTY_BUFFER_DONE;
+    msg.u.buffer_data.node = mNode;
+    msg.u.buffer_data.buffer = buffer;
+    postMessage(msg);
+}
+
+void OMXDecoder::postInitialFillBuffer(IOMX::buffer_id buffer) {
+    omx_message msg;
+    msg.type = omx_message::INITIAL_FILL_BUFFER;
+    msg.u.buffer_data.node = mNode;
+    msg.u.buffer_data.buffer = buffer;
+    postMessage(msg);
+}
+
+}  // namespace android
diff --git a/media/libstagefright/QComHardwareRenderer.cpp b/media/libstagefright/QComHardwareRenderer.cpp
new file mode 100644
index 0000000..5a23792
--- /dev/null
+++ b/media/libstagefright/QComHardwareRenderer.cpp
@@ -0,0 +1,139 @@
+/*
+ * 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.
+ */
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <binder/MemoryHeapBase.h>
+#include <binder/MemoryHeapPmem.h>
+#include <media/stagefright/QComHardwareRenderer.h>
+#include <ui/ISurface.h>
+
+namespace android {
+
+////////////////////////////////////////////////////////////////////////////////
+
+typedef struct PLATFORM_PRIVATE_ENTRY
+{
+    /* Entry type */
+    uint32_t type;
+
+    /* Pointer to platform specific entry */
+    void *entry;
+
+} PLATFORM_PRIVATE_ENTRY;
+
+typedef struct PLATFORM_PRIVATE_LIST
+{
+    /* Number of entries */
+    uint32_t nEntries;
+
+    /* Pointer to array of platform specific entries *
+     * Contiguous block of PLATFORM_PRIVATE_ENTRY elements */
+    PLATFORM_PRIVATE_ENTRY *entryList;
+
+} PLATFORM_PRIVATE_LIST;
+
+// data structures for tunneling buffers
+typedef struct PLATFORM_PRIVATE_PMEM_INFO
+{
+    /* pmem file descriptor */
+    uint32_t pmem_fd;
+    uint32_t offset;
+
+} PLATFORM_PRIVATE_PMEM_INFO;
+
+#define PLATFORM_PRIVATE_PMEM   1
+
+QComHardwareRenderer::QComHardwareRenderer(
+        const sp<ISurface> &surface,
+        size_t displayWidth, size_t displayHeight,
+        size_t decodedWidth, size_t decodedHeight)
+    : mISurface(surface),
+      mDisplayWidth(displayWidth),
+      mDisplayHeight(displayHeight),
+      mDecodedWidth(decodedWidth),
+      mDecodedHeight(decodedHeight),
+      mFrameSize((mDecodedWidth * mDecodedHeight * 3) / 2) {
+    assert(mISurface.get() != NULL);
+    assert(mDecodedWidth > 0);
+    assert(mDecodedHeight > 0);
+}
+
+QComHardwareRenderer::~QComHardwareRenderer() {
+    mISurface->unregisterBuffers();
+}
+
+void QComHardwareRenderer::render(
+        const void *data, size_t size, void *platformPrivate) {
+    size_t offset;
+    if (!getOffset(platformPrivate, &offset)) {
+        return;
+    }
+
+    mISurface->postBuffer(offset);
+}
+
+bool QComHardwareRenderer::getOffset(void *platformPrivate, size_t *offset) {
+    *offset = 0;
+
+    PLATFORM_PRIVATE_LIST *list = (PLATFORM_PRIVATE_LIST *)platformPrivate;
+    for (uint32_t i = 0; i < list->nEntries; ++i) {
+        if (list->entryList[i].type != PLATFORM_PRIVATE_PMEM) {
+            continue;
+        }
+
+        PLATFORM_PRIVATE_PMEM_INFO *info =
+            (PLATFORM_PRIVATE_PMEM_INFO *)list->entryList[i].entry;
+
+        if (info != NULL) {
+            if (mMemoryHeap.get() == NULL) {
+                publishBuffers(info->pmem_fd);
+            }
+
+            if (mMemoryHeap.get() == NULL) {
+                return false;
+            }
+
+            *offset = info->offset;
+
+            return true;
+        }
+    }
+
+    return false;
+}
+
+void QComHardwareRenderer::publishBuffers(uint32_t pmem_fd) {
+    sp<MemoryHeapBase> master =
+        reinterpret_cast<MemoryHeapBase *>(pmem_fd);
+
+    master->setDevice("/dev/pmem");
+
+    mMemoryHeap = new MemoryHeapPmem(master, 0);
+    mMemoryHeap->slap();
+
+    ISurface::BufferHeap bufferHeap(
+            mDisplayWidth, mDisplayHeight,
+            mDecodedWidth, mDecodedHeight,
+            PIXEL_FORMAT_YCbCr_420_SP,
+            mMemoryHeap);
+
+    status_t err = mISurface->registerBuffers(bufferHeap);
+    assert(err == OK);
+}
+
+}  // namespace android
diff --git a/media/libstagefright/SampleTable.cpp b/media/libstagefright/SampleTable.cpp
new file mode 100644
index 0000000..8f1fa67
--- /dev/null
+++ b/media/libstagefright/SampleTable.cpp
@@ -0,0 +1,598 @@
+/*
+ * 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 "SampleTable"
+#include <utils/Log.h>
+
+#include <arpa/inet.h>
+#include <assert.h>
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/SampleTable.h>
+#include <media/stagefright/Utils.h>
+
+namespace android {
+
+static const uint32_t kChunkOffsetType32 = FOURCC('s', 't', 'c', 'o');
+static const uint32_t kChunkOffsetType64 = FOURCC('c', 'o', '6', '4');
+static const uint32_t kSampleSizeType32 = FOURCC('s', 't', 's', 'z');
+static const uint32_t kSampleSizeTypeCompact = FOURCC('s', 't', 'z', '2');
+
+SampleTable::SampleTable(DataSource *source)
+    : mDataSource(source),
+      mChunkOffsetOffset(-1),
+      mChunkOffsetType(0),
+      mNumChunkOffsets(0),
+      mSampleToChunkOffset(-1),
+      mNumSampleToChunkOffsets(0),
+      mSampleSizeOffset(-1),
+      mSampleSizeFieldSize(0),
+      mDefaultSampleSize(0),
+      mNumSampleSizes(0),
+      mTimeToSampleCount(0),
+      mTimeToSample(NULL),
+      mSyncSampleOffset(-1),
+      mNumSyncSamples(0) {
+}
+
+SampleTable::~SampleTable() {
+    delete[] mTimeToSample;
+    mTimeToSample = NULL;
+}
+
+status_t SampleTable::setChunkOffsetParams(
+        uint32_t type, off_t data_offset, off_t data_size) {
+    if (mChunkOffsetOffset >= 0) {
+        return ERROR_MALFORMED;
+    }
+
+    assert(type == kChunkOffsetType32 || type == kChunkOffsetType64);
+
+    mChunkOffsetOffset = data_offset;
+    mChunkOffsetType = type;
+
+    if (data_size < 8) {
+        return ERROR_MALFORMED;
+    }
+
+    uint8_t header[8];
+    if (mDataSource->read_at(
+                data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
+        return ERROR_IO;
+    }
+
+    if (U32_AT(header) != 0) {
+        // Expected version = 0, flags = 0.
+        return ERROR_MALFORMED;
+    }
+
+    mNumChunkOffsets = U32_AT(&header[4]);
+
+    if (mChunkOffsetType == kChunkOffsetType32) {
+        if (data_size < 8 + mNumChunkOffsets * 4) {
+            return ERROR_MALFORMED;
+        }
+    } else {
+        if (data_size < 8 + mNumChunkOffsets * 8) {
+            return ERROR_MALFORMED;
+        }
+    }
+
+    return OK;
+}
+
+status_t SampleTable::setSampleToChunkParams(
+        off_t data_offset, off_t data_size) {
+    if (mSampleToChunkOffset >= 0) {
+        return ERROR_MALFORMED;
+    }
+
+    mSampleToChunkOffset = data_offset;
+
+    if (data_size < 8) {
+        return ERROR_MALFORMED;
+    }
+
+    uint8_t header[8];
+    if (mDataSource->read_at(
+                data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
+        return ERROR_IO;
+    }
+
+    if (U32_AT(header) != 0) {
+        // Expected version = 0, flags = 0.
+        return ERROR_MALFORMED;
+    }
+
+    mNumSampleToChunkOffsets = U32_AT(&header[4]);
+
+    if (data_size < 8 + mNumSampleToChunkOffsets * 12) {
+        return ERROR_MALFORMED;
+    }
+
+    return OK;
+}
+
+status_t SampleTable::setSampleSizeParams(
+        uint32_t type, off_t data_offset, off_t data_size) {
+    if (mSampleSizeOffset >= 0) {
+        return ERROR_MALFORMED;
+    }
+
+    assert(type == kSampleSizeType32 || type == kSampleSizeTypeCompact);
+
+    mSampleSizeOffset = data_offset;
+
+    if (data_size < 12) {
+        return ERROR_MALFORMED;
+    }
+
+    uint8_t header[12];
+    if (mDataSource->read_at(
+                data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
+        return ERROR_IO;
+    }
+
+    if (U32_AT(header) != 0) {
+        // Expected version = 0, flags = 0.
+        return ERROR_MALFORMED;
+    }
+
+    mDefaultSampleSize = U32_AT(&header[4]);
+    mNumSampleSizes = U32_AT(&header[8]);
+
+    if (type == kSampleSizeType32) {
+        mSampleSizeFieldSize = 32;
+
+        if (mDefaultSampleSize != 0) {
+            return OK;
+        }
+
+        if (data_size < 12 + mNumSampleSizes * 4) {
+            return ERROR_MALFORMED;
+        }
+    } else {
+        if ((mDefaultSampleSize & 0xffffff00) != 0) {
+            // The high 24 bits are reserved and must be 0.
+            return ERROR_MALFORMED;
+        }
+
+        mSampleSizeFieldSize = mDefaultSampleSize & 0xf;
+        mDefaultSampleSize = 0;
+
+        if (mSampleSizeFieldSize != 4 && mSampleSizeFieldSize != 8
+            && mSampleSizeFieldSize != 16) {
+            return ERROR_MALFORMED;
+        }
+
+        if (data_size < 12 + (mNumSampleSizes * mSampleSizeFieldSize + 4) / 8) {
+            return ERROR_MALFORMED;
+        }
+    }
+
+    return OK;
+}
+
+status_t SampleTable::setTimeToSampleParams(
+        off_t data_offset, off_t data_size) {
+    if (mTimeToSample != NULL || data_size < 8) {
+        return ERROR_MALFORMED;
+    }
+
+    uint8_t header[8];
+    if (mDataSource->read_at(
+                data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
+        return ERROR_IO;
+    }
+
+    if (U32_AT(header) != 0) {
+        // Expected version = 0, flags = 0.
+        return ERROR_MALFORMED;
+    }
+
+    mTimeToSampleCount = U32_AT(&header[4]);
+    mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
+
+    size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
+    if (mDataSource->read_at(
+                data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
+        return ERROR_IO;
+    }
+
+    for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
+        mTimeToSample[i] = ntohl(mTimeToSample[i]);
+    }
+
+    return OK;
+}
+
+status_t SampleTable::setSyncSampleParams(off_t data_offset, off_t data_size) {
+    if (mSyncSampleOffset >= 0 || data_size < 8) {
+        return ERROR_MALFORMED;
+    }
+
+    mSyncSampleOffset = data_offset;
+
+    uint8_t header[8];
+    if (mDataSource->read_at(
+                data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
+        return ERROR_IO;
+    }
+
+    if (U32_AT(header) != 0) {
+        // Expected version = 0, flags = 0.
+        return ERROR_MALFORMED;
+    }
+
+    mNumSyncSamples = U32_AT(&header[4]);
+
+    if (mNumSyncSamples < 2) {
+        LOGW("Table of sync samples is empty or has only a single entry!");
+    }
+    return OK;
+}
+
+uint32_t SampleTable::countChunkOffsets() const {
+    return mNumChunkOffsets;
+}
+
+status_t SampleTable::getChunkOffset(uint32_t chunk_index, off_t *offset) {
+    *offset = 0;
+
+    if (mChunkOffsetOffset < 0) {
+        return ERROR_MALFORMED;
+    }
+
+    if (chunk_index >= mNumChunkOffsets) {
+        return ERROR_OUT_OF_RANGE;
+    }
+
+    if (mChunkOffsetType == kChunkOffsetType32) {
+        uint32_t offset32;
+
+        if (mDataSource->read_at(
+                    mChunkOffsetOffset + 8 + 4 * chunk_index,
+                    &offset32,
+                    sizeof(offset32)) < (ssize_t)sizeof(offset32)) {
+            return ERROR_IO;
+        }
+
+        *offset = ntohl(offset32);
+    } else {
+        assert(mChunkOffsetOffset == kChunkOffsetType64);
+
+        uint64_t offset64;
+        if (mDataSource->read_at(
+                    mChunkOffsetOffset + 8 + 8 * chunk_index,
+                    &offset64,
+                    sizeof(offset64)) < (ssize_t)sizeof(offset64)) {
+            return ERROR_IO;
+        }
+
+        *offset = ntoh64(offset64);
+    }
+
+    return OK;
+}
+
+status_t SampleTable::getChunkForSample(
+        uint32_t sample_index,
+        uint32_t *chunk_index, 
+        uint32_t *chunk_relative_sample_index,
+        uint32_t *desc_index) {
+    *chunk_index = 0;
+    *chunk_relative_sample_index = 0;
+    *desc_index = 0;
+
+    if (mSampleToChunkOffset < 0) {
+        return ERROR_MALFORMED;
+    }
+
+    if (sample_index >= countSamples()) {
+        return ERROR_END_OF_STREAM;
+    }
+
+    uint32_t first_chunk = 0;
+    uint32_t samples_per_chunk = 0;
+    uint32_t chunk_desc_index = 0;
+
+    uint32_t index = 0;
+    while (index < mNumSampleToChunkOffsets) {
+        uint8_t buffer[12];
+        if (mDataSource->read_at(mSampleToChunkOffset + 8 + index * 12,
+                                 buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
+            return ERROR_IO;
+        }
+
+        uint32_t stop_chunk = U32_AT(buffer);
+        if (sample_index < (stop_chunk - first_chunk) * samples_per_chunk) {
+            break;
+        }
+
+        sample_index -= (stop_chunk - first_chunk) * samples_per_chunk;
+        first_chunk = stop_chunk;
+        samples_per_chunk = U32_AT(&buffer[4]);
+        chunk_desc_index = U32_AT(&buffer[8]);
+
+        ++index;
+    }
+
+    *chunk_index = sample_index / samples_per_chunk + first_chunk - 1;
+    *chunk_relative_sample_index = sample_index % samples_per_chunk;
+    *desc_index = chunk_desc_index;
+
+    return OK;
+}
+
+uint32_t SampleTable::countSamples() const {
+    return mNumSampleSizes;
+}
+
+status_t SampleTable::getSampleSize(
+        uint32_t sample_index, size_t *sample_size) {
+    *sample_size = 0;
+
+    if (mSampleSizeOffset < 0) {
+        return ERROR_MALFORMED;
+    }
+
+    if (sample_index >= mNumSampleSizes) {
+        return ERROR_OUT_OF_RANGE;
+    }
+
+    if (mDefaultSampleSize > 0) {
+        *sample_size = mDefaultSampleSize;
+        return OK;
+    }
+
+    switch (mSampleSizeFieldSize) {
+        case 32:
+        {
+            if (mDataSource->read_at(
+                        mSampleSizeOffset + 12 + 4 * sample_index,
+                        sample_size, sizeof(*sample_size)) < (ssize_t)sizeof(*sample_size)) {
+                return ERROR_IO;
+            }
+
+            *sample_size = ntohl(*sample_size);
+            break;
+        }
+
+        case 16:
+        {
+            uint16_t x;
+            if (mDataSource->read_at(
+                        mSampleSizeOffset + 12 + 2 * sample_index,
+                        &x, sizeof(x)) < (ssize_t)sizeof(x)) {
+                return ERROR_IO;
+            }
+
+            *sample_size = ntohs(x);
+            break;
+        }
+
+        case 8:
+        {
+            uint8_t x;
+            if (mDataSource->read_at(
+                        mSampleSizeOffset + 12 + sample_index,
+                        &x, sizeof(x)) < (ssize_t)sizeof(x)) {
+                return ERROR_IO;
+            }
+
+            *sample_size = x;
+            break;
+        }
+
+        default:
+        {
+            assert(mSampleSizeFieldSize == 4);
+
+            uint8_t x;
+            if (mDataSource->read_at(
+                        mSampleSizeOffset + 12 + sample_index / 2,
+                        &x, sizeof(x)) < (ssize_t)sizeof(x)) {
+                return ERROR_IO;
+            }
+
+            *sample_size = (sample_index & 1) ? x & 0x0f : x >> 4;
+            break;
+        }
+    }
+
+    return OK;
+}
+
+status_t SampleTable::getSampleOffsetAndSize(
+        uint32_t sample_index, off_t *offset, size_t *size) {
+    Mutex::Autolock autoLock(mLock);
+
+    *offset = 0;
+    *size = 0;
+
+    uint32_t chunk_index;
+    uint32_t chunk_relative_sample_index;
+    uint32_t desc_index;
+    status_t err = getChunkForSample(
+            sample_index, &chunk_index, &chunk_relative_sample_index,
+            &desc_index);
+
+    if (err != OK) {
+        return err;
+    }
+
+    err = getChunkOffset(chunk_index, offset);
+
+    if (err != OK) {
+        return err;
+    }
+
+    for (uint32_t j = 0; j < chunk_relative_sample_index; ++j) {
+        size_t sample_size;
+        err = getSampleSize(sample_index - j - 1, &sample_size);
+
+        if (err != OK) {
+            return err;
+        }
+
+        *offset += sample_size;
+    }
+
+    err = getSampleSize(sample_index, size);
+
+    if (err != OK) {
+        return err;
+    }
+
+    return OK;
+}
+
+status_t SampleTable::getMaxSampleSize(size_t *max_size) {
+    Mutex::Autolock autoLock(mLock);
+
+    *max_size = 0;
+
+    for (uint32_t i = 0; i < mNumSampleSizes; ++i) {
+        size_t sample_size;
+        status_t err = getSampleSize(i, &sample_size);
+        
+        if (err != OK) {
+            return err;
+        }
+
+        if (sample_size > *max_size) {
+            *max_size = sample_size;
+        }
+    }
+
+    return OK;
+}
+
+status_t SampleTable::getDecodingTime(uint32_t sample_index, uint32_t *time) {
+    // XXX FIXME idiotic (for the common use-case) O(n) algorithm below...
+
+    Mutex::Autolock autoLock(mLock);
+
+    if (sample_index >= mNumSampleSizes) {
+        return ERROR_OUT_OF_RANGE;
+    }
+
+    uint32_t cur_sample = 0;
+    *time = 0;
+    for (uint32_t i = 0; i < mTimeToSampleCount; ++i) {
+        uint32_t n = mTimeToSample[2 * i];
+        uint32_t delta = mTimeToSample[2 * i + 1];
+
+        if (sample_index < cur_sample + n) {
+            *time += delta * (sample_index - cur_sample);
+
+            return OK;
+        }
+        
+        *time += delta * n;
+        cur_sample += n;
+    }
+
+    return ERROR_OUT_OF_RANGE;
+}
+
+status_t SampleTable::findClosestSample(
+        uint32_t req_time, uint32_t *sample_index, uint32_t flags) {
+    Mutex::Autolock autoLock(mLock);
+
+    uint32_t cur_sample = 0;
+    uint32_t time = 0;
+    for (uint32_t i = 0; i < mTimeToSampleCount; ++i) {
+        uint32_t n = mTimeToSample[2 * i];
+        uint32_t delta = mTimeToSample[2 * i + 1];
+
+        if (req_time < time + n * delta) {
+            int j = (req_time - time) / delta;
+
+            *sample_index = cur_sample + j;
+
+            if (flags & kSyncSample_Flag) {
+                return findClosestSyncSample(*sample_index, sample_index);
+            }
+
+            return OK;
+        }
+
+        time += delta * n;
+        cur_sample += n;
+    }
+
+    return ERROR_OUT_OF_RANGE;
+}
+
+status_t SampleTable::findClosestSyncSample(
+        uint32_t start_sample_index, uint32_t *sample_index) {
+    *sample_index = 0;
+
+    if (mSyncSampleOffset < 0) {
+        // All samples are sync-samples.
+        *sample_index = start_sample_index;
+        return OK;
+    }
+
+    uint32_t x;
+    uint32_t left = 0;
+    uint32_t right = mNumSyncSamples;
+    while (left < right) {
+        uint32_t mid = (left + right) / 2;
+        if (mDataSource->read_at(
+                    mSyncSampleOffset + 8 + (mid - 1) * 4, &x, 4) != 4) {
+            return ERROR_IO;
+        }
+
+        x = ntohl(x);
+
+        if (x < (start_sample_index + 1)) {
+            left = mid + 1;
+        } else if (x > (start_sample_index + 1)) {
+            right = mid;
+        } else {
+            break;
+        }
+    }
+
+#if 1
+    // Make sure we return a sample at or _after_ the requested one.
+    // Seeking to a particular time in a media source containing audio and
+    // video will most likely be able to sync fairly close to the requested
+    // time in the audio track but may only be able to seek a fair distance
+    // from the requested time in the video track.
+    // If we seek the video track to a time earlier than the audio track,
+    // we'll cause the video track to be late for quite a while, the decoder
+    // trying to catch up.
+    // If we seek the video track to a time later than the audio track,
+    // audio will start playing fine while no video will be output for a
+    // while, the video decoder will not stress the system.
+    if (mDataSource->read_at(
+                mSyncSampleOffset + 8 + (left - 1) * 4, &x, 4) != 4) {
+        return ERROR_IO;
+    }
+    x = ntohl(x);
+    assert((x - 1) >= start_sample_index);
+#endif
+
+    *sample_index = x - 1;
+
+    return OK;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/ShoutcastSource.cpp b/media/libstagefright/ShoutcastSource.cpp
new file mode 100644
index 0000000..17b626e
--- /dev/null
+++ b/media/libstagefright/ShoutcastSource.cpp
@@ -0,0 +1,154 @@
+/*
+ * 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.
+ */
+
+#include <stdlib.h>
+
+#include <media/stagefright/HTTPStream.h>
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/ShoutcastSource.h>
+#include <media/stagefright/string.h>
+
+namespace android {
+
+ShoutcastSource::ShoutcastSource(HTTPStream *http)
+    : mHttp(http),
+      mMetaDataOffset(0),
+      mBytesUntilMetaData(0),
+      mGroup(NULL),
+      mStarted(false) {
+    string metaint;
+    if (mHttp->find_header_value("icy-metaint", &metaint)) {
+        char *end;
+        const char *start = metaint.c_str();
+        mMetaDataOffset = strtol(start, &end, 10);
+        assert(end > start && *end == '\0');
+        assert(mMetaDataOffset > 0);
+
+        mBytesUntilMetaData = mMetaDataOffset;
+    }
+}
+
+ShoutcastSource::~ShoutcastSource() {
+    if (mStarted) {
+        stop();
+    }
+
+    delete mHttp;
+    mHttp = NULL;
+}
+
+status_t ShoutcastSource::start(MetaData *) {
+    assert(!mStarted);
+
+    mGroup = new MediaBufferGroup;
+    mGroup->add_buffer(new MediaBuffer(4096));  // XXX
+
+    mStarted = true;
+
+    return OK;
+}
+
+status_t ShoutcastSource::stop() {
+    assert(mStarted);
+
+    delete mGroup;
+    mGroup = NULL;
+
+    mStarted = false;
+
+    return OK;
+}
+
+sp<MetaData> ShoutcastSource::getFormat() {
+    sp<MetaData> meta = new MetaData;
+    meta->setCString(kKeyMIMEType, "audio/mpeg");
+    meta->setInt32(kKeySampleRate, 44100);
+    meta->setInt32(kKeyChannelCount, 2);  // XXX
+
+    return meta;
+}
+
+status_t ShoutcastSource::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    assert(mStarted);
+
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        return ERROR_UNSUPPORTED;
+    }
+
+    MediaBuffer *buffer;
+    status_t err = mGroup->acquire_buffer(&buffer);
+    if (err != OK) {
+        return err;
+    }
+
+    *out = buffer;
+
+    size_t num_bytes = buffer->size();
+    if (mMetaDataOffset > 0 && num_bytes > mBytesUntilMetaData) {
+        num_bytes = mBytesUntilMetaData;
+    }
+
+    ssize_t n = mHttp->receive(buffer->data(), num_bytes);
+
+    if (n <= 0) {
+        return (status_t)n;
+    }
+
+    buffer->set_range(0, n);
+
+    mBytesUntilMetaData -= (size_t)n;
+
+    if (mBytesUntilMetaData == 0) {
+        unsigned char num_16_byte_blocks = 0;
+        n = mHttp->receive((char *)&num_16_byte_blocks, 1);
+        assert(n == 1);
+
+        char meta[255 * 16];
+        size_t meta_size = num_16_byte_blocks * 16;
+        size_t meta_length = 0;
+        while (meta_length < meta_size) {
+            n = mHttp->receive(&meta[meta_length], meta_size - meta_length);
+            if (n <= 0) {
+                return (status_t)n;
+            }
+
+            meta_length += (size_t) n;
+        }
+
+        while (meta_length > 0 && meta[meta_length - 1] == '\0') {
+            --meta_length;
+        }
+
+        if (meta_length > 0) {
+            // Technically we should probably attach this meta data to the
+            // next buffer. XXX
+            buffer->meta_data()->setData('shou', 'shou', meta, meta_length);
+        }
+
+        mBytesUntilMetaData = mMetaDataOffset;
+    }
+
+    return OK;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/SoftwareRenderer.cpp b/media/libstagefright/SoftwareRenderer.cpp
new file mode 100644
index 0000000..66b6b07
--- /dev/null
+++ b/media/libstagefright/SoftwareRenderer.cpp
@@ -0,0 +1,173 @@
+/*
+ * 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 "SoftwareRenderer"
+#include <utils/Log.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <binder/MemoryHeapBase.h>
+#include <media/stagefright/SoftwareRenderer.h>
+#include <ui/ISurface.h>
+
+namespace android {
+
+#define QCOM_YUV        0
+
+SoftwareRenderer::SoftwareRenderer(
+        const sp<ISurface> &surface,
+        size_t displayWidth, size_t displayHeight,
+        size_t decodedWidth, size_t decodedHeight)
+    : mISurface(surface),
+      mDisplayWidth(displayWidth),
+      mDisplayHeight(displayHeight),
+      mDecodedWidth(decodedWidth),
+      mDecodedHeight(decodedHeight),
+      mFrameSize(mDecodedWidth * mDecodedHeight * 2),  // RGB565
+      mMemoryHeap(new MemoryHeapBase(2 * mFrameSize)),
+      mIndex(0) {
+    assert(mISurface.get() != NULL);
+    assert(mDecodedWidth > 0);
+    assert(mDecodedHeight > 0);
+    assert(mMemoryHeap->heapID() >= 0);
+
+    ISurface::BufferHeap bufferHeap(
+            mDisplayWidth, mDisplayHeight,
+            mDecodedWidth, mDecodedHeight,
+            PIXEL_FORMAT_RGB_565,
+            mMemoryHeap);
+
+    status_t err = mISurface->registerBuffers(bufferHeap);
+    assert(err == OK);
+}
+
+SoftwareRenderer::~SoftwareRenderer() {
+    mISurface->unregisterBuffers();
+}
+
+void SoftwareRenderer::render(
+        const void *data, size_t size, void *platformPrivate) {
+    assert(size >= (mDecodedWidth * mDecodedHeight * 3) / 2);
+
+    static const signed kClipMin = -278;
+    static const signed kClipMax = 535;
+    static uint8_t kClip[kClipMax - kClipMin + 1];
+    static uint8_t *kAdjustedClip = &kClip[-kClipMin];
+
+    static bool clipInitialized = false;
+
+    if (!clipInitialized) {
+        for (signed i = kClipMin; i <= kClipMax; ++i) {
+            kClip[i - kClipMin] = (i < 0) ? 0 : (i > 255) ? 255 : (uint8_t)i;
+        }
+        clipInitialized = true;
+    }
+
+    size_t offset = mIndex * mFrameSize;
+
+    void *dst = (uint8_t *)mMemoryHeap->getBase() + offset;
+
+    uint32_t *dst_ptr = (uint32_t *)dst;
+
+    const uint8_t *src_y = (const uint8_t *)data;
+
+    const uint8_t *src_u =
+        (const uint8_t *)src_y + mDecodedWidth * mDecodedHeight;
+
+#if !QCOM_YUV
+    const uint8_t *src_v =
+        (const uint8_t *)src_u + (mDecodedWidth / 2) * (mDecodedHeight / 2);
+#endif
+
+    for (size_t y = 0; y < mDecodedHeight; ++y) {
+        for (size_t x = 0; x < mDecodedWidth; x += 2) {
+            // B = 1.164 * (Y - 16) + 2.018 * (U - 128)
+            // G = 1.164 * (Y - 16) - 0.813 * (V - 128) - 0.391 * (U - 128)
+            // R = 1.164 * (Y - 16) + 1.596 * (V - 128)
+
+            // B = 298/256 * (Y - 16) + 517/256 * (U - 128)
+            // G = .................. - 208/256 * (V - 128) - 100/256 * (U - 128)
+            // R = .................. + 409/256 * (V - 128)
+
+            // min_B = (298 * (- 16) + 517 * (- 128)) / 256 = -277
+            // min_G = (298 * (- 16) - 208 * (255 - 128) - 100 * (255 - 128)) / 256 = -172
+            // min_R = (298 * (- 16) + 409 * (- 128)) / 256 = -223
+
+            // max_B = (298 * (255 - 16) + 517 * (255 - 128)) / 256 = 534
+            // max_G = (298 * (255 - 16) - 208 * (- 128) - 100 * (- 128)) / 256 = 432
+            // max_R = (298 * (255 - 16) + 409 * (255 - 128)) / 256 = 481
+
+            // clip range -278 .. 535
+
+            signed y1 = (signed)src_y[x] - 16;
+            signed y2 = (signed)src_y[x + 1] - 16;
+
+#if QCOM_YUV
+            signed u = (signed)src_u[x & ~1] - 128;
+            signed v = (signed)src_u[(x & ~1) + 1] - 128;
+#else
+            signed u = (signed)src_u[x / 2] - 128;
+            signed v = (signed)src_v[x / 2] - 128;
+#endif
+
+            signed u_b = u * 517;
+            signed u_g = -u * 100;
+            signed v_g = -v * 208;
+            signed v_r = v * 409;
+
+            signed tmp1 = y1 * 298;
+            signed b1 = (tmp1 + u_b) / 256;
+            signed g1 = (tmp1 + v_g + u_g) / 256;
+            signed r1 = (tmp1 + v_r) / 256;
+
+            signed tmp2 = y2 * 298;
+            signed b2 = (tmp2 + u_b) / 256;
+            signed g2 = (tmp2 + v_g + u_g) / 256;
+            signed r2 = (tmp2 + v_r) / 256;
+
+            uint32_t rgb1 =
+                ((kAdjustedClip[r1] >> 3) << 11)
+                | ((kAdjustedClip[g1] >> 2) << 5)
+                | (kAdjustedClip[b1] >> 3);
+
+            uint32_t rgb2 =
+                ((kAdjustedClip[r2] >> 3) << 11)
+                | ((kAdjustedClip[g2] >> 2) << 5)
+                | (kAdjustedClip[b2] >> 3);
+
+            dst_ptr[x / 2] = (rgb2 << 16) | rgb1;
+        }
+
+        src_y += mDecodedWidth;
+
+        if (y & 1) {
+#if QCOM_YUV
+            src_u += mDecodedWidth;
+#else
+            src_u += mDecodedWidth / 2;
+            src_v += mDecodedWidth / 2;
+#endif
+        }
+
+        dst_ptr += mDecodedWidth / 2;
+    }
+
+    mISurface->postBuffer(offset);
+    mIndex = 1 - mIndex;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/SurfaceRenderer.cpp b/media/libstagefright/SurfaceRenderer.cpp
new file mode 100644
index 0000000..e54288d
--- /dev/null
+++ b/media/libstagefright/SurfaceRenderer.cpp
@@ -0,0 +1,69 @@
+/*
+ * 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 "SurfaceRenderer"
+#include <utils/Log.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <media/stagefright/SurfaceRenderer.h>
+#include <ui/Surface.h>
+
+namespace android {
+
+SurfaceRenderer::SurfaceRenderer(
+        const sp<Surface> &surface,
+        size_t displayWidth, size_t displayHeight,
+        size_t decodedWidth, size_t decodedHeight)
+    : mSurface(surface),
+      mDisplayWidth(displayWidth),
+      mDisplayHeight(displayHeight),
+      mDecodedWidth(decodedWidth),
+      mDecodedHeight(decodedHeight) {
+}
+
+SurfaceRenderer::~SurfaceRenderer() {
+}
+
+void SurfaceRenderer::render(
+        const void *data, size_t size, void *platformPrivate) {
+    Surface::SurfaceInfo info;
+    status_t err = mSurface->lock(&info);
+    if (err != OK) {
+        return;
+    }
+
+    const uint8_t *src = (const uint8_t *)data;
+    uint8_t *dst = (uint8_t *)info.bits;
+
+    for (size_t i = 0; i < mDisplayHeight; ++i) {
+        memcpy(dst, src, mDisplayWidth);
+        src += mDecodedWidth;
+        dst += mDisplayWidth;
+    }
+    src += (mDecodedHeight - mDisplayHeight) * mDecodedWidth;
+    
+    for (size_t i = 0; i < (mDisplayHeight + 1) / 2; ++i) {
+        memcpy(dst, src, (mDisplayWidth + 1) & ~1);
+        src += (mDecodedWidth + 1) & ~1;
+        dst += (mDisplayWidth + 1) & ~1;
+    }
+
+    mSurface->unlockAndPost();
+}
+
+}  // namespace android
diff --git a/media/libstagefright/TimeSource.cpp b/media/libstagefright/TimeSource.cpp
new file mode 100644
index 0000000..d987fbf
--- /dev/null
+++ b/media/libstagefright/TimeSource.cpp
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+#include <stddef.h>
+#include <sys/time.h>
+
+#include <media/stagefright/TimeSource.h>
+
+namespace android {
+
+SystemTimeSource::SystemTimeSource()
+    : mStartTimeUs(GetSystemTimeUs()) {
+}
+
+int64_t SystemTimeSource::getRealTimeUs() {
+    return GetSystemTimeUs() - mStartTimeUs;
+}
+
+// static
+int64_t SystemTimeSource::GetSystemTimeUs() {
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+
+    return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/TimedEventQueue.cpp b/media/libstagefright/TimedEventQueue.cpp
new file mode 100644
index 0000000..2f8a19f
--- /dev/null
+++ b/media/libstagefright/TimedEventQueue.cpp
@@ -0,0 +1,207 @@
+/*
+ * 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.
+ */
+
+#undef __STRICT_ANSI__
+#define __STDINT_LIMITS
+#define __STDC_LIMIT_MACROS
+#include <stdint.h>
+
+#define LOG_TAG "TimedEventQueue"
+#include <utils/Log.h>
+
+#include <sys/time.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include <media/stagefright/TimedEventQueue.h>
+
+namespace android {
+
+TimedEventQueue::TimedEventQueue()
+    : mRunning(false),
+      mStopped(false) {
+}
+
+TimedEventQueue::~TimedEventQueue() {
+    stop();
+}
+
+void TimedEventQueue::start() {
+    if (mRunning) {
+        return;
+    }
+
+    mStopped = false;
+
+    pthread_attr_t attr;
+    pthread_attr_init(&attr);
+    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
+
+    pthread_create(&mThread, &attr, ThreadWrapper, this);
+
+    pthread_attr_destroy(&attr);
+
+    mRunning = true;
+}
+
+void TimedEventQueue::stop(bool flush) {
+    if (!mRunning) {
+        return;
+    }
+
+    if (flush) {
+        postEventToBack(new StopEvent);
+    } else {
+        postTimedEvent(new StopEvent, INT64_MIN);
+    }
+
+    void *dummy;
+    pthread_join(mThread, &dummy);
+
+    mQueue.clear();
+
+    mRunning = false;
+}
+
+void TimedEventQueue::postEvent(const sp<Event> &event) {
+    // Reserve an earlier timeslot an INT64_MIN to be able to post
+    // the StopEvent to the absolute head of the queue.
+    postTimedEvent(event, INT64_MIN + 1);
+}
+
+void TimedEventQueue::postEventToBack(const sp<Event> &event) {
+    postTimedEvent(event, INT64_MAX);
+}
+
+void TimedEventQueue::postEventWithDelay(
+        const sp<Event> &event, int64_t delay_us) {
+    assert(delay_us >= 0);
+    postTimedEvent(event, getRealTimeUs() + delay_us);
+}
+
+void TimedEventQueue::postTimedEvent(
+        const sp<Event> &event, int64_t realtime_us) {
+    Mutex::Autolock autoLock(mLock);
+
+    List<QueueItem>::iterator it = mQueue.begin();
+    while (it != mQueue.end() && realtime_us >= (*it).realtime_us) {
+        ++it;
+    }
+
+    QueueItem item;
+    item.event = event;
+    item.realtime_us = realtime_us;
+
+    if (it == mQueue.begin()) {
+        mQueueHeadChangedCondition.signal();
+    }
+
+    mQueue.insert(it, item);
+
+    mQueueNotEmptyCondition.signal();
+}
+
+bool TimedEventQueue::cancelEvent(const sp<Event> &event) {
+    Mutex::Autolock autoLock(mLock);
+
+    List<QueueItem>::iterator it = mQueue.begin();
+    while (it != mQueue.end() && (*it).event != event) {
+        ++it;
+    }
+
+    if (it == mQueue.end()) {
+        return false;
+    }
+
+    if (it == mQueue.begin()) {
+        mQueueHeadChangedCondition.signal();
+    }
+
+    mQueue.erase(it);
+
+    return true;
+}
+
+// static
+int64_t TimedEventQueue::getRealTimeUs() {
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+
+    return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
+}
+
+// static
+void *TimedEventQueue::ThreadWrapper(void *me) {
+    static_cast<TimedEventQueue *>(me)->threadEntry();
+
+    return NULL;
+}
+
+void TimedEventQueue::threadEntry() {
+    for (;;) {
+        int64_t now_us;
+        sp<Event> event;
+
+        {
+            Mutex::Autolock autoLock(mLock);
+
+            if (mStopped) {
+                break;
+            }
+
+            while (mQueue.empty()) {
+                mQueueNotEmptyCondition.wait(mLock);
+            }
+
+            List<QueueItem>::iterator it;
+            for (;;) {
+                it = mQueue.begin();
+
+                now_us = getRealTimeUs();
+                int64_t when_us = (*it).realtime_us;
+
+                int64_t delay_us;
+                if (when_us < 0 || when_us == INT64_MAX) {
+                    delay_us = 0;
+                } else {
+                    delay_us = when_us - now_us;
+                }
+
+                if (delay_us <= 0) {
+                    break;
+                }
+
+                status_t err = mQueueHeadChangedCondition.waitRelative(
+                        mLock, delay_us * 1000);
+
+                if (err == -ETIMEDOUT) {
+                    now_us = getRealTimeUs();
+                    break;
+                }
+            }
+
+            event = (*it).event;
+            mQueue.erase(it);
+        }
+
+        // Fire event with the lock NOT held.
+        event->fire(this, now_us);
+    }
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/Utils.cpp b/media/libstagefright/Utils.cpp
new file mode 100644
index 0000000..2720f93
--- /dev/null
+++ b/media/libstagefright/Utils.cpp
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+
+#include <arpa/inet.h>
+
+#include <media/stagefright/Utils.h>
+
+namespace android {
+
+uint16_t U16_AT(const uint8_t *ptr) {
+    return ptr[0] << 8 | ptr[1];
+}
+
+uint32_t U32_AT(const uint8_t *ptr) {
+    return ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
+}
+
+uint64_t U64_AT(const uint8_t *ptr) {
+    return ((uint64_t)U32_AT(ptr)) << 32 | U32_AT(ptr + 4);
+}
+
+// XXX warning: these won't work on big-endian host.
+uint64_t ntoh64(uint64_t x) {
+    return ((uint64_t)ntohl(x & 0xffffffff) << 32) | ntohl(x >> 32);
+}
+
+uint64_t hton64(uint64_t x) {
+    return ((uint64_t)htonl(x & 0xffffffff) << 32) | htonl(x >> 32);
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/omx/Android.mk b/media/libstagefright/omx/Android.mk
new file mode 100644
index 0000000..9c6d475
--- /dev/null
+++ b/media/libstagefright/omx/Android.mk
@@ -0,0 +1,27 @@
+ifeq ($(BUILD_WITH_STAGEFRIGHT),true)
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+# Set up the OpenCore variables.
+include external/opencore/Config.mk
+LOCAL_C_INCLUDES := $(PV_INCLUDES)
+LOCAL_CFLAGS := $(PV_CFLAGS_MINUS_VISIBILITY)
+
+LOCAL_SRC_FILES:=                 \
+	OMX.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+        libbinder         \
+        libmedia          \
+	libutils          \
+        libui             \
+        libopencore_common
+
+LOCAL_PRELINK_MODULE:= false
+
+LOCAL_MODULE:= libstagefright_omx
+
+include $(BUILD_SHARED_LIBRARY)
+
+endif
diff --git a/media/libstagefright/omx/OMX.cpp b/media/libstagefright/omx/OMX.cpp
new file mode 100644
index 0000000..daaa741
--- /dev/null
+++ b/media/libstagefright/omx/OMX.cpp
@@ -0,0 +1,623 @@
+/*
+ * 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_NDEBUG 0
+#define LOG_TAG "OMX"
+#include <utils/Log.h>
+
+#include <sys/socket.h>
+
+#undef NDEBUG
+#include <assert.h>
+
+#include "OMX.h"
+#include "pv_omxcore.h"
+
+#include <binder/IMemory.h>
+
+#include <OMX_Component.h>
+
+namespace android {
+
+class NodeMeta {
+public:
+    NodeMeta(OMX *owner)
+        : mOwner(owner),
+          mHandle(NULL) {
+    }
+
+    OMX *owner() const {
+        return mOwner;
+    }
+
+    void setHandle(OMX_HANDLETYPE handle) {
+        assert(mHandle == NULL);
+        mHandle = handle;
+    }
+
+    OMX_HANDLETYPE handle() const {
+        return mHandle;
+    }
+
+    void setObserver(const sp<IOMXObserver> &observer) {
+        mObserver = observer;
+    }
+
+    sp<IOMXObserver> observer() {
+        return mObserver;
+    }
+
+private:
+    OMX *mOwner;
+    OMX_HANDLETYPE mHandle;
+    sp<IOMXObserver> mObserver;
+
+    NodeMeta(const NodeMeta &);
+    NodeMeta &operator=(const NodeMeta &);
+};
+
+class BufferMeta {
+public:
+    BufferMeta(OMX *owner, const sp<IMemory> &mem, bool is_backup = false)
+        : mOwner(owner),
+          mMem(mem),
+          mIsBackup(is_backup) {
+    }
+
+    BufferMeta(OMX *owner, size_t size)
+        : mOwner(owner),
+          mSize(size),
+          mIsBackup(false) {
+    }
+
+    void CopyFromOMX(const OMX_BUFFERHEADERTYPE *header) {
+        if (!mIsBackup) {
+            return;
+        }
+
+        memcpy((OMX_U8 *)mMem->pointer() + header->nOffset,
+               header->pBuffer + header->nOffset,
+               header->nFilledLen);
+    }
+
+    void CopyToOMX(const OMX_BUFFERHEADERTYPE *header) {
+        if (!mIsBackup) {
+            return;
+        }
+
+        memcpy(header->pBuffer + header->nOffset,
+               (const OMX_U8 *)mMem->pointer() + header->nOffset,
+               header->nFilledLen);
+    }
+
+private:
+    OMX *mOwner;
+    sp<IMemory> mMem;
+    size_t mSize;
+    bool mIsBackup;
+
+    BufferMeta(const BufferMeta &);
+    BufferMeta &operator=(const BufferMeta &);
+};
+
+// static
+OMX_CALLBACKTYPE OMX::kCallbacks = {
+    &OnEvent, &OnEmptyBufferDone, &OnFillBufferDone
+};
+
+// static
+OMX_ERRORTYPE OMX::OnEvent(
+        OMX_IN OMX_HANDLETYPE hComponent,
+        OMX_IN OMX_PTR pAppData,
+        OMX_IN OMX_EVENTTYPE eEvent,
+        OMX_IN OMX_U32 nData1,
+        OMX_IN OMX_U32 nData2,
+        OMX_IN OMX_PTR pEventData) {
+    NodeMeta *meta = static_cast<NodeMeta *>(pAppData);
+    return meta->owner()->OnEvent(meta, eEvent, nData1, nData2, pEventData);
+}
+
+// static
+OMX_ERRORTYPE OMX::OnEmptyBufferDone(
+        OMX_IN OMX_HANDLETYPE hComponent,
+        OMX_IN OMX_PTR pAppData,
+        OMX_IN OMX_BUFFERHEADERTYPE* pBuffer) {
+    NodeMeta *meta = static_cast<NodeMeta *>(pAppData);
+    return meta->owner()->OnEmptyBufferDone(meta, pBuffer);
+}
+
+// static
+OMX_ERRORTYPE OMX::OnFillBufferDone(
+        OMX_IN OMX_HANDLETYPE hComponent,
+        OMX_IN OMX_PTR pAppData,
+        OMX_IN OMX_BUFFERHEADERTYPE* pBuffer) {
+    NodeMeta *meta = static_cast<NodeMeta *>(pAppData);
+    return meta->owner()->OnFillBufferDone(meta, pBuffer);
+}
+
+OMX::OMX()
+#if IOMX_USES_SOCKETS
+    : mSock(-1)
+#endif
+{
+}
+
+OMX::~OMX() {
+#if IOMX_USES_SOCKETS
+    assert(mSock < 0);
+#endif
+}
+
+#if IOMX_USES_SOCKETS
+status_t OMX::connect(int *sd) {
+    Mutex::Autolock autoLock(mLock);
+
+    if (mSock >= 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    int sockets[2];
+    if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets) < 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    mSock = sockets[0];
+    *sd = sockets[1];
+
+    pthread_attr_t attr;
+    pthread_attr_init(&attr);
+    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
+
+    int err = pthread_create(&mThread, &attr, ThreadWrapper, this);
+    assert(err == 0);
+
+    pthread_attr_destroy(&attr);
+
+    return OK;
+}
+
+// static
+void *OMX::ThreadWrapper(void *me) {
+    ((OMX *)me)->threadEntry();
+
+    return NULL;
+}
+
+void OMX::threadEntry() {
+    bool done = false;
+    while (!done) {
+        omx_message msg;
+        ssize_t n = recv(mSock, &msg, sizeof(msg), 0);
+
+        if (n <= 0) {
+            break;
+        }
+
+        Mutex::Autolock autoLock(mLock);
+
+        switch (msg.type) {
+            case omx_message::FILL_BUFFER:
+            {
+                OMX_BUFFERHEADERTYPE *header =
+                    static_cast<OMX_BUFFERHEADERTYPE *>(
+                            msg.u.buffer_data.buffer);
+
+                header->nFilledLen = 0;
+                header->nOffset = 0;
+                header->hMarkTargetComponent = NULL;
+                header->nFlags = 0;
+
+                NodeMeta *node_meta = static_cast<NodeMeta *>(
+                        msg.u.buffer_data.node);
+                
+                LOGV("FillThisBuffer buffer=%p", header);
+
+                OMX_ERRORTYPE err =
+                    OMX_FillThisBuffer(node_meta->handle(), header);
+                assert(err == OMX_ErrorNone);
+                break;
+            }
+
+            case omx_message::EMPTY_BUFFER:
+            {
+                OMX_BUFFERHEADERTYPE *header =
+                    static_cast<OMX_BUFFERHEADERTYPE *>(
+                            msg.u.extended_buffer_data.buffer);
+
+                header->nFilledLen = msg.u.extended_buffer_data.range_length;
+                header->nOffset = msg.u.extended_buffer_data.range_offset;
+                header->hMarkTargetComponent = NULL;
+                header->nFlags = msg.u.extended_buffer_data.flags;
+                header->nTimeStamp = msg.u.extended_buffer_data.timestamp;
+
+                BufferMeta *buffer_meta =
+                    static_cast<BufferMeta *>(header->pAppPrivate);
+                buffer_meta->CopyToOMX(header);
+
+                NodeMeta *node_meta = static_cast<NodeMeta *>(
+                        msg.u.extended_buffer_data.node);
+
+                LOGV("EmptyThisBuffer buffer=%p", header);
+
+                OMX_ERRORTYPE err =
+                    OMX_EmptyThisBuffer(node_meta->handle(), header);
+                assert(err == OMX_ErrorNone);
+                break;
+            }
+
+            case omx_message::SEND_COMMAND:
+            {
+                NodeMeta *node_meta = static_cast<NodeMeta *>(
+                        msg.u.send_command_data.node);
+
+                OMX_ERRORTYPE err =
+                    OMX_SendCommand(
+                            node_meta->handle(), msg.u.send_command_data.cmd,
+                            msg.u.send_command_data.param, NULL);
+                assert(err == OMX_ErrorNone);
+                break;
+            }
+
+            case omx_message::DISCONNECT:
+            {
+                omx_message msg;
+                msg.type = omx_message::DISCONNECTED;
+                ssize_t n = send(mSock, &msg, sizeof(msg), 0);
+                assert(n > 0 && static_cast<size_t>(n) == sizeof(msg));
+                done = true;
+                break;
+            }
+
+            default:
+                LOGE("received unknown omx_message type %d", msg.type);
+                break;
+        }
+    }
+
+    Mutex::Autolock autoLock(mLock);
+    close(mSock);
+    mSock = -1;
+}
+#endif
+
+status_t OMX::list_nodes(List<String8> *list) {
+    OMX_MasterInit();  // XXX Put this somewhere else.
+
+    list->clear();
+
+    OMX_U32 index = 0;
+    char componentName[256];
+    while (OMX_MasterComponentNameEnum(componentName, sizeof(componentName), index)
+               == OMX_ErrorNone) {
+        list->push_back(String8(componentName));
+
+        ++index;
+    }
+
+    return OK;
+}
+
+status_t OMX::allocate_node(const char *name, node_id *node) {
+    Mutex::Autolock autoLock(mLock);
+
+    *node = 0;
+
+    OMX_MasterInit();  // XXX Put this somewhere else.
+
+    NodeMeta *meta = new NodeMeta(this);
+
+    OMX_HANDLETYPE handle;
+    OMX_ERRORTYPE err = OMX_MasterGetHandle(
+            &handle, const_cast<char *>(name), meta, &kCallbacks);
+
+    if (err != OMX_ErrorNone) {
+        LOGE("FAILED to allocate omx component '%s'", name);
+
+        delete meta;
+        meta = NULL;
+
+        return UNKNOWN_ERROR;
+    }
+
+    meta->setHandle(handle);
+
+    *node = meta;
+
+    return OK;
+}
+
+status_t OMX::free_node(node_id node) {
+    Mutex::Autolock autoLock(mLock);
+
+    NodeMeta *meta = static_cast<NodeMeta *>(node);
+
+    OMX_ERRORTYPE err = OMX_MasterFreeHandle(meta->handle());
+
+    delete meta;
+    meta = NULL;
+
+    return (err != OMX_ErrorNone) ? UNKNOWN_ERROR : OK;
+}
+
+status_t OMX::send_command(
+        node_id node, OMX_COMMANDTYPE cmd, OMX_S32 param) {
+    Mutex::Autolock autoLock(mLock);
+
+#if IOMX_USES_SOCKETS
+    if (mSock < 0) {
+        return UNKNOWN_ERROR;
+    }
+#endif
+
+    NodeMeta *meta = static_cast<NodeMeta *>(node);
+    OMX_ERRORTYPE err = OMX_SendCommand(meta->handle(), cmd, param, NULL);
+
+    return (err != OMX_ErrorNone) ? UNKNOWN_ERROR : OK;
+}
+
+status_t OMX::get_parameter(
+        node_id node, OMX_INDEXTYPE index,
+        void *params, size_t size) {
+    Mutex::Autolock autoLock(mLock);
+
+    NodeMeta *meta = static_cast<NodeMeta *>(node);
+    OMX_ERRORTYPE err = OMX_GetParameter(meta->handle(), index, params);
+
+    return (err != OMX_ErrorNone) ? UNKNOWN_ERROR : OK;
+}
+
+status_t OMX::set_parameter(
+        node_id node, OMX_INDEXTYPE index,
+        const void *params, size_t size) {
+    Mutex::Autolock autoLock(mLock);
+
+    NodeMeta *meta = static_cast<NodeMeta *>(node);
+    OMX_ERRORTYPE err =
+        OMX_SetParameter(meta->handle(), index, const_cast<void *>(params));
+
+    return (err != OMX_ErrorNone) ? UNKNOWN_ERROR : OK;
+}
+
+status_t OMX::use_buffer(
+        node_id node, OMX_U32 port_index, const sp<IMemory> &params,
+        buffer_id *buffer) {
+    Mutex::Autolock autoLock(mLock);
+
+    BufferMeta *buffer_meta = new BufferMeta(this, params);
+
+    OMX_BUFFERHEADERTYPE *header;
+
+    NodeMeta *node_meta = static_cast<NodeMeta *>(node);
+    OMX_ERRORTYPE err =
+        OMX_UseBuffer(node_meta->handle(), &header, port_index, buffer_meta,
+                      params->size(), static_cast<OMX_U8 *>(params->pointer()));
+
+    if (err != OMX_ErrorNone) {
+        LOGE("OMX_UseBuffer failed with error %d (0x%08x)", err, err);
+
+        delete buffer_meta;
+        buffer_meta = NULL;
+
+        *buffer = 0;
+        return UNKNOWN_ERROR;
+    }
+
+    *buffer = header;
+
+    return OK;
+}
+
+status_t OMX::allocate_buffer(
+        node_id node, OMX_U32 port_index, size_t size,
+        buffer_id *buffer) {
+    Mutex::Autolock autoLock(mLock);
+
+    BufferMeta *buffer_meta = new BufferMeta(this, size);
+
+    OMX_BUFFERHEADERTYPE *header;
+
+    NodeMeta *node_meta = static_cast<NodeMeta *>(node);
+    OMX_ERRORTYPE err =
+        OMX_AllocateBuffer(node_meta->handle(), &header, port_index,
+                           buffer_meta, size);
+
+    if (err != OMX_ErrorNone) {
+        delete buffer_meta;
+        buffer_meta = NULL;
+
+        *buffer = 0;
+        return UNKNOWN_ERROR;
+    }
+
+    *buffer = header;
+
+    return OK;
+}
+
+status_t OMX::allocate_buffer_with_backup(
+        node_id node, OMX_U32 port_index, const sp<IMemory> &params,
+        buffer_id *buffer) {
+    Mutex::Autolock autoLock(mLock);
+
+    BufferMeta *buffer_meta = new BufferMeta(this, params, true);
+
+    OMX_BUFFERHEADERTYPE *header;
+
+    NodeMeta *node_meta = static_cast<NodeMeta *>(node);
+    OMX_ERRORTYPE err =
+        OMX_AllocateBuffer(
+                node_meta->handle(), &header, port_index, buffer_meta,
+                params->size());
+
+    if (err != OMX_ErrorNone) {
+        delete buffer_meta;
+        buffer_meta = NULL;
+
+        *buffer = 0;
+        return UNKNOWN_ERROR;
+    }
+
+    *buffer = header;
+
+    return OK;
+}
+
+status_t OMX::free_buffer(node_id node, OMX_U32 port_index, buffer_id buffer) {
+    OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *)buffer;
+    BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate);
+
+    NodeMeta *node_meta = static_cast<NodeMeta *>(node);
+    OMX_ERRORTYPE err =
+        OMX_FreeBuffer(node_meta->handle(), port_index, header);
+
+    delete buffer_meta;
+    buffer_meta = NULL;
+
+    return (err != OMX_ErrorNone) ? UNKNOWN_ERROR : OK;
+}
+
+OMX_ERRORTYPE OMX::OnEvent(
+        NodeMeta *meta,
+        OMX_IN OMX_EVENTTYPE eEvent,
+        OMX_IN OMX_U32 nData1,
+        OMX_IN OMX_U32 nData2,
+        OMX_IN OMX_PTR pEventData) {
+    LOGV("OnEvent(%d, %ld, %ld)", eEvent, nData1, nData2);
+
+    omx_message msg;
+    msg.type = omx_message::EVENT;
+    msg.u.event_data.node = meta;
+    msg.u.event_data.event = eEvent;
+    msg.u.event_data.data1 = nData1;
+    msg.u.event_data.data2 = nData2;
+
+#if !IOMX_USES_SOCKETS
+    sp<IOMXObserver> observer = meta->observer();
+    if (observer.get() != NULL) {
+        observer->on_message(msg);
+    }
+#else
+    assert(mSock >= 0);
+
+    ssize_t n = send(mSock, &msg, sizeof(msg), 0);
+    assert(n > 0 && static_cast<size_t>(n) == sizeof(msg));
+#endif
+
+    return OMX_ErrorNone;
+}
+    
+OMX_ERRORTYPE OMX::OnEmptyBufferDone(
+        NodeMeta *meta, OMX_IN OMX_BUFFERHEADERTYPE *pBuffer) {
+    LOGV("OnEmptyBufferDone buffer=%p", pBuffer);
+
+    omx_message msg;
+    msg.type = omx_message::EMPTY_BUFFER_DONE;
+    msg.u.buffer_data.node = meta;
+    msg.u.buffer_data.buffer = pBuffer;
+
+#if !IOMX_USES_SOCKETS
+    sp<IOMXObserver> observer = meta->observer();
+    if (observer.get() != NULL) {
+        observer->on_message(msg);
+    }
+#else
+    assert(mSock >= 0);
+    ssize_t n = send(mSock, &msg, sizeof(msg), 0);
+    assert(n > 0 && static_cast<size_t>(n) == sizeof(msg));
+#endif
+
+    return OMX_ErrorNone;
+}
+
+OMX_ERRORTYPE OMX::OnFillBufferDone(
+        NodeMeta *meta, OMX_IN OMX_BUFFERHEADERTYPE *pBuffer) {
+    LOGV("OnFillBufferDone buffer=%p", pBuffer);
+    BufferMeta *buffer_meta = static_cast<BufferMeta *>(pBuffer->pAppPrivate);
+    buffer_meta->CopyFromOMX(pBuffer);
+
+    omx_message msg;
+    msg.type = omx_message::FILL_BUFFER_DONE;
+    msg.u.extended_buffer_data.node = meta;
+    msg.u.extended_buffer_data.buffer = pBuffer;
+    msg.u.extended_buffer_data.range_offset = pBuffer->nOffset;
+    msg.u.extended_buffer_data.range_length = pBuffer->nFilledLen;
+    msg.u.extended_buffer_data.flags = pBuffer->nFlags;
+    msg.u.extended_buffer_data.timestamp = pBuffer->nTimeStamp;
+    msg.u.extended_buffer_data.platform_private = pBuffer->pPlatformPrivate;
+
+#if !IOMX_USES_SOCKETS
+    sp<IOMXObserver> observer = meta->observer();
+    if (observer.get() != NULL) {
+        observer->on_message(msg);
+    }
+#else
+    assert(mSock >= 0);
+
+    ssize_t n = send(mSock, &msg, sizeof(msg), 0);
+    assert(n > 0 && static_cast<size_t>(n) == sizeof(msg));
+#endif
+
+    return OMX_ErrorNone;
+}
+
+#if !IOMX_USES_SOCKETS
+status_t OMX::observe_node(
+        node_id node, const sp<IOMXObserver> &observer) {
+    NodeMeta *node_meta = static_cast<NodeMeta *>(node);
+
+    node_meta->setObserver(observer);
+
+    return OK;
+}
+
+void OMX::fill_buffer(node_id node, buffer_id buffer) {
+    OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *)buffer;
+    header->nFilledLen = 0;
+    header->nOffset = 0;
+    header->nFlags = 0;
+
+    NodeMeta *node_meta = static_cast<NodeMeta *>(node);
+
+    OMX_ERRORTYPE err =
+        OMX_FillThisBuffer(node_meta->handle(), header);
+    assert(err == OMX_ErrorNone);
+}
+
+void OMX::empty_buffer(
+        node_id node,
+        buffer_id buffer,
+        OMX_U32 range_offset, OMX_U32 range_length,
+        OMX_U32 flags, OMX_TICKS timestamp) {
+    OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *)buffer;
+    header->nFilledLen = range_length;
+    header->nOffset = range_offset;
+    header->nFlags = flags;
+    header->nTimeStamp = timestamp;
+
+    BufferMeta *buffer_meta =
+        static_cast<BufferMeta *>(header->pAppPrivate);
+    buffer_meta->CopyToOMX(header);
+
+    NodeMeta *node_meta = static_cast<NodeMeta *>(node);
+
+    OMX_ERRORTYPE err =
+        OMX_EmptyThisBuffer(node_meta->handle(), header);
+    assert(err == OMX_ErrorNone);
+}
+#endif
+
+}  // namespace android
+
diff --git a/media/libstagefright/omx/OMX.h b/media/libstagefright/omx/OMX.h
new file mode 100644
index 0000000..ed4e5dd
--- /dev/null
+++ b/media/libstagefright/omx/OMX.h
@@ -0,0 +1,132 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_OMX_H_
+#define ANDROID_OMX_H_
+
+#include <pthread.h>
+
+#include <media/IOMX.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class NodeMeta;
+
+class OMX : public BnOMX {
+public:
+    OMX();
+    virtual ~OMX();
+
+#if IOMX_USES_SOCKETS
+    virtual status_t connect(int *sd);
+#endif
+
+    virtual status_t list_nodes(List<String8> *list);
+
+    virtual status_t allocate_node(const char *name, node_id *node);
+    virtual status_t free_node(node_id node);
+
+    virtual status_t send_command(
+            node_id node, OMX_COMMANDTYPE cmd, OMX_S32 param);
+
+    virtual status_t get_parameter(
+            node_id node, OMX_INDEXTYPE index,
+            void *params, size_t size);
+
+    virtual status_t set_parameter(
+            node_id node, OMX_INDEXTYPE index,
+            const void *params, size_t size);
+
+    virtual status_t use_buffer(
+            node_id node, OMX_U32 port_index, const sp<IMemory> &params,
+            buffer_id *buffer);
+
+    virtual status_t allocate_buffer(
+            node_id node, OMX_U32 port_index, size_t size,
+            buffer_id *buffer);
+
+    virtual status_t allocate_buffer_with_backup(
+            node_id node, OMX_U32 port_index, const sp<IMemory> &params,
+            buffer_id *buffer);
+
+    virtual status_t free_buffer(
+            node_id node, OMX_U32 port_index, buffer_id buffer);
+
+#if !IOMX_USES_SOCKETS
+    virtual status_t observe_node(
+            node_id node, const sp<IOMXObserver> &observer);
+
+    virtual void fill_buffer(node_id node, buffer_id buffer);
+
+    virtual void empty_buffer(
+            node_id node,
+            buffer_id buffer,
+            OMX_U32 range_offset, OMX_U32 range_length,
+            OMX_U32 flags, OMX_TICKS timestamp);
+#endif
+
+private:
+    static OMX_CALLBACKTYPE kCallbacks;
+
+#if IOMX_USES_SOCKETS
+    int mSock;
+    pthread_t mThread;
+
+    static void *ThreadWrapper(void *me);
+    void threadEntry();
+#endif
+
+    Mutex mLock;
+
+    static OMX_ERRORTYPE OnEvent(
+            OMX_IN OMX_HANDLETYPE hComponent,
+            OMX_IN OMX_PTR pAppData,
+            OMX_IN OMX_EVENTTYPE eEvent,
+            OMX_IN OMX_U32 nData1,
+            OMX_IN OMX_U32 nData2,
+            OMX_IN OMX_PTR pEventData);
+
+    static OMX_ERRORTYPE OnEmptyBufferDone(
+            OMX_IN OMX_HANDLETYPE hComponent,
+            OMX_IN OMX_PTR pAppData,
+            OMX_IN OMX_BUFFERHEADERTYPE* pBuffer);
+
+    static OMX_ERRORTYPE OnFillBufferDone(
+            OMX_IN OMX_HANDLETYPE hComponent,
+            OMX_IN OMX_PTR pAppData,
+            OMX_IN OMX_BUFFERHEADERTYPE* pBuffer);
+
+    OMX_ERRORTYPE OnEvent(
+            NodeMeta *meta,
+            OMX_IN OMX_EVENTTYPE eEvent,
+            OMX_IN OMX_U32 nData1,
+            OMX_IN OMX_U32 nData2,
+            OMX_IN OMX_PTR pEventData);
+        
+    OMX_ERRORTYPE OnEmptyBufferDone(
+            NodeMeta *meta, OMX_IN OMX_BUFFERHEADERTYPE *pBuffer);
+
+    OMX_ERRORTYPE OnFillBufferDone(
+            NodeMeta *meta, OMX_IN OMX_BUFFERHEADERTYPE *pBuffer);
+
+    OMX(const OMX &);
+    OMX &operator=(const OMX &);
+};
+
+}  // namespace android
+
+#endif  // ANDROID_OMX_H_
diff --git a/media/libstagefright/string.cpp b/media/libstagefright/string.cpp
new file mode 100644
index 0000000..5b16784
--- /dev/null
+++ b/media/libstagefright/string.cpp
@@ -0,0 +1,83 @@
+/*
+ * 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.
+ */
+
+#include <media/stagefright/string.h>
+
+namespace android {
+
+// static
+string::size_type string::npos = (string::size_type)-1;
+
+string::string() {
+}
+
+string::string(const char *s, size_t length)
+    : mString(s, length) {
+}
+
+string::string(const string &from, size_type start, size_type length)
+    : mString(from.c_str() + start, length) {
+}
+
+string::string(const char *s)
+    : mString(s) {
+}
+
+const char *string::c_str() const {
+    return mString.string();
+}
+
+string::size_type string::size() const {
+    return mString.length();
+}
+
+void string::clear() {
+    mString = String8();
+}
+
+string::size_type string::find(char c) const {
+    char s[2];
+    s[0] = c;
+    s[1] = '\0';
+
+    ssize_t index = mString.find(s);
+
+    return index < 0 ? npos : (size_type)index;
+}
+
+bool string::operator<(const string &other) const {
+    return mString < other.mString;
+}
+
+bool string::operator==(const string &other) const {
+    return mString == other.mString;
+}
+
+string &string::operator+=(char c) {
+    mString.append(&c, 1);
+
+    return *this;
+}
+
+void string::erase(size_t from, size_t length) {
+    String8 s(mString.string(), from);
+    s.append(mString.string() + from + length);
+    
+    mString = s;
+}
+
+}  // namespace android
+
diff --git a/media/mediaserver/Android.mk b/media/mediaserver/Android.mk
index c681698..a92cea8 100644
--- a/media/mediaserver/Android.mk
+++ b/media/mediaserver/Android.mk
@@ -8,7 +8,8 @@
 	libaudioflinger \
 	libcameraservice \
 	libmediaplayerservice \
-	libutils
+	libutils \
+	libbinder
 
 base := $(LOCAL_PATH)/../..
 
diff --git a/media/mediaserver/main_mediaserver.cpp b/media/mediaserver/main_mediaserver.cpp
index 6954b63..7094cfa 100644
--- a/media/mediaserver/main_mediaserver.cpp
+++ b/media/mediaserver/main_mediaserver.cpp
@@ -20,14 +20,15 @@
 #include <unistd.h>
 #include <grp.h>
 
-#include <utils/IPCThreadState.h>
-#include <utils/ProcessState.h>
-#include <utils/IServiceManager.h>
+#include <binder/IPCThreadState.h>
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
 #include <utils/Log.h>
 
 #include <AudioFlinger.h>
 #include <CameraService.h>
 #include <MediaPlayerService.h>
+#include <AudioPolicyService.h>
 #include <private/android_filesystem_config.h>
 
 using namespace android;
@@ -40,6 +41,7 @@
     AudioFlinger::instantiate();
     MediaPlayerService::instantiate();
     CameraService::instantiate();
+    AudioPolicyService::instantiate();
     ProcessState::self()->startThreadPool();
     IPCThreadState::self()->joinThreadPool();
 }
diff --git a/media/sdutils/sdutil.cpp b/media/sdutils/sdutil.cpp
index 06120f5..fe11878 100644
--- a/media/sdutils/sdutil.cpp
+++ b/media/sdutils/sdutil.cpp
@@ -15,8 +15,8 @@
  */
 
 #include <hardware_legacy/IMountService.h>
-#include <utils/BpBinder.h>
-#include <utils/IServiceManager.h>
+#include <binder/BpBinder.h>
+#include <binder/IServiceManager.h>
 
 #include <stdio.h>
 #include <stdlib.h>
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkTestRunner.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkTestRunner.java
index 6edc2cc..2a4e9a0 100755
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkTestRunner.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkTestRunner.java
@@ -23,6 +23,7 @@
 import com.android.mediaframeworktest.functional.MediaPlayerApiTest;
 import com.android.mediaframeworktest.functional.MediaRecorderTest;
 import com.android.mediaframeworktest.functional.SimTonesTest;
+import com.android.mediaframeworktest.functional.MediaPlayerInvokeTest;
 
 import junit.framework.TestSuite;
 
@@ -32,7 +33,7 @@
 
 /**
  * Instrumentation Test Runner for all MediaPlayer tests.
- * 
+ *
  * Running all tests:
  *
  * adb shell am instrument \
@@ -52,6 +53,7 @@
         suite.addTestSuite(MediaRecorderTest.class);
         suite.addTestSuite(MediaAudioTrackTest.class);
         suite.addTestSuite(MediaMimeTest.class);
+        suite.addTestSuite(MediaPlayerInvokeTest.class);
         return suite;
     }
 
@@ -60,5 +62,3 @@
         return MediaFrameworkTestRunner.class.getClassLoader();
     }
 }
-
-
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkUnitTestRunner.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkUnitTestRunner.java
index 81d59da..a203adc 100755
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkUnitTestRunner.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkUnitTestRunner.java
@@ -24,16 +24,16 @@
 
 /**
  * Instrumentation Test Runner for all media framework unit tests.
- * 
+ *
  * Make sure that MediaFrameworkUnitTestRunner has been added to
  * AndroidManifest.xml file, and then "make -j4 mediaframeworktest; adb sync"
  * to build and upload mediaframeworktest to the phone or emulator.
- * 
+ *
  * Example on running all unit tests for a single class:
  * adb shell am instrument -e class \
- * com.android.mediaframeworktest.unit.MediaMetadataRetrieverUnitTest \ 
+ * com.android.mediaframeworktest.unit.MediaMetadataRetrieverUnitTest \
  * -w com.android.mediaframeworktest/.MediaFrameworkUnitTestRunner
- * 
+ *
  * Example on running all unit tests for the media framework:
  * adb shell am instrument \
  * -w com.android.mediaframeworktest/.MediaFrameworkUnitTestRunner
@@ -54,12 +54,12 @@
     public ClassLoader getLoader() {
         return MediaFrameworkUnitTestRunner.class.getClassLoader();
     }
-    
+
     // Running all unit tests checking the state machine may be time-consuming.
     private void addMediaMetadataRetrieverStateUnitTests(TestSuite suite) {
         suite.addTestSuite(MediaMetadataRetrieverTest.class);
     }
-    
+
     // Running all unit tests checking the state machine may be time-consuming.
     private void addMediaRecorderStateUnitTests(TestSuite suite) {
         suite.addTestSuite(MediaRecorderPrepareStateUnitTest.class);
@@ -87,5 +87,6 @@
         suite.addTestSuite(MediaPlayerSetLoopingStateUnitTest.class);
         suite.addTestSuite(MediaPlayerSetAudioStreamTypeStateUnitTest.class);
         suite.addTestSuite(MediaPlayerSetVolumeStateUnitTest.class);
+        suite.addTestSuite(MediaPlayerMetadataParserTest.class);
     }
 }
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaAudioTrackTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaAudioTrackTest.java
index aefedc3..cea3a5a 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaAudioTrackTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaAudioTrackTest.java
@@ -140,7 +140,7 @@
         
         TestResults res = constructorTestMultiSampleRate(
                 AudioManager.STREAM_MUSIC, AudioTrack.MODE_STREAM, 
-                    AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,
+                    AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
                 AudioTrack.STATE_INITIALIZED);
 
         assertTrue("testConstructorMono16MusicStream: " + res.mResultLog, res.mResult);
@@ -153,7 +153,7 @@
         
         TestResults res = constructorTestMultiSampleRate(
                 AudioManager.STREAM_MUSIC, AudioTrack.MODE_STREAM, 
-                    AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT,
+                    AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT,
                 AudioTrack.STATE_INITIALIZED);
 
         assertTrue("testConstructorStereo16MusicStream: " + res.mResultLog, res.mResult);
@@ -166,7 +166,7 @@
         
         TestResults res = constructorTestMultiSampleRate(
                 AudioManager.STREAM_MUSIC, AudioTrack.MODE_STATIC, 
-                    AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,
+                    AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
                 AudioTrack.STATE_NO_STATIC_DATA);
 
         assertTrue("testConstructorMono16MusicStatic: " + res.mResultLog, res.mResult);
@@ -179,7 +179,7 @@
         
         TestResults res = constructorTestMultiSampleRate(
                 AudioManager.STREAM_MUSIC, AudioTrack.MODE_STATIC, 
-                    AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT,
+                    AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT,
                 AudioTrack.STATE_NO_STATIC_DATA);
 
         assertTrue("testConstructorStereo16MusicStatic: " + res.mResultLog, res.mResult);
@@ -196,7 +196,7 @@
         
         TestResults res = constructorTestMultiSampleRate(
                 AudioManager.STREAM_MUSIC, AudioTrack.MODE_STREAM, 
-                    AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT,
+                    AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_8BIT,
                 AudioTrack.STATE_INITIALIZED);
 
         assertTrue("testConstructorMono8MusicStream: " + res.mResultLog, res.mResult);
@@ -208,7 +208,7 @@
         
         TestResults res = constructorTestMultiSampleRate(
                 AudioManager.STREAM_MUSIC, AudioTrack.MODE_STREAM, 
-                    AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_8BIT,
+                    AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_8BIT,
                 AudioTrack.STATE_INITIALIZED);
 
         assertTrue("testConstructorStereo8MusicStream: " + res.mResultLog, res.mResult);
@@ -220,7 +220,7 @@
         
         TestResults res = constructorTestMultiSampleRate(
                 AudioManager.STREAM_MUSIC, AudioTrack.MODE_STATIC, 
-                    AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT,
+                    AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_8BIT,
                 AudioTrack.STATE_NO_STATIC_DATA);
 
         assertTrue("testConstructorMono8MusicStatic: " + res.mResultLog, res.mResult);
@@ -232,7 +232,7 @@
         
         TestResults res = constructorTestMultiSampleRate(
                 AudioManager.STREAM_MUSIC, AudioTrack.MODE_STATIC, 
-                    AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_8BIT,
+                    AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_8BIT,
                 AudioTrack.STATE_NO_STATIC_DATA);
 
         assertTrue("testConstructorStereo8MusicStatic: " + res.mResultLog, res.mResult);
@@ -248,15 +248,15 @@
     public void testConstructorStreamType() throws Exception {
         // constants for test
         final int TYPE_TEST_SR = 22050;
-        final int TYPE_TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TYPE_TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TYPE_TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TYPE_TEST_MODE = AudioTrack.MODE_STREAM;
         final int[] STREAM_TYPES = { AudioManager.STREAM_ALARM, AudioManager.STREAM_BLUETOOTH_SCO, 
                 AudioManager.STREAM_MUSIC, AudioManager.STREAM_NOTIFICATION,
                 AudioManager.STREAM_RING, AudioManager.STREAM_SYSTEM, 
-                AudioManager.STREAM_VOICE_CALL };
+                AudioManager.STREAM_VOICE_CALL, AudioManager.STREAM_DTMF, };
         final String[] STREAM_NAMES = { "STREAM_ALARM", "STREAM_BLUETOOTH_SCO", "STREAM_MUSIC",
-                "STREAM_NOTIFICATION", "STREAM_RING", "STREAM_SYSTEM", "STREAM_VOICE_CALL" };
+                "STREAM_NOTIFICATION", "STREAM_RING", "STREAM_SYSTEM", "STREAM_VOICE_CALL", "STREAM_DTMF" };
         
         boolean localTestRes = true;
         AudioTrack track = null;
@@ -303,7 +303,7 @@
         // constants for test
         final String TEST_NAME = "testPlaybackHeadPositionAfterInit";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -324,7 +324,7 @@
         // constants for test
         final String TEST_NAME = "testPlaybackHeadPositionIncrease";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -352,7 +352,7 @@
         // constants for test
         final String TEST_NAME = "testPlaybackHeadPositionAfterFlush";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -382,7 +382,7 @@
         // constants for test
         final String TEST_NAME = "testPlaybackHeadPositionAfterStop";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -413,7 +413,7 @@
         // constants for test
         final String TEST_NAME = "testPlaybackHeadPositionAfterPause";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -448,7 +448,7 @@
         // constants for test
         final String TEST_NAME = "testSetStereoVolumeMax";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -474,7 +474,7 @@
         // constants for test
         final String TEST_NAME = "testSetStereoVolumeMin";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -500,7 +500,7 @@
         // constants for test
         final String TEST_NAME = "testSetStereoVolumeMid";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -526,7 +526,7 @@
         // constants for test
         final String TEST_NAME = "testSetPlaybackRate";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -552,7 +552,7 @@
         // constants for test
         final String TEST_NAME = "testSetPlaybackRateZero";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -574,7 +574,7 @@
         // constants for test
         final String TEST_NAME = "testSetPlaybackRateTwiceOutputSR";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -601,7 +601,7 @@
         // constants for test
         final String TEST_NAME = "testSetGetPlaybackRate";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_STEREO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -628,7 +628,7 @@
         // constants for test
         final String TEST_NAME = "testSetPlaybackRateUninit";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STATIC;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -655,7 +655,7 @@
         // constants for test
         final String TEST_NAME = "testSetPlaybackHeadPositionPlaying";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -682,7 +682,7 @@
         // constants for test
         final String TEST_NAME = "testSetPlaybackHeadPositionStopped";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -710,7 +710,7 @@
         // constants for test
         final String TEST_NAME = "testSetPlaybackHeadPositionPaused";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -738,7 +738,7 @@
         // constants for test
         final String TEST_NAME = "testSetPlaybackHeadPositionTooFar";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -770,7 +770,7 @@
         // constants for test
         final String TEST_NAME = "testSetLoopPointsStream";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -794,7 +794,7 @@
         // constants for test
         final String TEST_NAME = "testSetLoopPointsStartAfterEnd";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STATIC;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -818,7 +818,7 @@
         // constants for test
         final String TEST_NAME = "testSetLoopPointsSuccess";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STATIC;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -842,7 +842,7 @@
         // constants for test
         final String TEST_NAME = "testSetLoopPointsLoopTooLong";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STATIC;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -868,7 +868,7 @@
         // constants for test
         final String TEST_NAME = "testSetLoopPointsStartTooFar";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STATIC;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -896,7 +896,7 @@
         // constants for test
         final String TEST_NAME = "testSetLoopPointsEndTooFar";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STATIC;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -929,7 +929,7 @@
         // constants for test
         final String TEST_NAME = "testWriteByteOffsetTooBig";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -953,7 +953,7 @@
         // constants for test
         final String TEST_NAME = "testWriteShortOffsetTooBig";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -977,7 +977,7 @@
         // constants for test
         final String TEST_NAME = "testWriteByteSizeTooBig";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1001,7 +1001,7 @@
         // constants for test
         final String TEST_NAME = "testWriteShortSizeTooBig";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1025,7 +1025,7 @@
         // constants for test
         final String TEST_NAME = "testWriteByteNegativeOffset";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1049,7 +1049,7 @@
         // constants for test
         final String TEST_NAME = "testWriteShortNegativeOffset";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1073,7 +1073,7 @@
         // constants for test
         final String TEST_NAME = "testWriteByteNegativeSize";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1097,7 +1097,7 @@
         // constants for test
         final String TEST_NAME = "testWriteShortNegativeSize";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1121,7 +1121,7 @@
         // constants for test
         final String TEST_NAME = "testWriteByte";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1145,7 +1145,7 @@
         // constants for test
         final String TEST_NAME = "testWriteShort";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1169,7 +1169,7 @@
         // constants for test
         final String TEST_NAME = "testWriteByte8bit";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_8BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1193,7 +1193,7 @@
         // constants for test
         final String TEST_NAME = "testWriteShort8bit";
         final int TEST_SR = 22050;
-        final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_8BIT;
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1221,7 +1221,7 @@
       // constant for test
       final String TEST_NAME = "testGetMinBufferSizeTooLowSR";
       final int TEST_SR = 3999;
-      final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+      final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
       final int TEST_FORMAT = AudioFormat.ENCODING_PCM_8BIT;
       final int TEST_MODE = AudioTrack.MODE_STREAM;
       final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
@@ -1238,7 +1238,7 @@
       // constant for testg
       final String TEST_NAME = "testGetMinBufferSizeTooHighSR";
       final int TEST_SR = 48001;
-      final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+      final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
       final int TEST_FORMAT = AudioFormat.ENCODING_PCM_8BIT;
       final int TEST_MODE = AudioTrack.MODE_STREAM;
       final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerInvokeTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerInvokeTest.java
new file mode 100644
index 0000000..ab8b311
--- /dev/null
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerInvokeTest.java
@@ -0,0 +1,70 @@
+/*
+ * 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.
+ */
+
+package com.android.mediaframeworktest.functional;
+
+import com.android.mediaframeworktest.MediaFrameworkTest;
+import com.android.mediaframeworktest.MediaNames;
+
+import android.test.ActivityInstrumentationTestCase2;
+import android.util.Log;
+import android.test.suitebuilder.annotation.LargeTest;
+import android.test.suitebuilder.annotation.MediumTest;
+import android.test.suitebuilder.annotation.Suppress;
+
+import android.media.MediaPlayer;
+import android.os.Parcel;
+
+import java.util.Calendar;
+import java.util.Random;
+
+// Tests for the invoke method in the MediaPlayer.
+public class MediaPlayerInvokeTest extends ActivityInstrumentationTestCase2<MediaFrameworkTest> {
+   private static final String TAG = "MediaPlayerInvokeTest";
+   private MediaPlayer mPlayer;
+   private Random rnd;
+
+   public MediaPlayerInvokeTest() {
+       super("com.android.mediaframeworktest", MediaFrameworkTest.class);
+       rnd = new Random(Calendar.getInstance().getTimeInMillis());
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+      super.setUp();
+      mPlayer = new MediaPlayer();
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        mPlayer.release();
+        super.tearDown();
+    }
+
+    // Generate a random number, sends it to the ping test player.
+    @MediumTest
+    public void testPing() throws Exception {
+        mPlayer.setDataSource("test:invoke_mock_media_player.so?url=ping");
+
+        Parcel request = mPlayer.newRequest();
+        Parcel reply = Parcel.obtain();
+
+        int val = rnd.nextInt();
+        request.writeInt(val);
+        assertEquals(0, mPlayer.invoke(request, reply));
+        assertEquals(val, reply.readInt());
+   }
+}
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java
index 84058f5..4adb04e 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java
@@ -47,7 +47,7 @@
  */
 public class MediaPlayerPerformance extends ActivityInstrumentationTestCase<MediaFrameworkTest> {
 
-    private String TAG = "MediaFrameworkPerformance";
+    private String TAG = "MediaPlayerPerformance";
 
     private SQLiteDatabase mDB;
     private SurfaceHolder mSurfaceHolder = null;
@@ -76,9 +76,11 @@
 
     public void createDB() {
         mDB = SQLiteDatabase.openOrCreateDatabase("/sdcard/perf.db", null);
-        mDB.execSQL("CREATE TABLE perfdata (_id INTEGER PRIMARY KEY," + 
+        mDB.execSQL("CREATE TABLE IF NOT EXISTS perfdata (_id INTEGER PRIMARY KEY," + 
                 "file TEXT," + "setdatatime LONG," + "preparetime LONG," +
                 "playtime LONG" + ");");
+        //clean the table before adding new data
+        mDB.execSQL("DELETE FROM perfdata");
     }
 
     public void audioPlaybackStartupTime(String[] testFile) {
@@ -137,6 +139,10 @@
         audioPlaybackStartupTime(MediaNames.MP3FILES);
         audioPlaybackStartupTime(MediaNames.AACFILES);
 
+        //close the database after all transactions
+        if (mDB.isOpen()) {
+            mDB.close();
+        }
     }
 
     public void wmametadatautility(String[] testFile) {
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerMetadataParserTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerMetadataParserTest.java
new file mode 100644
index 0000000..38f598a
--- /dev/null
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerMetadataParserTest.java
@@ -0,0 +1,432 @@
+/*
+ * 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.
+ */
+
+package com.android.mediaframeworktest.unit;
+import android.media.Metadata;
+import android.os.Parcel;
+import android.test.AndroidTestCase;
+import android.test.suitebuilder.annotation.SmallTest;
+import android.util.Log;
+
+import java.util.Calendar;
+import java.util.Date;
+
+/*
+ * Check the Java layer that parses serialized metadata in Parcel
+ * works as expected.
+ *
+ */
+
+public class MediaPlayerMetadataParserTest extends AndroidTestCase {
+    private static final String TAG = "MediaPlayerMetadataTest";
+    private static final int kMarker = 0x4d455441;  // 'M' 'E' 'T' 'A'
+    private static final int kHeaderSize = 8;
+
+    private Metadata mMetadata = null;
+    private Parcel mParcel = null;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mMetadata = new Metadata();
+        mParcel = Parcel.obtain();
+
+        resetParcel();
+    }
+
+    // Check parsing of the parcel fails. Make sure the parser rewind
+    // the parcel properly.
+    private void assertParseFail() throws Exception {
+        mParcel.setDataPosition(0);
+        assertFalse(mMetadata.parse(mParcel));
+        assertEquals(0, mParcel.dataPosition());
+    }
+
+    // Check parsing of the parcel is successful.
+    private void assertParse() throws Exception {
+        mParcel.setDataPosition(0);
+        assertTrue(mMetadata.parse(mParcel));
+    }
+
+    // Write the number of bytes from the start of the parcel to the
+    // current position at the beginning of the parcel (offset 0).
+    private void adjustSize() {
+        adjustSize(0);
+    }
+
+    // Write the number of bytes from the offset to the current
+    // position at position pointed by offset.
+    private void adjustSize(int offset) {
+        final int pos = mParcel.dataPosition();
+
+        mParcel.setDataPosition(offset);
+        mParcel.writeInt(pos - offset);
+        mParcel.setDataPosition(pos);
+    }
+
+    // Rewind the parcel and insert the header.
+    private void resetParcel() {
+        mParcel.setDataPosition(0);
+        // Most tests will use a properly formed parcel with a size
+        // and the meta marker so we add them by default.
+        mParcel.writeInt(-1);  // Placeholder for the size
+        mParcel.writeInt(kMarker);
+    }
+
+    // ----------------------------------------------------------------------
+    // START OF THE TESTS
+
+
+    // There should be at least 8 bytes in the parcel, 4 for the size
+    // and 4 for the 'M' 'E' 'T' 'A' marker.
+    @SmallTest
+    public void testMissingSizeAndMarker() throws Exception {
+        for (int i = 0; i < kHeaderSize; ++i) {
+            mParcel.setDataPosition(0);
+            mParcel.setDataSize(i);
+
+            assertEquals(i, mParcel.dataAvail());
+            assertParseFail();
+        }
+    }
+
+    // There should be at least 'size' bytes in the parcel.
+    @SmallTest
+    public void testMissingData() throws Exception {
+        final int size = 20;
+
+        mParcel.writeInt(size);
+        mParcel.setDataSize(size - 1);
+        assertParseFail();
+    }
+
+    // Empty parcel is fine
+    @SmallTest
+    public void testEmptyIsOk() throws Exception {
+        adjustSize();
+        assertParse();
+    }
+
+    // ----------------------------------------------------------------------
+    // RECORDS
+    // ----------------------------------------------------------------------
+
+    // A record header should be at least 12 bytes long
+    @SmallTest
+    public void testRecordMissingId() throws Exception {
+        mParcel.writeInt(13); // record length
+        // misses metadata id and metadata type.
+        adjustSize();
+        assertParseFail();
+    }
+
+    @SmallTest
+    public void testRecordMissingType() throws Exception {
+        mParcel.writeInt(13); // record length lies
+        mParcel.writeInt(Metadata.TITLE);
+        // misses metadata type
+        adjustSize();
+        assertParseFail();
+    }
+
+    @SmallTest
+    public void testRecordWithZeroPayload() throws Exception {
+        mParcel.writeInt(0);
+        adjustSize();
+        assertParseFail();
+    }
+
+    // A record cannot be empty.
+    @SmallTest
+    public void testRecordMissingPayload() throws Exception {
+        mParcel.writeInt(12);
+        mParcel.writeInt(Metadata.TITLE);
+        mParcel.writeInt(Metadata.STRING_VAL);
+        // misses payload
+        adjustSize();
+        assertParseFail();
+    }
+
+    // Check records can be found.
+    @SmallTest
+    public void testRecordsFound() throws Exception {
+        writeStringRecord(Metadata.TITLE, "a title");
+        writeStringRecord(Metadata.GENRE, "comedy");
+        writeStringRecord(Metadata.firstCustomId(), "custom");
+        adjustSize();
+        assertParse();
+        assertTrue(mMetadata.has(Metadata.TITLE));
+        assertTrue(mMetadata.has(Metadata.GENRE));
+        assertTrue(mMetadata.has(Metadata.firstCustomId()));
+        assertFalse(mMetadata.has(Metadata.DRM_CRIPPLED));
+        assertEquals(3, mMetadata.keySet().size());
+    }
+
+    // Detects bad metadata type
+    @SmallTest
+    public void testBadMetadataType() throws Exception {
+        final int start = mParcel.dataPosition();
+        mParcel.writeInt(-1);  // Placeholder for the length
+        mParcel.writeInt(Metadata.TITLE);
+        mParcel.writeInt(0);  // Invalid type.
+        mParcel.writeString("dummy");
+        adjustSize(start);
+
+        adjustSize();
+        assertParseFail();
+    }
+
+    // Check a Metadata instance can be reused, i.e the parse method
+    // wipes out the existing states/keys.
+    @SmallTest
+    public void testParseClearState() throws Exception {
+        writeStringRecord(Metadata.TITLE, "a title");
+        writeStringRecord(Metadata.GENRE, "comedy");
+        writeStringRecord(Metadata.firstCustomId(), "custom");
+        adjustSize();
+        assertParse();
+
+        resetParcel();
+        writeStringRecord(Metadata.MIME_TYPE, "audio/mpg");
+        adjustSize();
+        assertParse();
+
+        // Only the mime type metadata should be present.
+        assertEquals(1, mMetadata.keySet().size());
+        assertTrue(mMetadata.has(Metadata.MIME_TYPE));
+
+        assertFalse(mMetadata.has(Metadata.TITLE));
+        assertFalse(mMetadata.has(Metadata.GENRE));
+        assertFalse(mMetadata.has(Metadata.firstCustomId()));
+    }
+
+    // ----------------------------------------------------------------------
+    // GETTERS
+    // ----------------------------------------------------------------------
+
+    // getString
+    @SmallTest
+    public void testGetString() throws Exception {
+        writeStringRecord(Metadata.TITLE, "a title");
+        writeStringRecord(Metadata.GENRE, "comedy");
+        adjustSize();
+        assertParse();
+
+        assertEquals("a title", mMetadata.getString(Metadata.TITLE));
+        assertEquals("comedy", mMetadata.getString(Metadata.GENRE));
+    }
+
+    // get an empty string.
+    @SmallTest
+    public void testGetEmptyString() throws Exception {
+        writeStringRecord(Metadata.TITLE, "");
+        adjustSize();
+        assertParse();
+
+        assertEquals("", mMetadata.getString(Metadata.TITLE));
+    }
+
+    // get a string when a NULL value was in the parcel
+    @SmallTest
+    public void testGetNullString() throws Exception {
+        writeStringRecord(Metadata.TITLE, null);
+        adjustSize();
+        assertParse();
+
+        assertEquals(null, mMetadata.getString(Metadata.TITLE));
+    }
+
+    // get a string when an integer is actually present
+    @SmallTest
+    public void testWrongType() throws Exception {
+        writeIntRecord(Metadata.DURATION, 5);
+        adjustSize();
+        assertParse();
+
+        try {
+            mMetadata.getString(Metadata.DURATION);
+        } catch (IllegalStateException ise) {
+            return;
+        }
+        fail("Exception was not thrown");
+    }
+
+    // getInt
+    @SmallTest
+    public void testGetInt() throws Exception {
+        writeIntRecord(Metadata.CD_TRACK_NUM, 1);
+        adjustSize();
+        assertParse();
+
+        assertEquals(1, mMetadata.getInt(Metadata.CD_TRACK_NUM));
+    }
+
+    // getBoolean
+    @SmallTest
+    public void testGetBoolean() throws Exception {
+        writeBooleanRecord(Metadata.DRM_CRIPPLED, true);
+        adjustSize();
+        assertParse();
+
+        assertEquals(true, mMetadata.getBoolean(Metadata.DRM_CRIPPLED));
+    }
+
+    // getLong
+    @SmallTest
+    public void testGetLong() throws Exception {
+        writeLongRecord(Metadata.DURATION, 1L);
+        adjustSize();
+        assertParse();
+
+        assertEquals(1L, mMetadata.getLong(Metadata.DURATION));
+    }
+
+    // getDouble
+    @SmallTest
+    public void testGetDouble() throws Exception {
+        writeDoubleRecord(Metadata.VIDEO_FRAME_RATE, 29.97);
+        adjustSize();
+        assertParse();
+
+        assertEquals(29.97, mMetadata.getDouble(Metadata.VIDEO_FRAME_RATE));
+    }
+
+    // getByteArray
+    @SmallTest
+    public void testGetByteArray() throws Exception {
+        byte data[] = new byte[]{1,2,3,4,5};
+
+        writeByteArrayRecord(Metadata.ALBUM_ART, data);
+        adjustSize();
+        assertParse();
+
+        byte res[] = mMetadata.getByteArray(Metadata.ALBUM_ART);
+        for (int i = 0; i < data.length; ++i) {
+            assertEquals(data[i], res[i]);
+        }
+    }
+
+    // getDate
+    @SmallTest
+    public void testGetDate() throws Exception {
+        writeDateRecord(Metadata.DATE, 0, "PST");
+        adjustSize();
+        assertParse();
+
+        assertEquals(new Date(0), mMetadata.getDate(Metadata.DATE));
+    }
+
+    // getTimedText
+    @SmallTest
+    public void testGetTimedText() throws Exception {
+        Date now = Calendar.getInstance().getTime();
+        writeTimedTextRecord(Metadata.CAPTION, now.getTime(),
+                             10, "Some caption");
+        adjustSize();
+        assertParse();
+
+        Metadata.TimedText caption = mMetadata.getTimedText(Metadata.CAPTION);
+        assertEquals("" + now + "-" + 10 + ":Some caption", caption.toString());
+    }
+
+    // ----------------------------------------------------------------------
+    // HELPERS TO APPEND RECORDS
+    // ----------------------------------------------------------------------
+
+    // Insert a string record at the current position.
+    private void writeStringRecord(int metadataId, String val) {
+        final int start = mParcel.dataPosition();
+        mParcel.writeInt(-1);  // Placeholder for the length
+        mParcel.writeInt(metadataId);
+        mParcel.writeInt(Metadata.STRING_VAL);
+        mParcel.writeString(val);
+        adjustSize(start);
+    }
+
+    // Insert an int record at the current position.
+    private void writeIntRecord(int metadataId, int val) {
+        final int start = mParcel.dataPosition();
+        mParcel.writeInt(-1);  // Placeholder for the length
+        mParcel.writeInt(metadataId);
+        mParcel.writeInt(Metadata.INTEGER_VAL);
+        mParcel.writeInt(val);
+        adjustSize(start);
+    }
+
+    // Insert a boolean record at the current position.
+    private void writeBooleanRecord(int metadataId, boolean val) {
+        final int start = mParcel.dataPosition();
+        mParcel.writeInt(-1);  // Placeholder for the length
+        mParcel.writeInt(metadataId);
+        mParcel.writeInt(Metadata.BOOLEAN_VAL);
+        mParcel.writeInt(val ? 1 : 0);
+        adjustSize(start);
+    }
+
+    // Insert a Long record at the current position.
+    private void writeLongRecord(int metadataId, long val) {
+        final int start = mParcel.dataPosition();
+        mParcel.writeInt(-1);  // Placeholder for the length
+        mParcel.writeInt(metadataId);
+        mParcel.writeInt(Metadata.LONG_VAL);
+        mParcel.writeLong(val);
+        adjustSize(start);
+    }
+
+    // Insert a Double record at the current position.
+    private void writeDoubleRecord(int metadataId, double val) {
+        final int start = mParcel.dataPosition();
+        mParcel.writeInt(-1);  // Placeholder for the length
+        mParcel.writeInt(metadataId);
+        mParcel.writeInt(Metadata.DOUBLE_VAL);
+        mParcel.writeDouble(val);
+        adjustSize(start);
+    }
+
+    // Insert a ByteArray record at the current position.
+    private void writeByteArrayRecord(int metadataId, byte[] val) {
+        final int start = mParcel.dataPosition();
+        mParcel.writeInt(-1);  // Placeholder for the length
+        mParcel.writeInt(metadataId);
+        mParcel.writeInt(Metadata.BYTE_ARRAY_VAL);
+        mParcel.writeByteArray(val);
+        adjustSize(start);
+    }
+
+    // Insert a Date record at the current position.
+    private void writeDateRecord(int metadataId, long time, String tz) {
+        final int start = mParcel.dataPosition();
+        mParcel.writeInt(-1);  // Placeholder for the length
+        mParcel.writeInt(metadataId);
+        mParcel.writeInt(Metadata.DATE_VAL);
+        mParcel.writeLong(time);
+        mParcel.writeString(tz);
+        adjustSize(start);
+    }
+
+    // Insert a TimedText record at the current position.
+    private void writeTimedTextRecord(int metadataId, long begin,
+                                      int duration, String text) {
+        final int start = mParcel.dataPosition();
+        mParcel.writeInt(-1);  // Placeholder for the length
+        mParcel.writeInt(metadataId);
+        mParcel.writeInt(Metadata.TIMED_TEXT_VAL);
+        mParcel.writeLong(begin);
+        mParcel.writeInt(duration);
+        mParcel.writeString(text);
+        adjustSize(start);
+    }
+}
diff --git a/media/tests/players/Android.mk b/media/tests/players/Android.mk
new file mode 100644
index 0000000..eb50a51
--- /dev/null
+++ b/media/tests/players/Android.mk
@@ -0,0 +1,29 @@
+# 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= invoke_mock_media_player.cpp
+
+LOCAL_SHARED_LIBRARIES:= \
+    libbinder \
+    libutils
+
+LOCAL_MODULE:= invoke_mock_media_player
+LOCAL_MODULE_TAGS := test eng
+LOCAL_PRELINK_MODULE:= false
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/media/tests/players/README b/media/tests/players/README
new file mode 100644
index 0000000..edf9bd6
--- /dev/null
+++ b/media/tests/players/README
@@ -0,0 +1,8 @@
+Native test players for system tests.
+
+For functional/system/performance tests, a native test player can be used.
+This directory contains the sources of such players.
+The class TestPlayerStub uses the dynamic loader to load any of them.
+
+
+
diff --git a/media/tests/players/invoke_mock_media_player.cpp b/media/tests/players/invoke_mock_media_player.cpp
new file mode 100644
index 0000000..77bb5b2
--- /dev/null
+++ b/media/tests/players/invoke_mock_media_player.cpp
@@ -0,0 +1,121 @@
+/*
+ * 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_NDEBUG 0
+#define LOG_TAG "TestPlayerStub"
+#include "utils/Log.h"
+
+#include <string.h>
+
+#include <binder/Parcel.h>
+#include <media/MediaPlayerInterface.h>
+#include <utils/Errors.h>
+
+using android::INVALID_OPERATION;
+using android::ISurface;
+using android::MediaPlayerBase;
+using android::OK;
+using android::Parcel;
+using android::SortedVector;
+using android::TEST_PLAYER;
+using android::UNKNOWN_ERROR;
+using android::player_type;
+using android::sp;
+using android::status_t;
+
+// This file contains a test player that is loaded via the
+// TestPlayerStub class.  The player contains various implementation
+// of the invoke method that java tests can use.
+
+namespace {
+const char *kPing = "ping";
+
+class Player: public MediaPlayerBase
+{
+  public:
+    enum TestType {TEST_UNKNOWN, PING};
+    Player() {}
+    virtual ~Player() {}
+
+    virtual status_t    initCheck() {return OK;}
+    virtual bool        hardwareOutput() {return true;}
+
+    virtual status_t    setDataSource(const char *url) {
+        LOGV("setDataSource %s", url);
+        mTest = TEST_UNKNOWN;
+        if (strncmp(url, kPing, strlen(kPing)) == 0) {
+            mTest = PING;
+        }
+        return OK;
+    }
+
+    virtual status_t    setDataSource(int fd, int64_t offset, int64_t length) {return OK;}
+    virtual status_t    setVideoSurface(const sp<ISurface>& surface) {return OK;}
+    virtual status_t    prepare() {return OK;}
+    virtual status_t    prepareAsync() {return OK;}
+    virtual status_t    start() {return OK;}
+    virtual status_t    stop() {return OK;}
+    virtual status_t    pause() {return OK;}
+    virtual bool        isPlaying() {return true;}
+    virtual status_t    seekTo(int msec) {return OK;}
+    virtual status_t    getCurrentPosition(int *msec) {return OK;}
+    virtual status_t    getDuration(int *msec) {return OK;}
+    virtual status_t    reset() {return OK;}
+    virtual status_t    setLooping(int loop) {return OK;}
+    virtual player_type playerType() {return TEST_PLAYER;}
+    virtual status_t    invoke(const Parcel& request, Parcel *reply);
+
+  private:
+    // Take a request, copy it to the reply.
+    void ping(const Parcel& request, Parcel *reply);
+
+    status_t mStatus;
+    TestType mTest;
+};
+
+status_t Player::invoke(const Parcel& request, Parcel *reply)
+{
+    switch (mTest) {
+        case PING:
+            ping(request, reply);
+            break;
+        default: mStatus = UNKNOWN_ERROR;
+    }
+    return mStatus;
+}
+
+void Player::ping(const Parcel& request, Parcel *reply)
+{
+    const size_t len = request.dataAvail();
+
+    reply->setData(static_cast<const uint8_t*>(request.readInplace(len)), len);
+    mStatus = OK;
+}
+
+}
+
+extern "C" android::MediaPlayerBase* newPlayer()
+{
+    LOGD("New invoke test player");
+    return new Player();
+}
+
+extern "C" android::status_t deletePlayer(android::MediaPlayerBase *player)
+{
+    LOGD("Delete invoke test player");
+    delete player;
+    return OK;
+}
diff --git a/obex/Android.mk b/obex/Android.mk
new file mode 100644
index 0000000..fbfe9be
--- /dev/null
+++ b/obex/Android.mk
@@ -0,0 +1,9 @@
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_MODULE:= javax.obex
+
+include $(BUILD_JAVA_LIBRARY)
diff --git a/obex/javax/obex/ApplicationParameter.java b/obex/javax/obex/ApplicationParameter.java
new file mode 100644
index 0000000..a62210f
--- /dev/null
+++ b/obex/javax/obex/ApplicationParameter.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+/**
+ * @hide
+ */
+public final class ApplicationParameter {
+
+    private byte[] mArray;
+
+    private int mLength;
+
+    private int mMaxLength = 1000;
+
+    public static class TRIPLET_TAGID {
+        public static final byte ORDER_TAGID = 0x01;
+
+        public static final byte SEARCH_VALUE_TAGID = 0x02;
+
+        public static final byte SEARCH_ATTRIBUTE_TAGID = 0x03;
+
+        // if equals to "0", PSE only reply number of contacts
+        public static final byte MAXLISTCOUNT_TAGID = 0x04;
+
+        public static final byte LISTSTARTOFFSET_TAGID = 0x05;
+
+        public static final byte FILTER_TAGID = 0x06;
+
+        public static final byte FORMAT_TAGID = 0x07;
+
+        // only used if max list count = 0
+        public static final byte PHONEBOOKSIZE_TAGID = 0x08;
+
+        // only used in "mch" in response
+        public static final byte NEWMISSEDCALLS_TAGID = 0x09;
+    }
+
+    public static class TRIPLET_VALUE {
+        public static class ORDER {
+            public static final byte ORDER_BY_INDEX = 0x00;
+
+            public static final byte ORDER_BY_ALPHANUMERIC = 0x01;
+
+            public static final byte ORDER_BY_PHONETIC = 0x02;
+        }
+
+        public static class SEARCHATTRIBUTE {
+            public static final byte SEARCH_BY_NAME = 0x00;
+
+            public static final byte SEARCH_BY_NUMBER = 0x01;
+
+            public static final byte SEARCH_BY_SOUND = 0x02;
+        }
+
+        public static class FORMAT {
+            public static final byte VCARD_VERSION_21 = 0x00;
+
+            public static final byte VCARD_VERSION_30 = 0x01;
+        }
+    }
+
+    public static class TRIPLET_LENGTH {
+        public static final byte ORDER_LENGTH = 1;
+
+        public static final byte SEARCH_ATTRIBUTE_LENGTH = 1;
+
+        public static final byte MAXLISTCOUNT_LENGTH = 2;
+
+        public static final byte LISTSTARTOFFSET_LENGTH = 2;
+
+        public static final byte FILTER_LENGTH = 8;
+
+        public static final byte FORMAT_LENGTH = 1;
+
+        public static final byte PHONEBOOKSIZE_LENGTH = 2;
+
+        public static final byte NEWMISSEDCALLS_LENGTH = 1;
+    }
+
+    public ApplicationParameter() {
+        mArray = new byte[mMaxLength];
+        mLength = 0;
+    }
+
+    public void addAPPHeader(byte tag, byte len, byte[] value) {
+        if ((mLength + len + 2) > mMaxLength) {
+            byte[] array_tmp = new byte[mLength + 4 * len];
+            System.arraycopy(mArray, 0, array_tmp, 0, mLength);
+            mArray = array_tmp;
+            mMaxLength = mLength + 4 * len;
+        }
+        mArray[mLength++] = tag;
+        mArray[mLength++] = len;
+        System.arraycopy(value, 0, mArray, mLength, len);
+        mLength += len;
+    }
+
+    public byte[] getAPPparam() {
+        byte[] para = new byte[mLength];
+        System.arraycopy(mArray, 0, para, 0, mLength);
+        return para;
+    }
+}
diff --git a/obex/javax/obex/Authenticator.java b/obex/javax/obex/Authenticator.java
new file mode 100644
index 0000000..ec226fb
--- /dev/null
+++ b/obex/javax/obex/Authenticator.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+/**
+ * This interface provides a way to respond to authentication challenge and
+ * authentication response headers. When a client or server receives an
+ * authentication challenge or authentication response header, the
+ * <code>onAuthenticationChallenge()</code> or
+ * <code>onAuthenticationResponse()</code> will be called, respectively, by the
+ * implementation.
+ * <P>
+ * For more information on how the authentication procedure works in OBEX,
+ * please review the IrOBEX specification at <A
+ * HREF="http://www.irda.org">http://www.irda.org</A>.
+ * <P>
+ * <STRONG>Authentication Challenges</STRONG>
+ * <P>
+ * When a client or server receives an authentication challenge header, the
+ * <code>onAuthenticationChallenge()</code> method will be invoked by the OBEX
+ * API implementation. The application will then return the user name (if
+ * needed) and password via a <code>PasswordAuthentication</code> object. The
+ * password in this object is not sent in the authentication response. Instead,
+ * the 16-byte challenge received in the authentication challenge is combined
+ * with the password returned from the <code>onAuthenticationChallenge()</code>
+ * method and passed through the MD5 hash algorithm. The resulting value is sent
+ * in the authentication response along with the user name if it was provided.
+ * <P>
+ * <STRONG>Authentication Responses</STRONG>
+ * <P>
+ * When a client or server receives an authentication response header, the
+ * <code>onAuthenticationResponse()</code> method is invoked by the API
+ * implementation with the user name received in the authentication response
+ * header. (The user name will be <code>null</code> if no user name was provided
+ * in the authentication response header.) The application must determine the
+ * correct password. This value should be returned from the
+ * <code>onAuthenticationResponse()</code> method. If the authentication request
+ * should fail without the implementation checking the password,
+ * <code>null</code> should be returned by the application. (This is needed for
+ * reasons like not recognizing the user name, etc.) If the returned value is
+ * not <code>null</code>, the OBEX API implementation will combine the password
+ * returned from the <code>onAuthenticationResponse()</code> method and
+ * challenge sent via the authentication challenge, apply the MD5 hash
+ * algorithm, and compare the result to the response hash received in the
+ * authentication response header. If the values are not equal, an
+ * <code>IOException</code> will be thrown if the client requested
+ * authentication. If the server requested authentication, the
+ * <code>onAuthenticationFailure()</code> method will be called on the
+ * <code>ServerRequestHandler</code> that failed authentication. The connection
+ * is <B>not</B> closed if authentication failed.
+ * @hide
+ */
+public interface Authenticator {
+
+    /**
+     * Called when a client or a server receives an authentication challenge
+     * header. It should respond to the challenge with a
+     * <code>PasswordAuthentication</code> that contains the correct user name
+     * and password for the challenge.
+     * @param description the description of which user name and password should
+     *        be used; if no description is provided in the authentication
+     *        challenge or the description is encoded in an encoding scheme that
+     *        is not supported, an empty string will be provided
+     * @param isUserIdRequired <code>true</code> if the user ID is required;
+     *        <code>false</code> if the user ID is not required
+     * @param isFullAccess <code>true</code> if full access to the server will
+     *        be granted; <code>false</code> if read only access will be granted
+     * @return a <code>PasswordAuthentication</code> object containing the user
+     *         name and password used for authentication
+     */
+    PasswordAuthentication onAuthenticationChallenge(String description, boolean isUserIdRequired,
+            boolean isFullAccess);
+
+    /**
+     * Called when a client or server receives an authentication response
+     * header. This method will provide the user name and expect the correct
+     * password to be returned.
+     * @param userName the user name provided in the authentication response; may
+     *        be <code>null</code>
+     * @return the correct password for the user name provided; if
+     *         <code>null</code> is returned then the authentication request
+     *         failed
+     */
+    byte[] onAuthenticationResponse(byte[] userName);
+}
diff --git a/obex/javax/obex/BaseStream.java b/obex/javax/obex/BaseStream.java
new file mode 100644
index 0000000..022ad4f
--- /dev/null
+++ b/obex/javax/obex/BaseStream.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.IOException;
+
+/**
+ * This interface defines the methods needed by a parent that uses the
+ * PrivateInputStream and PrivateOutputStream objects defined in this package.
+ * @hide
+ */
+public interface BaseStream {
+
+    /**
+     * Verifies that this object is still open.
+     * @throws IOException if the object is closed
+     */
+    void ensureOpen() throws IOException;
+
+    /**
+     * Verifies that additional information may be sent. In other words, the
+     * operation is not done.
+     * @throws IOException if the operation is completed
+     */
+    void ensureNotDone() throws IOException;
+
+    /**
+     * Continues the operation since there is no data to read.
+     * @param sendEmpty <code>true</code> if the operation should send an empty
+     *        packet or not send anything if there is no data to send
+     * @param inStream <code>true</code> if the stream is input stream or is
+     *        output stream
+     * @return <code>true</code> if the operation was completed;
+     *         <code>false</code> if no operation took place
+     * @throws IOException if an IO error occurs
+     */
+    boolean continueOperation(boolean sendEmpty, boolean inStream) throws IOException;
+
+    /**
+     * Called when the output or input stream is closed.
+     * @param inStream <code>true</code> if the input stream is closed;
+     *        <code>false</code> if the output stream is closed
+     * @throws IOException if an IO error occurs
+     */
+    void streamClosed(boolean inStream) throws IOException;
+}
diff --git a/obex/javax/obex/ClientOperation.java b/obex/javax/obex/ClientOperation.java
new file mode 100644
index 0000000..65663b1
--- /dev/null
+++ b/obex/javax/obex/ClientOperation.java
@@ -0,0 +1,720 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.ByteArrayOutputStream;
+
+/**
+ * This class implements the <code>Operation</code> interface. It will read and
+ * write data via puts and gets.
+ * @hide
+ */
+public final class ClientOperation implements Operation, BaseStream {
+
+    private ClientSession mParent;
+
+    private boolean mInputOpen;
+
+    private PrivateInputStream mPrivateInput;
+
+    private boolean mPrivateInputOpen;
+
+    private PrivateOutputStream mPrivateOutput;
+
+    private boolean mPrivateOutputOpen;
+
+    private String mExceptionMessage;
+
+    private int mMaxPacketSize;
+
+    private boolean mOperationDone;
+
+    private boolean mGetOperation;
+
+    private HeaderSet mRequestHeader;
+
+    private HeaderSet mReplyHeader;
+
+    private boolean mEndOfBodySent;
+
+    /**
+     * Creates new OperationImpl to read and write data to a server
+     * @param maxSize the maximum packet size
+     * @param p the parent to this object
+     * @param type <code>true</code> if this is a get request;
+     *        <code>false</code. if this is a put request
+     * @param header the header to set in the initial request
+     * @throws IOException if the an IO error occurred
+     */
+    public ClientOperation(int maxSize, ClientSession p, HeaderSet header, boolean type)
+            throws IOException {
+
+        mParent = p;
+        mEndOfBodySent = false;
+        mInputOpen = true;
+        mOperationDone = false;
+        mMaxPacketSize = maxSize;
+        mGetOperation = type;
+
+        mPrivateInputOpen = false;
+        mPrivateOutputOpen = false;
+        mPrivateInput = null;
+        mPrivateOutput = null;
+
+        mReplyHeader = new HeaderSet();
+
+        mRequestHeader = new HeaderSet();
+
+        int[] headerList = header.getHeaderList();
+
+        if (headerList != null) {
+
+            for (int i = 0; i < headerList.length; i++) {
+                mRequestHeader.setHeader(headerList[i], header.getHeader(headerList[i]));
+            }
+        }
+
+        if ((header).mAuthChall != null) {
+            mRequestHeader.mAuthChall = new byte[(header).mAuthChall.length];
+            System.arraycopy((header).mAuthChall, 0, mRequestHeader.mAuthChall, 0,
+                    (header).mAuthChall.length);
+        }
+
+        if ((header).mAuthResp != null) {
+            mRequestHeader.mAuthResp = new byte[(header).mAuthResp.length];
+            System.arraycopy((header).mAuthResp, 0, mRequestHeader.mAuthResp, 0,
+                    (header).mAuthResp.length);
+
+        }
+    }
+
+    /**
+     * Sends an ABORT message to the server. By calling this method, the
+     * corresponding input and output streams will be closed along with this
+     * object.
+     * @throws IOException if the transaction has already ended or if an OBEX
+     *         server called this method
+     */
+    public synchronized void abort() throws IOException {
+        ensureOpen();
+        //no compatible with sun-ri
+        if ((mOperationDone) && (mReplyHeader.responseCode != ResponseCodes.OBEX_HTTP_CONTINUE)) {
+            throw new IOException("Operation has already ended");
+        }
+
+        mExceptionMessage = "Operation aborted";
+        if ((!mOperationDone) && (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE)) {
+            mOperationDone = true;
+            /*
+             * Since we are not sending any headers or returning any headers then
+             * we just need to write and read the same bytes
+             */
+            mParent.sendRequest(ObexHelper.OBEX_OPCODE_ABORT, null, mReplyHeader, null);
+
+            if (mReplyHeader.responseCode != ResponseCodes.OBEX_HTTP_OK) {
+                throw new IOException("Invalid response code from server");
+            }
+
+            mExceptionMessage = null;
+        }
+
+        close();
+    }
+
+    /**
+     * Retrieves the response code retrieved from the server. Response codes are
+     * defined in the <code>ResponseCodes</code> interface.
+     * @return the response code retrieved from the server
+     * @throws IOException if an error occurred in the transport layer during
+     *         the transaction; if this method is called on a
+     *         <code>HeaderSet</code> object created by calling
+     *         <code>createHeaderSet</code> in a <code>ClientSession</code>
+     *         object
+     */
+    public synchronized int getResponseCode() throws IOException {
+        //avoid dup validateConnection
+        if ((mReplyHeader.responseCode == -1)
+                || (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE)) {
+            validateConnection();
+        }
+
+        return mReplyHeader.responseCode;
+    }
+
+    /**
+     * This method will always return <code>null</code>
+     * @return <code>null</code>
+     */
+    public String getEncoding() {
+        return null;
+    }
+
+    /**
+     * Returns the type of content that the resource connected to is providing.
+     * E.g. if the connection is via HTTP, then the value of the content-type
+     * header field is returned.
+     * @return the content type of the resource that the URL references, or
+     *         <code>null</code> if not known
+     */
+    public String getType() {
+        try {
+            return (String)mReplyHeader.getHeader(HeaderSet.TYPE);
+        } catch (IOException e) {
+            return null;
+        }
+    }
+
+    /**
+     * Returns the length of the content which is being provided. E.g. if the
+     * connection is via HTTP, then the value of the content-length header field
+     * is returned.
+     * @return the content length of the resource that this connection's URL
+     *         references, or -1 if the content length is not known
+     */
+    public long getLength() {
+        try {
+            Long temp = (Long)mReplyHeader.getHeader(HeaderSet.LENGTH);
+
+            if (temp == null) {
+                return -1;
+            } else {
+                return temp.longValue();
+            }
+        } catch (IOException e) {
+            return -1;
+        }
+    }
+
+    /**
+     * Open and return an input stream for a connection.
+     * @return an input stream
+     * @throws IOException if an I/O error occurs
+     */
+    public InputStream openInputStream() throws IOException {
+
+        ensureOpen();
+
+        if (mPrivateInputOpen)
+            throw new IOException("no more input streams available");
+        if (mGetOperation) {
+            // send the GET request here
+            validateConnection();
+        } else {
+            if (mPrivateInput == null) {
+                mPrivateInput = new PrivateInputStream(this);
+            }
+        }
+
+        mPrivateInputOpen = true;
+
+        return mPrivateInput;
+    }
+
+    /**
+     * Open and return a data input stream for a connection.
+     * @return an input stream
+     * @throws IOException if an I/O error occurs
+     */
+    public DataInputStream openDataInputStream() throws IOException {
+        return new DataInputStream(openInputStream());
+    }
+
+    /**
+     * Open and return an output stream for a connection.
+     * @return an output stream
+     * @throws IOException if an I/O error occurs
+     */
+    public OutputStream openOutputStream() throws IOException {
+
+        ensureOpen();
+        ensureNotDone();
+
+        if (mPrivateOutputOpen)
+            throw new IOException("no more output streams available");
+
+        if (mPrivateOutput == null) {
+            // there are 3 bytes operation headers and 3 bytes body headers //
+            mPrivateOutput = new PrivateOutputStream(this, mMaxPacketSize - 6);
+        }
+
+        mPrivateOutputOpen = true;
+
+        return mPrivateOutput;
+    }
+
+    public int getMaxPacketSize() {
+        return mMaxPacketSize - 6;
+    }
+
+    /**
+     * Open and return a data output stream for a connection.
+     * @return an output stream
+     * @throws IOException if an I/O error occurs
+     */
+    public DataOutputStream openDataOutputStream() throws IOException {
+        return new DataOutputStream(openOutputStream());
+    }
+
+    /**
+     * Closes the connection and ends the transaction
+     * @throws IOException if the operation has already ended or is closed
+     */
+    public void close() throws IOException {
+        mInputOpen = false;
+        mPrivateInputOpen = false;
+        mPrivateOutputOpen = false;
+        mParent.setRequestInactive();
+    }
+
+    /**
+     * Returns the headers that have been received during the operation.
+     * Modifying the object returned has no effect on the headers that are sent
+     * or retrieved.
+     * @return the headers received during this <code>Operation</code>
+     * @throws IOException if this <code>Operation</code> has been closed
+     */
+    public HeaderSet getReceivedHeader() throws IOException {
+        ensureOpen();
+
+        return mReplyHeader;
+    }
+
+    /**
+     * Specifies the headers that should be sent in the next OBEX message that
+     * is sent.
+     * @param headers the headers to send in the next message
+     * @throws IOException if this <code>Operation</code> has been closed or the
+     *         transaction has ended and no further messages will be exchanged
+     * @throws IllegalArgumentException if <code>headers</code> was not created
+     *         by a call to <code>ServerRequestHandler.createHeaderSet()</code>
+     * @throws NullPointerException if <code>headers</code> is <code>null</code>
+     */
+    public void sendHeaders(HeaderSet headers) throws IOException {
+        ensureOpen();
+        if (mOperationDone) {
+            throw new IOException("Operation has already exchanged all data");
+        }
+
+        if (headers == null) {
+            throw new IOException("Headers may not be null");
+        }
+
+        int[] headerList = headers.getHeaderList();
+        if (headerList != null) {
+            for (int i = 0; i < headerList.length; i++) {
+                mRequestHeader.setHeader(headerList[i], headers.getHeader(headerList[i]));
+            }
+        }
+    }
+
+    /**
+     * Verifies that additional information may be sent. In other words, the
+     * operation is not done.
+     * @throws IOException if the operation is completed
+     */
+    public void ensureNotDone() throws IOException {
+        if (mOperationDone) {
+            throw new IOException("Operation has completed");
+        }
+    }
+
+    /**
+     * Verifies that the connection is open and no exceptions should be thrown.
+     * @throws IOException if an exception needs to be thrown
+     */
+    public void ensureOpen() throws IOException {
+        mParent.ensureOpen();
+
+        if (mExceptionMessage != null) {
+            throw new IOException(mExceptionMessage);
+        }
+        if (!mInputOpen) {
+            throw new IOException("Operation has already ended");
+        }
+    }
+
+    /**
+     * Verifies that the connection is open and the proper data has been read.
+     * @throws IOException if an IO error occurs
+     */
+    private void validateConnection() throws IOException {
+        ensureOpen();
+
+        // to sure only one privateInput object exist.
+        if (mPrivateInput == null) {
+            startProcessing();
+        }
+    }
+
+    /**
+     * Sends a request to the client of the specified type
+     * @param opCode the request code to send to the client
+     * @return <code>true</code> if there is more data to send;
+     *         <code>false</code> if there is no more data to send
+     * @throws IOException if an IO error occurs
+     */
+    private boolean sendRequest(int opCode) throws IOException {
+        boolean returnValue = false;
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        int bodyLength = -1;
+        byte[] headerArray = ObexHelper.createHeader(mRequestHeader, true);
+        if (mPrivateOutput != null) {
+            bodyLength = mPrivateOutput.size();
+        }
+
+        /*
+         * Determine if there is space to add a body request.  At present
+         * this method checks to see if there is room for at least a 17
+         * byte body header.  This number needs to be at least 6 so that
+         * there is room for the header ID and length and the reply ID and
+         * length, but it is a waste of resources if we can't send much of
+         * the body.
+         */
+        if ((ObexHelper.BASE_PACKET_LENGTH + headerArray.length) > mMaxPacketSize) {
+            int end = 0;
+            int start = 0;
+            // split & send the headerArray in multiple packets.
+
+            while (end != headerArray.length) {
+                //split the headerArray
+                end = ObexHelper.findHeaderEnd(headerArray, start, mMaxPacketSize
+                        - ObexHelper.BASE_PACKET_LENGTH);
+                // can not split 
+                if (end == -1) {
+                    mOperationDone = true;
+                    abort();
+                    mExceptionMessage = "Header larger then can be sent in a packet";
+                    mInputOpen = false;
+
+                    if (mPrivateInput != null) {
+                        mPrivateInput.close();
+                    }
+
+                    if (mPrivateOutput != null) {
+                        mPrivateOutput.close();
+                    }
+                    throw new IOException("OBEX Packet exceeds max packet size");
+                }
+
+                byte[] sendHeader = new byte[end - start];
+                System.arraycopy(headerArray, start, sendHeader, 0, sendHeader.length);
+                if (!mParent.sendRequest(opCode, sendHeader, mReplyHeader, mPrivateInput)) {
+                    return false;
+                }
+
+                if (mReplyHeader.responseCode != ResponseCodes.OBEX_HTTP_CONTINUE) {
+                    return false;
+                }
+
+                start = end;
+            }
+
+            if (bodyLength > 0) {
+                return true;
+            } else {
+                return false;
+            }
+        } else {
+            out.write(headerArray);
+        }
+
+        if (bodyLength > 0) {
+            /*
+             * Determine if we can send the whole body or just part of
+             * the body.  Remember that there is the 3 bytes for the
+             * response message and 3 bytes for the header ID and length
+             */
+            if (bodyLength > (mMaxPacketSize - headerArray.length - 6)) {
+                returnValue = true;
+
+                bodyLength = mMaxPacketSize - headerArray.length - 6;
+            }
+
+            byte[] body = mPrivateOutput.readBytes(bodyLength);
+
+            /*
+             * Since this is a put request if the final bit is set or
+             * the output stream is closed we need to send the 0x49
+             * (End of Body) otherwise, we need to send 0x48 (Body)
+             */
+            if ((mPrivateOutput.isClosed()) && (!returnValue) && (!mEndOfBodySent)
+                    && ((opCode & 0x80) != 0)) {
+                out.write(0x49);
+                mEndOfBodySent = true;
+            } else {
+                out.write(0x48);
+            }
+
+            bodyLength += 3;
+            out.write((byte)(bodyLength >> 8));
+            out.write((byte)bodyLength);
+
+            if (body != null) {
+                out.write(body);
+            }
+        }
+
+        if (mPrivateOutputOpen && bodyLength <= 0 && !mEndOfBodySent) {
+            // only 0x82 or 0x83 can send 0x49
+            if ((opCode & 0x80) == 0) {
+                out.write(0x48);
+            } else {
+                out.write(0x49);
+                mEndOfBodySent = true;
+
+            }
+
+            bodyLength = 3;
+            out.write((byte)(bodyLength >> 8));
+            out.write((byte)bodyLength);
+        }
+
+        if (out.size() == 0) {
+            if (!mParent.sendRequest(opCode, null, mReplyHeader, mPrivateInput)) {
+                return false;
+            }
+            return returnValue;
+        }
+        if ((out.size() > 0)
+                && (!mParent.sendRequest(opCode, out.toByteArray(), mReplyHeader, mPrivateInput))) {
+            return false;
+        }
+
+        // send all of the output data in 0x48, 
+        // send 0x49 with empty body
+        if ((mPrivateOutput != null) && (mPrivateOutput.size() > 0))
+            returnValue = true;
+
+        return returnValue;
+    }
+
+    /**
+     * This method starts the processing thread results. It will send the
+     * initial request. If the response takes more then one packet, a thread
+     * will be started to handle additional requests
+     * @throws IOException if an IO error occurs
+     */
+    private synchronized void startProcessing() throws IOException {
+
+        if (mPrivateInput == null) {
+            mPrivateInput = new PrivateInputStream(this);
+        }
+        boolean more = true;
+
+        if (mGetOperation) {
+            if (!mOperationDone) {
+                mReplyHeader.responseCode = ResponseCodes.OBEX_HTTP_CONTINUE;
+                while ((more) && (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE)) {
+                    more = sendRequest(0x03);
+                }
+
+                if (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE) {
+                    mParent.sendRequest(0x83, null, mReplyHeader, mPrivateInput);
+                }
+                if (mReplyHeader.responseCode != ResponseCodes.OBEX_HTTP_CONTINUE) {
+                    mOperationDone = true;
+                }
+            }
+        } else {
+
+            if (!mOperationDone) {
+                mReplyHeader.responseCode = ResponseCodes.OBEX_HTTP_CONTINUE;
+                while ((more) && (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE)) {
+                    more = sendRequest(0x02);
+
+                }
+            }
+
+            if (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE) {
+                mParent.sendRequest(0x82, null, mReplyHeader, mPrivateInput);
+            }
+
+            if (mReplyHeader.responseCode != ResponseCodes.OBEX_HTTP_CONTINUE) {
+                mOperationDone = true;
+            }
+        }
+    }
+
+    /**
+     * Continues the operation since there is no data to read.
+     * @param sendEmpty <code>true</code> if the operation should send an empty
+     *        packet or not send anything if there is no data to send
+     * @param inStream <code>true</code> if the stream is input stream or is
+     *        output stream
+     * @throws IOException if an IO error occurs
+     */
+    public synchronized boolean continueOperation(boolean sendEmpty, boolean inStream)
+            throws IOException {
+
+        if (mGetOperation) {
+            if ((inStream) && (!mOperationDone)) {
+                // to deal with inputstream in get operation
+                mParent.sendRequest(0x83, null, mReplyHeader, mPrivateInput);
+                /*
+                  * Determine if that was not the last packet in the operation
+                  */
+                if (mReplyHeader.responseCode != ResponseCodes.OBEX_HTTP_CONTINUE) {
+                    mOperationDone = true;
+                }
+
+                return true;
+
+            } else if ((!inStream) && (!mOperationDone)) {
+                // to deal with outputstream in get operation
+
+                if (mPrivateInput == null) {
+                    mPrivateInput = new PrivateInputStream(this);
+                }
+                sendRequest(0x03);
+                return true;
+
+            } else if (mOperationDone) {
+                return false;
+            }
+
+        } else {
+            if ((!inStream) && (!mOperationDone)) {
+                // to deal with outputstream in put operation
+                if (mReplyHeader.responseCode == -1) {
+                    mReplyHeader.responseCode = ResponseCodes.OBEX_HTTP_CONTINUE;
+                }
+                sendRequest(0x02);
+                return true;
+            } else if ((inStream) && (!mOperationDone)) {
+                // How to deal with inputstream  in put operation ?
+                return false;
+
+            } else if (mOperationDone) {
+                return false;
+            }
+
+        }
+        return false;
+    }
+
+    /**
+     * Called when the output or input stream is closed.
+     * @param inStream <code>true</code> if the input stream is closed;
+     *        <code>false</code> if the output stream is closed
+     * @throws IOException if an IO error occurs
+     */
+    public void streamClosed(boolean inStream) throws IOException {
+        if (!mGetOperation) {
+            if ((!inStream) && (!mOperationDone)) {
+                // to deal with outputstream in put operation
+
+                boolean more = true;
+
+                if ((mPrivateOutput != null) && (mPrivateOutput.size() <= 0)) {
+                    byte[] headerArray = ObexHelper.createHeader(mRequestHeader, false);
+                    if (headerArray.length <= 0)
+                        more = false;
+                }
+                // If have not sent any data so send  all now
+                if (mReplyHeader.responseCode == -1) {
+                    mReplyHeader.responseCode = ResponseCodes.OBEX_HTTP_CONTINUE;
+                }
+
+                while ((more) && (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE)) {
+                    more = sendRequest(0x02);
+                }
+
+                /*
+                 * According to the IrOBEX specification, after the final put, you
+                 * only have a single reply to send.  so we don't need the while
+                 * loop.
+                 */
+                while (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE) {
+
+                    sendRequest(0x82);
+                }
+                mOperationDone = true;
+            } else if ((inStream) && (mOperationDone)) {
+                // how to deal with input stream in put stream ?
+                mOperationDone = true;
+            }
+        } else {
+            if ((inStream) && (!mOperationDone)) {
+
+                // to deal with inputstream in get operation
+                // Have not sent any data so send it all now
+
+                if (mReplyHeader.responseCode == -1) {
+                    mReplyHeader.responseCode = ResponseCodes.OBEX_HTTP_CONTINUE;
+                }
+
+                while (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE) {
+                    if (!sendRequest(0x83)) {
+                        break;
+                    }
+                }
+                while (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE) {
+                    mParent.sendRequest(0x83, null, mReplyHeader, mPrivateInput);
+                }
+                mOperationDone = true;
+            } else if ((!inStream) && (!mOperationDone)) {
+                // to deal with outputstream in get operation
+                // part of the data may have been sent in continueOperation.
+
+                boolean more = true;
+
+                if ((mPrivateOutput != null) && (mPrivateOutput.size() <= 0)) {
+                    byte[] headerArray = ObexHelper.createHeader(mRequestHeader, false);
+                    if (headerArray.length <= 0)
+                        more = false;
+                }
+
+                if (mPrivateInput == null) {
+                    mPrivateInput = new PrivateInputStream(this);
+                }
+                if ((mPrivateOutput != null) && (mPrivateOutput.size() <= 0))
+                    more = false;
+
+                mReplyHeader.responseCode = ResponseCodes.OBEX_HTTP_CONTINUE;
+                while ((more) && (mReplyHeader.responseCode == ResponseCodes.OBEX_HTTP_CONTINUE)) {
+                    more = sendRequest(0x03);
+                }
+                sendRequest(0x83);
+                //                parent.sendRequest(0x83, null, replyHeaders, privateInput);
+                if (mReplyHeader.responseCode != ResponseCodes.OBEX_HTTP_CONTINUE) {
+                    mOperationDone = true;
+                }
+            }
+        }
+    }
+}
diff --git a/obex/javax/obex/ClientSession.java b/obex/javax/obex/ClientSession.java
new file mode 100644
index 0000000..0935383
--- /dev/null
+++ b/obex/javax/obex/ClientSession.java
@@ -0,0 +1,523 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * This class in an implementation of the OBEX ClientSession.
+ * @hide
+ */
+public final class ClientSession extends ObexSession {
+
+    private boolean mOpen;
+
+    // Determines if an OBEX layer connection has been established
+    private boolean mObexConnected;
+
+    private byte[] mConnectionId = null;
+
+    /*
+     * The max Packet size must be at least 256 according to the OBEX
+     * specification.
+     */
+    private int maxPacketSize = 256;
+
+    private boolean mRequestActive;
+
+    private final InputStream mInput;
+
+    private final OutputStream mOutput;
+
+    public ClientSession(final ObexTransport trans) throws IOException {
+        mInput = trans.openInputStream();
+        mOutput = trans.openOutputStream();
+        mOpen = true;
+        mRequestActive = false;
+    }
+
+    public HeaderSet connect(final HeaderSet header) throws IOException {
+        ensureOpen();
+        if (mObexConnected) {
+            throw new IOException("Already connected to server");
+        }
+        setRequestActive();
+
+        int totalLength = 4;
+        byte[] head = null;
+
+        // Determine the header byte array
+        if (header != null) {
+            if (header.nonce != null) {
+                mChallengeDigest = new byte[16];
+                System.arraycopy(header.nonce, 0, mChallengeDigest, 0, 16);
+            }
+            head = ObexHelper.createHeader(header, false);
+            totalLength += head.length;
+        }
+        /*
+        * Write the OBEX CONNECT packet to the server.
+        * Byte 0: 0x80
+        * Byte 1&2: Connect Packet Length
+        * Byte 3: OBEX Version Number (Presently, 0x10)
+        * Byte 4: Flags (For TCP 0x00)
+        * Byte 5&6: Max OBEX Packet Length (Defined in MAX_PACKET_SIZE)
+        * Byte 7 to n: headers
+        */
+        byte[] requestPacket = new byte[totalLength];
+        // We just need to start at  byte 3 since the sendRequest() method will
+        // handle the length and 0x80.
+        requestPacket[0] = (byte)0x10;
+        requestPacket[1] = (byte)0x00;
+        requestPacket[2] = (byte)(ObexHelper.MAX_PACKET_SIZE_INT >> 8);
+        requestPacket[3] = (byte)(ObexHelper.MAX_PACKET_SIZE_INT & 0xFF);
+        if (head != null) {
+            System.arraycopy(head, 0, requestPacket, 4, head.length);
+        }
+
+        // check with local max packet size
+        if ((requestPacket.length + 3) > ObexHelper.MAX_PACKET_SIZE_INT) {
+            throw new IOException("Packet size exceeds max packet size");
+        }
+
+        HeaderSet returnHeaderSet = new HeaderSet();
+        sendRequest(ObexHelper.OBEX_OPCODE_CONNECT, requestPacket, returnHeaderSet, null);
+
+        /*
+        * Read the response from the OBEX server.
+        * Byte 0: Response Code (If successful then OBEX_HTTP_OK)
+        * Byte 1&2: Packet Length
+        * Byte 3: OBEX Version Number
+        * Byte 4: Flags3
+        * Byte 5&6: Max OBEX packet Length
+        * Byte 7 to n: Optional HeaderSet
+        */
+        if (returnHeaderSet.responseCode == ResponseCodes.OBEX_HTTP_OK) {
+            mObexConnected = true;
+        }
+        setRequestInactive();
+
+        return returnHeaderSet;
+    }
+
+    public Operation get(HeaderSet header) throws IOException {
+
+        if (!mObexConnected) {
+            throw new IOException("Not connected to the server");
+        }
+        setRequestActive();
+
+        ensureOpen();
+
+        HeaderSet head;
+        if (header == null) {
+            head = new HeaderSet();
+        } else {
+            head = header;
+            if (head.nonce != null) {
+                mChallengeDigest = new byte[16];
+                System.arraycopy(head.nonce, 0, mChallengeDigest, 0, 16);
+            }
+        }
+        // Add the connection ID if one exists
+        if (mConnectionId != null) {
+            head.mConnectionID = new byte[4];
+            System.arraycopy(mConnectionId, 0, head.mConnectionID, 0, 4);
+        }
+
+        return new ClientOperation(maxPacketSize, this, head, true);
+    }
+
+    /**
+     * 0xCB Connection Id an identifier used for OBEX connection multiplexing
+     */
+    public void setConnectionID(long id) {
+        if ((id < 0) || (id > 0xFFFFFFFFL)) {
+            throw new IllegalArgumentException("Connection ID is not in a valid range");
+        }
+        mConnectionId = ObexHelper.convertToByteArray(id);
+    }
+
+    public HeaderSet delete(HeaderSet header) throws IOException {
+
+        Operation op = put(header);
+        op.getResponseCode();
+        HeaderSet returnValue = op.getReceivedHeader();
+        op.close();
+
+        return returnValue;
+    }
+
+    public HeaderSet disconnect(HeaderSet header) throws IOException {
+        if (!mObexConnected) {
+            throw new IOException("Not connected to the server");
+        }
+        setRequestActive();
+
+        ensureOpen();
+        // Determine the header byte array
+        byte[] head = null;
+        if (header != null) {
+            if (header.nonce != null) {
+                mChallengeDigest = new byte[16];
+                System.arraycopy(header.nonce, 0, mChallengeDigest, 0, 16);
+            }
+            // Add the connection ID if one exists
+            if (mConnectionId != null) {
+                header.mConnectionID = new byte[4];
+                System.arraycopy(mConnectionId, 0, header.mConnectionID, 0, 4);
+            }
+            head = ObexHelper.createHeader(header, false);
+
+            if ((head.length + 3) > maxPacketSize) {
+                throw new IOException("Packet size exceeds max packet size");
+            }
+        } else {
+            // Add the connection ID if one exists
+            if (mConnectionId != null) {
+                head = new byte[5];
+                head[0] = (byte)HeaderSet.CONNECTION_ID;
+                System.arraycopy(mConnectionId, 0, head, 1, 4);
+            }
+        }
+
+        HeaderSet returnHeaderSet = new HeaderSet();
+        sendRequest(ObexHelper.OBEX_OPCODE_DISCONNECT, head, returnHeaderSet, null);
+
+        /*
+         * An OBEX DISCONNECT reply from the server:
+         * Byte 1: Response code
+         * Bytes 2 & 3: packet size
+         * Bytes 4 & up: headers
+         */
+
+        /* response code , and header are ignored
+         * */
+
+        synchronized (this) {
+            mObexConnected = false;
+            setRequestInactive();
+        }
+
+        return returnHeaderSet;
+    }
+
+    public long getConnectionID() {
+
+        if (mConnectionId == null) {
+            return -1;
+        }
+        return ObexHelper.convertToLong(mConnectionId);
+    }
+
+    public Operation put(HeaderSet header) throws IOException {
+        if (!mObexConnected) {
+            throw new IOException("Not connected to the server");
+        }
+        setRequestActive();
+
+        ensureOpen();
+        HeaderSet head;
+        if (header == null) {
+            head = new HeaderSet();
+        } else {
+            head = header;
+            // when auth is initiated by client ,save the digest
+            if (head.nonce != null) {
+                mChallengeDigest = new byte[16];
+                System.arraycopy(head.nonce, 0, mChallengeDigest, 0, 16);
+            }
+        }
+
+        // Add the connection ID if one exists
+        if (mConnectionId != null) {
+
+            head.mConnectionID = new byte[4];
+            System.arraycopy(mConnectionId, 0, head.mConnectionID, 0, 4);
+        }
+
+        return new ClientOperation(maxPacketSize, this, head, false);
+    }
+
+    public void setAuthenticator(Authenticator auth) throws IOException {
+        if (auth == null) {
+            throw new IOException("Authenticator may not be null");
+        }
+        mAuthenticator = auth;
+    }
+
+    public HeaderSet setPath(HeaderSet header, boolean backup, boolean create) throws IOException {
+        if (!mObexConnected) {
+            throw new IOException("Not connected to the server");
+        }
+        setRequestActive();
+        ensureOpen();
+
+        int totalLength = 2;
+        byte[] head = null;
+        HeaderSet headset;
+        if (header == null) {
+            headset = new HeaderSet();
+        } else {
+            headset = header;
+            if (headset.nonce != null) {
+                mChallengeDigest = new byte[16];
+                System.arraycopy(headset.nonce, 0, mChallengeDigest, 0, 16);
+            }
+        }
+
+        // when auth is initiated by client ,save the digest
+        if (headset.nonce != null) {
+            mChallengeDigest = new byte[16];
+            System.arraycopy(headset.nonce, 0, mChallengeDigest, 0, 16);
+        }
+
+        // Add the connection ID if one exists
+        if (mConnectionId != null) {
+            headset.mConnectionID = new byte[4];
+            System.arraycopy(mConnectionId, 0, headset.mConnectionID, 0, 4);
+        }
+
+        head = ObexHelper.createHeader(headset, false);
+        totalLength += head.length;
+
+        if (totalLength > maxPacketSize) {
+            throw new IOException("Packet size exceeds max packet size");
+        }
+
+        int flags = 0;
+        /*
+         * The backup flag bit is bit 0 so if we add 1, this will set that bit
+         */
+        if (backup) {
+            flags++;
+        }
+        /*
+         * The create bit is bit 1 so if we or with 2 the bit will be set.
+         */
+        if (!create) {
+            flags |= 2;
+        }
+
+        /*
+         * An OBEX SETPATH packet to the server:
+         * Byte 1: 0x85
+         * Byte 2 & 3: packet size
+         * Byte 4: flags
+         * Byte 5: constants
+         * Byte 6 & up: headers
+         */
+        byte[] packet = new byte[totalLength];
+        packet[0] = (byte)flags;
+        packet[1] = (byte)0x00;
+        if (headset != null) {
+            System.arraycopy(head, 0, packet, 2, head.length);
+        }
+
+        HeaderSet returnHeaderSet = new HeaderSet();
+        sendRequest(ObexHelper.OBEX_OPCODE_SETPATH, packet, returnHeaderSet, null);
+
+        /*
+         * An OBEX SETPATH reply from the server:
+         * Byte 1: Response code
+         * Bytes 2 & 3: packet size
+         * Bytes 4 & up: headers
+         */
+
+        setRequestInactive();
+
+        return returnHeaderSet;
+    }
+
+    /**
+     * Verifies that the connection is open.
+     * @throws IOException if the connection is closed
+     */
+    public synchronized void ensureOpen() throws IOException {
+        if (!mOpen) {
+            throw new IOException("Connection closed");
+        }
+    }
+
+    /**
+     * Set request inactive. Allows Put and get operation objects to tell this
+     * object when they are done.
+     */
+    /*package*/synchronized void setRequestInactive() {
+        mRequestActive = false;
+    }
+
+    /**
+     * Set request to active.
+     * @throws IOException if already active
+     */
+    private synchronized void setRequestActive() throws IOException {
+        if (mRequestActive) {
+            throw new IOException("OBEX request is already being performed");
+        }
+        mRequestActive = true;
+    }
+
+    /**
+     * Sends a standard request to the client. It will then wait for the reply
+     * and update the header set object provided. If any authentication headers
+     * (i.e. authentication challenge or authentication response) are received,
+     * they will be processed.
+     * @param opCode the type of request to send to the client
+     * @param head the headers to send to the client
+     * @param header the header object to update with the response
+     * @param privateInput the input stream used by the Operation object; null
+     *        if this is called on a CONNECT, SETPATH or DISCONNECT return
+     *        <code>true</code> if the operation completed successfully;
+     *        <code>false</code> if an authentication response failed to pass
+     * @throws IOException if an IO error occurs
+     */
+    public boolean sendRequest(int opCode, byte[] head, HeaderSet header,
+            PrivateInputStream privateInput) throws IOException {
+        //check header length with local max size
+        if (head != null) {
+            if ((head.length + 3) > ObexHelper.MAX_PACKET_SIZE_INT) {
+                throw new IOException("header too large ");
+            }
+        }
+
+        int bytesReceived;
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        out.write((byte)opCode);
+
+        // Determine if there are any headers to send
+        if (head == null) {
+            out.write(0x00);
+            out.write(0x03);
+        } else {
+            out.write((byte)((head.length + 3) >> 8));
+            out.write((byte)(head.length + 3));
+            out.write(head);
+        }
+
+        // Write the request to the output stream and flush the stream
+        mOutput.write(out.toByteArray());
+        mOutput.flush();
+
+        header.responseCode = mInput.read();
+
+        int length = ((mInput.read() << 8) | (mInput.read()));
+
+        if (length > ObexHelper.MAX_PACKET_SIZE_INT) {
+            throw new IOException("Packet received exceeds packet size limit");
+        }
+        if (length > ObexHelper.BASE_PACKET_LENGTH) {
+            byte[] data = null;
+            if (opCode == ObexHelper.OBEX_OPCODE_CONNECT) {
+                @SuppressWarnings("unused")
+                int version = mInput.read();
+                @SuppressWarnings("unused")
+                int flags = mInput.read();
+                maxPacketSize = (mInput.read() << 8) + mInput.read();
+
+                //check with local max size
+                if (maxPacketSize > ObexHelper.MAX_PACKET_SIZE_INT) {
+                    maxPacketSize = ObexHelper.MAX_PACKET_SIZE_INT;
+                }
+
+                if (length > 7) {
+                    data = new byte[length - 7];
+
+                    bytesReceived = mInput.read(data);
+                    while (bytesReceived != (length - 7)) {
+                        bytesReceived += mInput.read(data, bytesReceived, data.length
+                                - bytesReceived);
+                    }
+                } else {
+                    return true;
+                }
+            } else {
+                data = new byte[length - 3];
+                bytesReceived = mInput.read(data);
+
+                while (bytesReceived != (length - 3)) {
+                    bytesReceived += mInput.read(data, bytesReceived, data.length - bytesReceived);
+                }
+                if (opCode == ObexHelper.OBEX_OPCODE_ABORT) {
+                    return true;
+                }
+            }
+
+            byte[] body = ObexHelper.updateHeaderSet(header, data);
+            if ((privateInput != null) && (body != null)) {
+                privateInput.writeBytes(body, 1);
+            }
+
+            if (header.mConnectionID != null) {
+                mConnectionId = new byte[4];
+                System.arraycopy(header.mConnectionID, 0, mConnectionId, 0, 4);
+            }
+
+            if (header.mAuthResp != null) {
+                if (!handleAuthResp(header.mAuthResp)) {
+                    setRequestInactive();
+                    throw new IOException("Authentication Failed");
+                }
+            }
+
+            if ((header.responseCode == ResponseCodes.OBEX_HTTP_UNAUTHORIZED)
+                    && (header.mAuthChall != null)) {
+
+                if (handleAuthChall(header)) {
+                    out.write((byte)HeaderSet.AUTH_RESPONSE);
+                    out.write((byte)((header.mAuthResp.length + 3) >> 8));
+                    out.write((byte)(header.mAuthResp.length + 3));
+                    out.write(header.mAuthResp);
+                    header.mAuthChall = null;
+                    header.mAuthResp = null;
+
+                    byte[] sendHeaders = new byte[out.size() - 3];
+                    System.arraycopy(out.toByteArray(), 3, sendHeaders, 0, sendHeaders.length);
+
+                    return sendRequest(opCode, sendHeaders, header, privateInput);
+                }
+            }
+        }
+
+        return true;
+    }
+
+    public void close() throws IOException {
+        mOpen = false;
+        mInput.close();
+        mOutput.close();
+    }
+}
diff --git a/obex/javax/obex/HeaderSet.java b/obex/javax/obex/HeaderSet.java
new file mode 100644
index 0000000..8b457f6
--- /dev/null
+++ b/obex/javax/obex/HeaderSet.java
@@ -0,0 +1,628 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.Calendar;
+import java.util.Random;
+
+/**
+ * This class implements the javax.obex.HeaderSet interface for OBEX over
+ * RFCOMM.
+ * @hide
+ */
+public final class HeaderSet {
+
+    /**
+     * Represents the OBEX Count header. This allows the connection statement to
+     * tell the server how many objects it plans to send or retrieve.
+     * <P>
+     * The value of <code>COUNT</code> is 0xC0 (192).
+     */
+    public static final int COUNT = 0xC0;
+
+    /**
+     * Represents the OBEX Name header. This specifies the name of the object.
+     * <P>
+     * The value of <code>NAME</code> is 0x01 (1).
+     */
+    public static final int NAME = 0x01;
+
+    /**
+     * Represents the OBEX Type header. This allows a request to specify the
+     * type of the object (e.g. text, html, binary, etc.).
+     * <P>
+     * The value of <code>TYPE</code> is 0x42 (66).
+     */
+    public static final int TYPE = 0x42;
+
+    /**
+     * Represents the OBEX Length header. This is the length of the object in
+     * bytes.
+     * <P>
+     * The value of <code>LENGTH</code> is 0xC3 (195).
+     */
+    public static final int LENGTH = 0xC3;
+
+    /**
+     * Represents the OBEX Time header using the ISO 8601 standards. This is the
+     * preferred time header.
+     * <P>
+     * The value of <code>TIME_ISO_8601</code> is 0x44 (68).
+     */
+    public static final int TIME_ISO_8601 = 0x44;
+
+    /**
+     * Represents the OBEX Time header using the 4 byte representation. This is
+     * only included for backwards compatibility. It represents the number of
+     * seconds since January 1, 1970.
+     * <P>
+     * The value of <code>TIME_4_BYTE</code> is 0xC4 (196).
+     */
+    public static final int TIME_4_BYTE = 0xC4;
+
+    /**
+     * Represents the OBEX Description header. This is a text description of the
+     * object.
+     * <P>
+     * The value of <code>DESCRIPTION</code> is 0x05 (5).
+     */
+    public static final int DESCRIPTION = 0x05;
+
+    /**
+     * Represents the OBEX Target header. This is the name of the service an
+     * operation is targeted to.
+     * <P>
+     * The value of <code>TARGET</code> is 0x46 (70).
+     */
+    public static final int TARGET = 0x46;
+
+    /**
+     * Represents the OBEX HTTP header. This allows an HTTP 1.X header to be
+     * included in a request or reply.
+     * <P>
+     * The value of <code>HTTP</code> is 0x47 (71).
+     */
+    public static final int HTTP = 0x47;
+
+    /**
+     * Represents the OBEX BODY header.
+     * <P>
+     * The value of <code>BODY</code> is 0x48 (72).
+     */
+    public static final int BODY = 0x48;
+
+    /**
+     * Represents the OBEX End of BODY header.
+     * <P>
+     * The value of <code>BODY</code> is 0x49 (73).
+     */
+    public static final int END_OF_BODY = 0x49;
+
+    /**
+     * Represents the OBEX Who header. Identifies the OBEX application to
+     * determine if the two peers are talking to each other.
+     * <P>
+     * The value of <code>WHO</code> is 0x4A (74).
+     */
+    public static final int WHO = 0x4A;
+
+    /**
+     * Represents the OBEX Connection ID header. Identifies used for OBEX
+     * connection multiplexing.
+     * <P>
+     * The value of <code>CONNECTION_ID</code> is 0xCB (203).
+     */
+
+    public static final int CONNECTION_ID = 0xCB;
+
+    /**
+     * Represents the OBEX Application Parameter header. This header specifies
+     * additional application request and response information.
+     * <P>
+     * The value of <code>APPLICATION_PARAMETER</code> is 0x4C (76).
+     */
+    public static final int APPLICATION_PARAMETER = 0x4C;
+
+    /**
+     * Represents the OBEX authentication digest-challenge.
+     * <P>
+     * The value of <code>AUTH_CHALLENGE</code> is 0x4D (77).
+     */
+    public static final int AUTH_CHALLENGE = 0x4D;
+
+    /**
+     * Represents the OBEX authentication digest-response.
+     * <P>
+     * The value of <code>AUTH_RESPONSE</code> is 0x4E (78).
+     */
+    public static final int AUTH_RESPONSE = 0x4E;
+
+    /**
+     * Represents the OBEX Object Class header. This header specifies the OBEX
+     * object class of the object.
+     * <P>
+     * The value of <code>OBJECT_CLASS</code> is 0x4F (79).
+     */
+    public static final int OBJECT_CLASS = 0x4F;
+
+    private Long mCount; // 4 byte unsigned integer
+
+    private String mName; // null terminated Unicode text string
+
+    private String mType; // null terminated ASCII text string
+
+    private Long mLength; // 4 byte unsigend integer
+
+    private Calendar mIsoTime; // String of the form YYYYMMDDTHHMMSSZ
+
+    private Calendar mByteTime; // 4 byte unsigned integer
+
+    private String mDescription; // null terminated Unicode text String
+
+    private byte[] mTarget; // byte sequence
+
+    private byte[] mHttpHeader; // byte sequence
+
+    private byte[] mWho; // length prefixed byte sequence
+
+    private byte[] mAppParam; // byte sequence of the form tag length value
+
+    private byte[] mObjectClass; // byte sequence
+
+    private String[] mUnicodeUserDefined; //null terminated unicode string
+
+    private byte[][] mSequenceUserDefined; // byte sequence user defined
+
+    private Byte[] mByteUserDefined; // 1 byte
+
+    private Long[] mIntegerUserDefined; // 4 byte unsigned integer
+
+    private final Random mRandom;
+
+    /*package*/ byte[] nonce;
+
+    public byte[] mAuthChall; // The authentication challenge header
+
+    public byte[] mAuthResp; // The authentication response header
+
+    public byte[] mConnectionID; // THe connection ID
+
+    public int responseCode;
+
+    /**
+     * Creates new <code>HeaderSet</code> object.
+     * @param size the max packet size for this connection
+     */
+    public HeaderSet() {
+        mUnicodeUserDefined = new String[16];
+        mSequenceUserDefined = new byte[16][];
+        mByteUserDefined = new Byte[16];
+        mIntegerUserDefined = new Long[16];
+        responseCode = -1;
+        mRandom = new Random();
+    }
+
+    /**
+     * Sets the value of the header identifier to the value provided. The type
+     * of object must correspond to the Java type defined in the description of
+     * this interface. If <code>null</code> is passed as the
+     * <code>headerValue</code> then the header will be removed from the set of
+     * headers to include in the next request.
+     * @param headerID the identifier to include in the message
+     * @param headerValue the value of the header identifier
+     * @throws IllegalArgumentException if the header identifier provided is not
+     *         one defined in this interface or a user-defined header; if the
+     *         type of <code>headerValue</code> is not the correct Java type as
+     *         defined in the description of this interface\
+     */
+    public void setHeader(int headerID, Object headerValue) {
+        long temp = -1;
+
+        switch (headerID) {
+            case COUNT:
+                if (!(headerValue instanceof Long)) {
+                    if (headerValue == null) {
+                        mCount = null;
+                        break;
+                    }
+                    throw new IllegalArgumentException("Count must be a Long");
+                }
+                temp = ((Long)headerValue).longValue();
+                if ((temp < 0L) || (temp > 0xFFFFFFFFL)) {
+                    throw new IllegalArgumentException("Count must be between 0 and 0xFFFFFFFF");
+                }
+                mCount = (Long)headerValue;
+                break;
+            case NAME:
+                if ((headerValue != null) && (!(headerValue instanceof String))) {
+                    throw new IllegalArgumentException("Name must be a String");
+                }
+                mName = (String)headerValue;
+                break;
+            case TYPE:
+                if ((headerValue != null) && (!(headerValue instanceof String))) {
+                    throw new IllegalArgumentException("Type must be a String");
+                }
+                mType = (String)headerValue;
+                break;
+            case LENGTH:
+                if (!(headerValue instanceof Long)) {
+                    if (headerValue == null) {
+                        mLength = null;
+                        break;
+                    }
+                    throw new IllegalArgumentException("Length must be a Long");
+                }
+                temp = ((Long)headerValue).longValue();
+                if ((temp < 0L) || (temp > 0xFFFFFFFFL)) {
+                    throw new IllegalArgumentException("Length must be between 0 and 0xFFFFFFFF");
+                }
+                mLength = (Long)headerValue;
+                break;
+            case TIME_ISO_8601:
+                if ((headerValue != null) && (!(headerValue instanceof Calendar))) {
+                    throw new IllegalArgumentException("Time ISO 8601 must be a Calendar");
+                }
+                mIsoTime = (Calendar)headerValue;
+                break;
+            case TIME_4_BYTE:
+                if ((headerValue != null) && (!(headerValue instanceof Calendar))) {
+                    throw new IllegalArgumentException("Time 4 Byte must be a Calendar");
+                }
+                mByteTime = (Calendar)headerValue;
+                break;
+            case DESCRIPTION:
+                if ((headerValue != null) && (!(headerValue instanceof String))) {
+                    throw new IllegalArgumentException("Description must be a String");
+                }
+                mDescription = (String)headerValue;
+                break;
+            case TARGET:
+                if (headerValue == null) {
+                    mTarget = null;
+                } else {
+                    if (!(headerValue instanceof byte[])) {
+                        throw new IllegalArgumentException("Target must be a byte array");
+                    } else {
+                        mTarget = new byte[((byte[])headerValue).length];
+                        System.arraycopy(headerValue, 0, mTarget, 0, mTarget.length);
+                    }
+                }
+                break;
+            case HTTP:
+                if (headerValue == null) {
+                    mHttpHeader = null;
+                } else {
+                    if (!(headerValue instanceof byte[])) {
+                        throw new IllegalArgumentException("HTTP must be a byte array");
+                    } else {
+                        mHttpHeader = new byte[((byte[])headerValue).length];
+                        System.arraycopy(headerValue, 0, mHttpHeader, 0, mHttpHeader.length);
+                    }
+                }
+                break;
+            case WHO:
+                if (headerValue == null) {
+                    mWho = null;
+                } else {
+                    if (!(headerValue instanceof byte[])) {
+                        throw new IllegalArgumentException("WHO must be a byte array");
+                    } else {
+                        mWho = new byte[((byte[])headerValue).length];
+                        System.arraycopy(headerValue, 0, mWho, 0, mWho.length);
+                    }
+                }
+                break;
+            case OBJECT_CLASS:
+                if (headerValue == null) {
+                    mObjectClass = null;
+                } else {
+                    if (!(headerValue instanceof byte[])) {
+                        throw new IllegalArgumentException("Object Class must be a byte array");
+                    } else {
+                        mObjectClass = new byte[((byte[])headerValue).length];
+                        System.arraycopy(headerValue, 0, mObjectClass, 0, mObjectClass.length);
+                    }
+                }
+                break;
+            case APPLICATION_PARAMETER:
+                if (headerValue == null) {
+                    mAppParam = null;
+                } else {
+                    if (!(headerValue instanceof byte[])) {
+                        throw new IllegalArgumentException(
+                                "Application Parameter must be a byte array");
+                    } else {
+                        mAppParam = new byte[((byte[])headerValue).length];
+                        System.arraycopy(headerValue, 0, mAppParam, 0, mAppParam.length);
+                    }
+                }
+                break;
+            default:
+                // Verify that it was not a Unicode String user Defined
+                if ((headerID >= 0x30) && (headerID <= 0x3F)) {
+                    if ((headerValue != null) && (!(headerValue instanceof String))) {
+                        throw new IllegalArgumentException(
+                                "Unicode String User Defined must be a String");
+                    }
+                    mUnicodeUserDefined[headerID - 0x30] = (String)headerValue;
+
+                    break;
+                }
+                // Verify that it was not a byte sequence user defined value
+                if ((headerID >= 0x70) && (headerID <= 0x7F)) {
+
+                    if (headerValue == null) {
+                        mSequenceUserDefined[headerID - 0x70] = null;
+                    } else {
+                        if (!(headerValue instanceof byte[])) {
+                            throw new IllegalArgumentException(
+                                    "Byte Sequence User Defined must be a byte array");
+                        } else {
+                            mSequenceUserDefined[headerID - 0x70] = new byte[((byte[])headerValue).length];
+                            System.arraycopy(headerValue, 0, mSequenceUserDefined[headerID - 0x70],
+                                    0, mSequenceUserDefined[headerID - 0x70].length);
+                        }
+                    }
+                    break;
+                }
+                // Verify that it was not a Byte user Defined
+                if ((headerID >= 0xB0) && (headerID <= 0xBF)) {
+                    if ((headerValue != null) && (!(headerValue instanceof Byte))) {
+                        throw new IllegalArgumentException("ByteUser Defined must be a Byte");
+                    }
+                    mByteUserDefined[headerID - 0xB0] = (Byte)headerValue;
+
+                    break;
+                }
+                // Verify that is was not the 4 byte unsigned integer user
+                // defined header
+                if ((headerID >= 0xF0) && (headerID <= 0xFF)) {
+                    if (!(headerValue instanceof Long)) {
+                        if (headerValue == null) {
+                            mIntegerUserDefined[headerID - 0xF0] = null;
+                            break;
+                        }
+                        throw new IllegalArgumentException("Integer User Defined must be a Long");
+                    }
+                    temp = ((Long)headerValue).longValue();
+                    if ((temp < 0L) || (temp > 0xFFFFFFFFL)) {
+                        throw new IllegalArgumentException(
+                                "Integer User Defined must be between 0 and 0xFFFFFFFF");
+                    }
+                    mIntegerUserDefined[headerID - 0xF0] = (Long)headerValue;
+                    break;
+                }
+                throw new IllegalArgumentException("Invalid Header Identifier");
+        }
+    }
+
+    /**
+     * Retrieves the value of the header identifier provided. The type of the
+     * Object returned is defined in the description of this interface.
+     * @param headerID the header identifier whose value is to be returned
+     * @return the value of the header provided or <code>null</code> if the
+     *         header identifier specified is not part of this
+     *         <code>HeaderSet</code> object
+     * @throws IllegalArgumentException if the <code>headerID</code> is not one
+     *         defined in this interface or any of the user-defined headers
+     * @throws IOException if an error occurred in the transport layer during
+     *         the operation or if the connection has been closed
+     */
+    public Object getHeader(int headerID) throws IOException {
+
+        switch (headerID) {
+            case COUNT:
+                return mCount;
+            case NAME:
+                return mName;
+            case TYPE:
+                return mType;
+            case LENGTH:
+                return mLength;
+            case TIME_ISO_8601:
+                return mIsoTime;
+            case TIME_4_BYTE:
+                return mByteTime;
+            case DESCRIPTION:
+                return mDescription;
+            case TARGET:
+                return mTarget;
+            case HTTP:
+                return mHttpHeader;
+            case WHO:
+                return mWho;
+            case OBJECT_CLASS:
+                return mObjectClass;
+            case APPLICATION_PARAMETER:
+                return mAppParam;
+            default:
+                // Verify that it was not a Unicode String user Defined
+                if ((headerID >= 0x30) && (headerID <= 0x3F)) {
+                    return mUnicodeUserDefined[headerID - 0x30];
+                }
+                // Verify that it was not a byte sequence user defined header
+                if ((headerID >= 0x70) && (headerID <= 0x7F)) {
+                    return mSequenceUserDefined[headerID - 0x70];
+                }
+                // Verify that it was not a byte user defined header
+                if ((headerID >= 0xB0) && (headerID <= 0xBF)) {
+                    return mByteUserDefined[headerID - 0xB0];
+                }
+                // Verify that it was not a integer user defined header
+                if ((headerID >= 0xF0) && (headerID <= 0xFF)) {
+                    return mIntegerUserDefined[headerID - 0xF0];
+                }
+                throw new IllegalArgumentException("Invalid Header Identifier");
+        }
+    }
+
+    /**
+     * Retrieves the list of headers that may be retrieved via the
+     * <code>getHeader</code> method that will not return <code>null</code>. In
+     * other words, this method returns all the headers that are available in
+     * this object.
+     * @see #getHeader
+     * @return the array of headers that are set in this object or
+     *         <code>null</code> if no headers are available
+     * @throws IOException if an error occurred in the transport layer during
+     *         the operation or the connection has been closed
+     */
+    public int[] getHeaderList() throws IOException {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+
+        if (mCount != null) {
+            out.write(COUNT);
+        }
+        if (mName != null) {
+            out.write(NAME);
+        }
+        if (mType != null) {
+            out.write(TYPE);
+        }
+        if (mLength != null) {
+            out.write(LENGTH);
+        }
+        if (mIsoTime != null) {
+            out.write(TIME_ISO_8601);
+        }
+        if (mByteTime != null) {
+            out.write(TIME_4_BYTE);
+        }
+        if (mDescription != null) {
+            out.write(DESCRIPTION);
+        }
+        if (mTarget != null) {
+            out.write(TARGET);
+        }
+        if (mHttpHeader != null) {
+            out.write(HTTP);
+        }
+        if (mWho != null) {
+            out.write(WHO);
+        }
+        if (mAppParam != null) {
+            out.write(APPLICATION_PARAMETER);
+        }
+        if (mObjectClass != null) {
+            out.write(OBJECT_CLASS);
+        }
+
+        for (int i = 0x30; i < 0x40; i++) {
+            if (mUnicodeUserDefined[i - 0x30] != null) {
+                out.write(i);
+            }
+        }
+
+        for (int i = 0x70; i < 0x80; i++) {
+            if (mSequenceUserDefined[i - 0x70] != null) {
+                out.write(i);
+            }
+        }
+
+        for (int i = 0xB0; i < 0xC0; i++) {
+            if (mByteUserDefined[i - 0xB0] != null) {
+                out.write(i);
+            }
+        }
+
+        for (int i = 0xF0; i < 0x100; i++) {
+            if (mIntegerUserDefined[i - 0xF0] != null) {
+                out.write(i);
+            }
+        }
+
+        byte[] headers = out.toByteArray();
+        out.close();
+
+        if ((headers == null) || (headers.length == 0)) {
+            return null;
+        }
+
+        int[] result = new int[headers.length];
+        for (int i = 0; i < headers.length; i++) {
+            // Convert the byte to a positive integer.  That is, an integer
+            // between 0 and 256.
+            result[i] = headers[i] & 0xFF;
+        }
+
+        return result;
+    }
+
+    /**
+     * Sets the authentication challenge header. The <code>realm</code> will be
+     * encoded based upon the default encoding scheme used by the implementation
+     * to encode strings. Therefore, the encoding scheme used to encode the
+     * <code>realm</code> is application dependent.
+     * @param realm a short description that describes what password to use; if
+     *        <code>null</code> no realm will be sent in the authentication
+     *        challenge header
+     * @param userID if <code>true</code>, a user ID is required in the reply;
+     *        if <code>false</code>, no user ID is required
+     * @param access if <code>true</code> then full access will be granted if
+     *        successful; if <code>false</code> then read-only access will be
+     *        granted if successful
+     * @throws IOException
+     */
+    public void createAuthenticationChallenge(String realm, boolean userID, boolean access)
+            throws IOException {
+
+        nonce = new byte[16];
+        for (int i = 0; i < 16; i++) {
+            nonce[i] = (byte)mRandom.nextInt();
+        }
+
+        mAuthChall = ObexHelper.computeAuthenticationChallenge(nonce, realm, access, userID);
+    }
+
+    /**
+     * Returns the response code received from the server. Response codes are
+     * defined in the <code>ResponseCodes</code> class.
+     * @see ResponseCodes
+     * @return the response code retrieved from the server
+     * @throws IOException if an error occurred in the transport layer during
+     *         the transaction; if this method is called on a
+     *         <code>HeaderSet</code> object created by calling
+     *         <code>createHeaderSet()</code> in a <code>ClientSession</code>
+     *         object; if this object was created by an OBEX server
+     */
+    public int getResponseCode() throws IOException {
+        if (responseCode == -1) {
+            throw new IOException("May not be called on a server");
+        } else {
+            return responseCode;
+        }
+    }
+}
diff --git a/obex/javax/obex/ObexHelper.java b/obex/javax/obex/ObexHelper.java
new file mode 100644
index 0000000..f569595
--- /dev/null
+++ b/obex/javax/obex/ObexHelper.java
@@ -0,0 +1,990 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import android.security.Md5MessageDigest;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
+
+/**
+ * This class defines a set of helper methods for the implementation of Obex.
+ * @hide
+ */
+public final class ObexHelper {
+
+    /**
+     * Defines the basic packet length used by OBEX. Every OBEX packet has the
+     * same basic format:<BR>
+     * Byte 0: Request or Response Code Byte 1&2: Length of the packet.
+     */
+    public static final int BASE_PACKET_LENGTH = 3;
+
+    /** Prevent object construction of helper class */
+    private ObexHelper() {
+    }
+
+    /**
+     * The maximum packet size for OBEX packets that this client can handle. At
+     * present, this must be changed for each port. TODO: The max packet size
+     * should be the Max incoming MTU minus TODO: L2CAP package headers and
+     * RFCOMM package headers. TODO: Retrieve the max incoming MTU from TODO:
+     * LocalDevice.getProperty().
+     */
+    /*
+     * android note set as 0xFFFE to match remote MPS
+     */
+    public static final int MAX_PACKET_SIZE_INT = 0xFFFE;
+
+    public static final int OBEX_OPCODE_CONNECT = 0x80;
+
+    public static final int OBEX_OPCODE_DISCONNECT = 0x81;
+
+    public static final int OBEX_OPCODE_PUT = 0x02;
+
+    public static final int OBEX_OPCODE_PUT_FINAL = 0x82;
+
+    public static final int OBEX_OPCODE_GET = 0x03;
+
+    public static final int OBEX_OPCODE_GET_FINAL = 0x83;
+
+    public static final int OBEX_OPCODE_RESERVED = 0x04;
+
+    public static final int OBEX_OPCODE_RESERVED_FINAL = 0x84;
+
+    public static final int OBEX_OPCODE_SETPATH = 0x85;
+
+    public static final int OBEX_OPCODE_ABORT = 0xFF;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_ASCII = 0x00;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_ISO_8859_1 = 0x01;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_ISO_8859_2 = 0x02;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_ISO_8859_3 = 0x03;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_ISO_8859_4 = 0x04;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_ISO_8859_5 = 0x05;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_ISO_8859_6 = 0x06;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_ISO_8859_7 = 0x07;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_ISO_8859_8 = 0x08;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_ISO_8859_9 = 0x09;
+
+    public static final int OBEX_AUTH_REALM_CHARSET_UNICODE = 0xFF;
+
+    /**
+     * Updates the HeaderSet with the headers received in the byte array
+     * provided. Invalid headers are ignored.
+     * <P>
+     * The first two bits of an OBEX Header specifies the type of object that is
+     * being sent. The table below specifies the meaning of the high bits.
+     * <TABLE>
+     * <TR>
+     * <TH>Bits 8 and 7</TH>
+     * <TH>Value</TH>
+     * <TH>Description</TH>
+     * </TR>
+     * <TR>
+     * <TD>00</TD>
+     * <TD>0x00</TD>
+     * <TD>Null Terminated Unicode text, prefixed with 2 byte unsigned integer</TD>
+     * </TR>
+     * <TR>
+     * <TD>01</TD>
+     * <TD>0x40</TD>
+     * <TD>Byte Sequence, length prefixed with 2 byte unsigned integer</TD>
+     * </TR>
+     * <TR>
+     * <TD>10</TD>
+     * <TD>0x80</TD>
+     * <TD>1 byte quantity</TD>
+     * </TR>
+     * <TR>
+     * <TD>11</TD>
+     * <TD>0xC0</TD>
+     * <TD>4 byte quantity - transmitted in network byte order (high byte first</TD>
+     * </TR>
+     * </TABLE>
+     * This method uses the information in this table to determine the type of
+     * Java object to create and passes that object with the full header to
+     * setHeader() to update the HeaderSet object. Invalid headers will cause an
+     * exception to be thrown. When it is thrown, it is ignored.
+     * @param header the HeaderSet to update
+     * @param headerArray the byte array containing headers
+     * @return the result of the last start body or end body header provided;
+     *         the first byte in the result will specify if a body or end of
+     *         body is received
+     * @throws IOException if an invalid header was found
+     */
+    public static byte[] updateHeaderSet(HeaderSet header, byte[] headerArray) throws IOException {
+        int index = 0;
+        int length = 0;
+        int headerID;
+        byte[] value = null;
+        byte[] body = null;
+        HeaderSet headerImpl = header;
+        try {
+            while (index < headerArray.length) {
+                headerID = 0xFF & headerArray[index];
+                switch (headerID & (0xC0)) {
+
+                    /*
+                     * 0x00 is a unicode null terminate string with the first
+                     * two bytes after the header identifier being the length
+                     */
+                    case 0x00:
+                        // Fall through
+                        /*
+                         * 0x40 is a byte sequence with the first
+                         * two bytes after the header identifier being the length
+                         */
+                    case 0x40:
+                        boolean trimTail = true;
+                        index++;
+                        length = 0xFF & headerArray[index];
+                        length = length << 8;
+                        index++;
+                        length += 0xFF & headerArray[index];
+                        length -= 3;
+                        index++;
+                        value = new byte[length];
+                        System.arraycopy(headerArray, index, value, 0, length);
+                        if (length == 0 || (length > 0 && (value[length - 1] != 0))) {
+                            trimTail = false;
+                        }
+                        switch (headerID) {
+                            case HeaderSet.TYPE:
+                                try {
+                                    // Remove trailing null
+                                    if (trimTail == false) {
+                                        headerImpl.setHeader(headerID, new String(value, 0,
+                                                value.length, "ISO8859_1"));
+                                    } else {
+                                        headerImpl.setHeader(headerID, new String(value, 0,
+                                                value.length - 1, "ISO8859_1"));
+                                    }
+                                } catch (UnsupportedEncodingException e) {
+                                    throw e;
+                                }
+                                break;
+
+                            case HeaderSet.AUTH_CHALLENGE:
+                                headerImpl.mAuthChall = new byte[length];
+                                System.arraycopy(headerArray, index, headerImpl.mAuthChall, 0,
+                                        length);
+                                break;
+
+                            case HeaderSet.AUTH_RESPONSE:
+                                headerImpl.mAuthResp = new byte[length];
+                                System.arraycopy(headerArray, index, headerImpl.mAuthResp, 0,
+                                        length);
+                                break;
+
+                            case HeaderSet.BODY:
+                                /* Fall Through */
+                            case HeaderSet.END_OF_BODY:
+                                body = new byte[length + 1];
+                                body[0] = (byte)headerID;
+                                System.arraycopy(headerArray, index, body, 1, length);
+                                break;
+
+                            case HeaderSet.TIME_ISO_8601:
+                                try {
+                                    String dateString = new String(value, "ISO8859_1");
+                                    Calendar temp = Calendar.getInstance();
+                                    if ((dateString.length() == 16)
+                                            && (dateString.charAt(15) == 'Z')) {
+                                        temp.setTimeZone(TimeZone.getTimeZone("UTC"));
+                                    }
+                                    temp.set(Calendar.YEAR, Integer.parseInt(dateString.substring(
+                                            0, 4)));
+                                    temp.set(Calendar.MONTH, Integer.parseInt(dateString.substring(
+                                            4, 6)));
+                                    temp.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateString
+                                            .substring(6, 8)));
+                                    temp.set(Calendar.HOUR_OF_DAY, Integer.parseInt(dateString
+                                            .substring(9, 11)));
+                                    temp.set(Calendar.MINUTE, Integer.parseInt(dateString
+                                            .substring(11, 13)));
+                                    temp.set(Calendar.SECOND, Integer.parseInt(dateString
+                                            .substring(13, 15)));
+                                    headerImpl.setHeader(HeaderSet.TIME_ISO_8601, temp);
+                                } catch (UnsupportedEncodingException e) {
+                                    throw e;
+                                }
+                                break;
+
+                            default:
+                                if ((headerID & 0xC0) == 0x00) {
+                                    headerImpl.setHeader(headerID, ObexHelper.convertToUnicode(
+                                            value, true));
+                                } else {
+                                    headerImpl.setHeader(headerID, value);
+                                }
+                        }
+
+                        index += length;
+                        break;
+
+                    /*
+                     * 0x80 is a byte header.  The only valid byte headers are
+                     * the 16 user defined byte headers.
+                     */
+                    case 0x80:
+                        index++;
+                        try {
+                            headerImpl.setHeader(headerID, Byte.valueOf(headerArray[index]));
+                        } catch (Exception e) {
+                            // Not a valid header so ignore
+                        }
+                        index++;
+                        break;
+
+                    /*
+                     * 0xC0 is a 4 byte unsigned integer header and with the
+                     * exception of TIME_4_BYTE will be converted to a Long
+                     * and added.
+                     */
+                    case 0xC0:
+                        index++;
+                        value = new byte[4];
+                        System.arraycopy(headerArray, index, value, 0, 4);
+                        try {
+                            if (headerID != HeaderSet.TIME_4_BYTE) {
+                                // Determine if it is a connection ID.  These
+                                // need to be handled differently
+                                if (headerID == HeaderSet.CONNECTION_ID) {
+                                    headerImpl.mConnectionID = new byte[4];
+                                    System.arraycopy(value, 0, headerImpl.mConnectionID, 0, 4);
+                                } else {
+                                    headerImpl.setHeader(headerID, Long
+                                            .valueOf(convertToLong(value)));
+                                }
+                            } else {
+                                Calendar temp = Calendar.getInstance();
+                                temp.setTime(new Date(convertToLong(value) * 1000L));
+                                headerImpl.setHeader(HeaderSet.TIME_4_BYTE, temp);
+                            }
+                        } catch (Exception e) {
+                            // Not a valid header so ignore
+                            throw new IOException("Header was not formatted properly");
+                        }
+                        index += 4;
+                        break;
+                }
+
+            }
+        } catch (IOException e) {
+            throw new IOException("Header was not formatted properly");
+        }
+
+        return body;
+    }
+
+    /**
+     * Creates the header part of OBEX packet based on the header provided.
+     * TODO: Could use getHeaderList() to get the array of headers to include
+     * and then use the high two bits to determine the the type of the object
+     * and construct the byte array from that. This will make the size smaller.
+     * @param head the header used to construct the byte array
+     * @param nullOut <code>true</code> if the header should be set to
+     *        <code>null</code> once it is added to the array or
+     *        <code>false</code> if it should not be nulled out
+     * @return the header of an OBEX packet
+     */
+    public static byte[] createHeader(HeaderSet head, boolean nullOut) {
+        Long intHeader = null;
+        String stringHeader = null;
+        Calendar dateHeader = null;
+        Byte byteHeader = null;
+        StringBuffer buffer = null;
+        byte[] value = null;
+        byte[] result = null;
+        byte[] lengthArray = new byte[2];
+        int length;
+        HeaderSet headImpl = null;
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        headImpl = head;
+
+        try {
+            /*
+             * Determine if there is a connection ID to send.  If there is,
+             * then it should be the first header in the packet.
+             */
+            if ((headImpl.mConnectionID != null) && (headImpl.getHeader(HeaderSet.TARGET) == null)) {
+
+                out.write((byte)HeaderSet.CONNECTION_ID);
+                out.write(headImpl.mConnectionID);
+            }
+
+            // Count Header
+            intHeader = (Long)headImpl.getHeader(HeaderSet.COUNT);
+            if (intHeader != null) {
+                out.write((byte)HeaderSet.COUNT);
+                value = ObexHelper.convertToByteArray(intHeader.longValue());
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.COUNT, null);
+                }
+            }
+
+            // Name Header
+            stringHeader = (String)headImpl.getHeader(HeaderSet.NAME);
+            if (stringHeader != null) {
+                out.write((byte)HeaderSet.NAME);
+                value = ObexHelper.convertToUnicodeByteArray(stringHeader);
+                length = value.length + 3;
+                lengthArray[0] = (byte)(0xFF & (length >> 8));
+                lengthArray[1] = (byte)(0xFF & length);
+                out.write(lengthArray);
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.NAME, null);
+                }
+            }
+
+            // Type Header
+            stringHeader = (String)headImpl.getHeader(HeaderSet.TYPE);
+            if (stringHeader != null) {
+                out.write((byte)HeaderSet.TYPE);
+                try {
+                    value = stringHeader.getBytes("ISO8859_1");
+                } catch (UnsupportedEncodingException e) {
+                    throw e;
+                }
+
+                length = value.length + 4;
+                lengthArray[0] = (byte)(255 & (length >> 8));
+                lengthArray[1] = (byte)(255 & length);
+                out.write(lengthArray);
+                out.write(value);
+                out.write(0x00);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.TYPE, null);
+                }
+            }
+
+            // Length Header
+            intHeader = (Long)headImpl.getHeader(HeaderSet.LENGTH);
+            if (intHeader != null) {
+                out.write((byte)HeaderSet.LENGTH);
+                value = ObexHelper.convertToByteArray(intHeader.longValue());
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.LENGTH, null);
+                }
+            }
+
+            // Time ISO Header
+            dateHeader = (Calendar)headImpl.getHeader(HeaderSet.TIME_ISO_8601);
+            if (dateHeader != null) {
+
+                /*
+                 * The ISO Header should take the form YYYYMMDDTHHMMSSZ.  The
+                 * 'Z' will only be included if it is a UTC time.
+                 */
+                buffer = new StringBuffer();
+                int temp = dateHeader.get(Calendar.YEAR);
+                for (int i = temp; i < 1000; i = i * 10) {
+                    buffer.append("0");
+                }
+                buffer.append(temp);
+                temp = dateHeader.get(Calendar.MONTH);
+                if (temp < 10) {
+                    buffer.append("0");
+                }
+                buffer.append(temp);
+                temp = dateHeader.get(Calendar.DAY_OF_MONTH);
+                if (temp < 10) {
+                    buffer.append("0");
+                }
+                buffer.append(temp);
+                buffer.append("T");
+                temp = dateHeader.get(Calendar.HOUR_OF_DAY);
+                if (temp < 10) {
+                    buffer.append("0");
+                }
+                buffer.append(temp);
+                temp = dateHeader.get(Calendar.MINUTE);
+                if (temp < 10) {
+                    buffer.append("0");
+                }
+                buffer.append(temp);
+                temp = dateHeader.get(Calendar.SECOND);
+                if (temp < 10) {
+                    buffer.append("0");
+                }
+                buffer.append(temp);
+
+                if (dateHeader.getTimeZone().getID().equals("UTC")) {
+                    buffer.append("Z");
+                }
+
+                try {
+                    value = buffer.toString().getBytes("ISO8859_1");
+                } catch (UnsupportedEncodingException e) {
+                    throw e;
+                }
+
+                length = value.length + 3;
+                lengthArray[0] = (byte)(255 & (length >> 8));
+                lengthArray[1] = (byte)(255 & length);
+                out.write(HeaderSet.TIME_ISO_8601);
+                out.write(lengthArray);
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.TIME_ISO_8601, null);
+                }
+            }
+
+            // Time 4 Byte Header
+            dateHeader = (Calendar)headImpl.getHeader(HeaderSet.TIME_4_BYTE);
+            if (dateHeader != null) {
+                out.write(HeaderSet.TIME_4_BYTE);
+
+                /*
+                 * Need to call getTime() twice.  The first call will return
+                 * a java.util.Date object.  The second call returns the number
+                 * of milliseconds since January 1, 1970.  We need to convert
+                 * it to seconds since the TIME_4_BYTE expects the number of
+                 * seconds since January 1, 1970.
+                 */
+                value = ObexHelper.convertToByteArray(dateHeader.getTime().getTime() / 1000L);
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.TIME_4_BYTE, null);
+                }
+            }
+
+            // Description Header
+            stringHeader = (String)headImpl.getHeader(HeaderSet.DESCRIPTION);
+            if (stringHeader != null) {
+                out.write((byte)HeaderSet.DESCRIPTION);
+                value = ObexHelper.convertToUnicodeByteArray(stringHeader);
+                length = value.length + 3;
+                lengthArray[0] = (byte)(255 & (length >> 8));
+                lengthArray[1] = (byte)(255 & length);
+                out.write(lengthArray);
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.DESCRIPTION, null);
+                }
+            }
+
+            // Target Header
+            value = (byte[])headImpl.getHeader(HeaderSet.TARGET);
+            if (value != null) {
+                out.write((byte)HeaderSet.TARGET);
+                length = value.length + 3;
+                lengthArray[0] = (byte)(255 & (length >> 8));
+                lengthArray[1] = (byte)(255 & length);
+                out.write(lengthArray);
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.TARGET, null);
+                }
+            }
+
+            // HTTP Header
+            value = (byte[])headImpl.getHeader(HeaderSet.HTTP);
+            if (value != null) {
+                out.write((byte)HeaderSet.HTTP);
+                length = value.length + 3;
+                lengthArray[0] = (byte)(255 & (length >> 8));
+                lengthArray[1] = (byte)(255 & length);
+                out.write(lengthArray);
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.HTTP, null);
+                }
+            }
+
+            // Who Header
+            value = (byte[])headImpl.getHeader(HeaderSet.WHO);
+            if (value != null) {
+                out.write((byte)HeaderSet.WHO);
+                length = value.length + 3;
+                lengthArray[0] = (byte)(255 & (length >> 8));
+                lengthArray[1] = (byte)(255 & length);
+                out.write(lengthArray);
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.WHO, null);
+                }
+            }
+
+            // Connection ID Header
+            value = (byte[])headImpl.getHeader(HeaderSet.APPLICATION_PARAMETER);
+            if (value != null) {
+                out.write((byte)HeaderSet.APPLICATION_PARAMETER);
+                length = value.length + 3;
+                lengthArray[0] = (byte)(255 & (length >> 8));
+                lengthArray[1] = (byte)(255 & length);
+                out.write(lengthArray);
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.APPLICATION_PARAMETER, null);
+                }
+            }
+
+            // Object Class Header
+            value = (byte[])headImpl.getHeader(HeaderSet.OBJECT_CLASS);
+            if (value != null) {
+                out.write((byte)HeaderSet.OBJECT_CLASS);
+                length = value.length + 3;
+                lengthArray[0] = (byte)(255 & (length >> 8));
+                lengthArray[1] = (byte)(255 & length);
+                out.write(lengthArray);
+                out.write(value);
+                if (nullOut) {
+                    headImpl.setHeader(HeaderSet.OBJECT_CLASS, null);
+                }
+            }
+
+            // Check User Defined Headers
+            for (int i = 0; i < 16; i++) {
+
+                //Unicode String Header
+                stringHeader = (String)headImpl.getHeader(i + 0x30);
+                if (stringHeader != null) {
+                    out.write((byte)i + 0x30);
+                    value = ObexHelper.convertToUnicodeByteArray(stringHeader);
+                    length = value.length + 3;
+                    lengthArray[0] = (byte)(255 & (length >> 8));
+                    lengthArray[1] = (byte)(255 & length);
+                    out.write(lengthArray);
+                    out.write(value);
+                    if (nullOut) {
+                        headImpl.setHeader(i + 0x30, null);
+                    }
+                }
+
+                // Byte Sequence Header
+                value = (byte[])headImpl.getHeader(i + 0x70);
+                if (value != null) {
+                    out.write((byte)i + 0x70);
+                    length = value.length + 3;
+                    lengthArray[0] = (byte)(255 & (length >> 8));
+                    lengthArray[1] = (byte)(255 & length);
+                    out.write(lengthArray);
+                    out.write(value);
+                    if (nullOut) {
+                        headImpl.setHeader(i + 0x70, null);
+                    }
+                }
+
+                // Byte Header
+                byteHeader = (Byte)headImpl.getHeader(i + 0xB0);
+                if (byteHeader != null) {
+                    out.write((byte)i + 0xB0);
+                    out.write(byteHeader.byteValue());
+                    if (nullOut) {
+                        headImpl.setHeader(i + 0xB0, null);
+                    }
+                }
+
+                // Integer header
+                intHeader = (Long)headImpl.getHeader(i + 0xF0);
+                if (intHeader != null) {
+                    out.write((byte)i + 0xF0);
+                    out.write(ObexHelper.convertToByteArray(intHeader.longValue()));
+                    if (nullOut) {
+                        headImpl.setHeader(i + 0xF0, null);
+                    }
+                }
+            }
+
+            // Add the authentication challenge header
+            if (headImpl.mAuthChall != null) {
+                out.write((byte)HeaderSet.AUTH_CHALLENGE);
+                length = headImpl.mAuthChall.length + 3;
+                lengthArray[0] = (byte)(255 & (length >> 8));
+                lengthArray[1] = (byte)(255 & length);
+                out.write(lengthArray);
+                out.write(headImpl.mAuthChall);
+                if (nullOut) {
+                    headImpl.mAuthChall = null;
+                }
+            }
+
+            // Add the authentication response header
+            if (headImpl.mAuthResp != null) {
+                out.write((byte)HeaderSet.AUTH_RESPONSE);
+                length = headImpl.mAuthResp.length + 3;
+                lengthArray[0] = (byte)(255 & (length >> 8));
+                lengthArray[1] = (byte)(255 & length);
+                out.write(lengthArray);
+                out.write(headImpl.mAuthResp);
+                if (nullOut) {
+                    headImpl.mAuthResp = null;
+                }
+            }
+
+        } catch (IOException e) {
+        } finally {
+            result = out.toByteArray();
+            try {
+                out.close();
+            } catch (Exception ex) {
+            }
+        }
+
+        return result;
+
+    }
+
+    /**
+     * Determines where the maximum divide is between headers. This method is
+     * used by put and get operations to separate headers to a size that meets
+     * the max packet size allowed.
+     * @param headerArray the headers to separate
+     * @param start the starting index to search
+     * @param maxSize the maximum size of a packet
+     * @return the index of the end of the header block to send or -1 if the
+     *         header could not be divided because the header is too large
+     */
+    public static int findHeaderEnd(byte[] headerArray, int start, int maxSize) {
+
+        int fullLength = 0;
+        int lastLength = -1;
+        int index = start;
+        int length = 0;
+
+        while ((fullLength < maxSize) && (index < headerArray.length)) {
+            int headerID = (headerArray[index] < 0 ? headerArray[index] + 256 : headerArray[index]);
+            lastLength = fullLength;
+
+            switch (headerID & (0xC0)) {
+
+                case 0x00:
+                    // Fall through
+                case 0x40:
+
+                    index++;
+                    length = (headerArray[index] < 0 ? headerArray[index] + 256
+                            : headerArray[index]);
+                    length = length << 8;
+                    index++;
+                    length += (headerArray[index] < 0 ? headerArray[index] + 256
+                            : headerArray[index]);
+                    length -= 3;
+                    index++;
+                    index += length;
+                    fullLength += length + 3;
+                    break;
+
+                case 0x80:
+
+                    index++;
+                    index++;
+                    fullLength += 2;
+                    break;
+
+                case 0xC0:
+
+                    index += 5;
+                    fullLength += 5;
+                    break;
+
+            }
+
+        }
+
+        /*
+         * Determine if this is the last header or not
+         */
+        if (lastLength == 0) {
+            /*
+             * Since this is the last header, check to see if the size of this
+             * header is less then maxSize.  If it is, return the length of the
+             * header, otherwise return -1.  The length of the header is
+             * returned since it would be the start of the next header
+             */
+            if (fullLength < maxSize) {
+                return headerArray.length;
+            } else {
+                return -1;
+            }
+        } else {
+            return lastLength + start;
+        }
+    }
+
+    /**
+     * Converts the byte array to a long.
+     * @param b the byte array to convert to a long
+     * @return the byte array as a long
+     */
+    public static long convertToLong(byte[] b) {
+        long result = 0;
+        long value = 0;
+        long power = 0;
+
+        for (int i = (b.length - 1); i >= 0; i--) {
+            value = b[i];
+            if (value < 0) {
+                value += 256;
+            }
+
+            result = result | (value << power);
+            power += 8;
+        }
+
+        return result;
+    }
+
+    /**
+     * Converts the long to a 4 byte array. The long must be non negative.
+     * @param l the long to convert
+     * @return a byte array that is the same as the long
+     */
+    public static byte[] convertToByteArray(long l) {
+        byte[] b = new byte[4];
+
+        b[0] = (byte)(255 & (l >> 24));
+        b[1] = (byte)(255 & (l >> 16));
+        b[2] = (byte)(255 & (l >> 8));
+        b[3] = (byte)(255 & l);
+
+        return b;
+    }
+
+    /**
+     * Converts the String to a UNICODE byte array. It will also add the ending
+     * null characters to the end of the string.
+     * @param s the string to convert
+     * @return the unicode byte array of the string
+     */
+    public static byte[] convertToUnicodeByteArray(String s) {
+        if (s == null) {
+            return null;
+        }
+
+        char c[] = s.toCharArray();
+        byte[] result = new byte[(c.length * 2) + 2];
+        for (int i = 0; i < c.length; i++) {
+            result[(i * 2)] = (byte)(c[i] >> 8);
+            result[((i * 2) + 1)] = (byte)c[i];
+        }
+
+        // Add the UNICODE null character
+        result[result.length - 2] = 0;
+        result[result.length - 1] = 0;
+
+        return result;
+    }
+
+    /**
+     * Retrieves the value from the byte array for the tag value specified. The
+     * array should be of the form Tag - Length - Value triplet.
+     * @param tag the tag to retrieve from the byte array
+     * @param triplet the byte sequence containing the tag length value form
+     * @return the value of the specified tag
+     */
+    public static byte[] getTagValue(byte tag, byte[] triplet) {
+
+        int index = findTag(tag, triplet);
+        if (index == -1) {
+            return null;
+        }
+
+        index++;
+        int length = triplet[index] & 0xFF;
+
+        byte[] result = new byte[length];
+        index++;
+        System.arraycopy(triplet, index, result, 0, length);
+
+        return result;
+    }
+
+    /**
+     * Finds the index that starts the tag value pair in the byte array provide.
+     * @param tag the tag to look for
+     * @param value the byte array to search
+     * @return the starting index of the tag or -1 if the tag could not be found
+     */
+    public static int findTag(byte tag, byte[] value) {
+        int length = 0;
+
+        if (value == null) {
+            return -1;
+        }
+
+        int index = 0;
+
+        while ((index < value.length) && (value[index] != tag)) {
+            length = value[index + 1] & 0xFF;
+            index += length + 2;
+        }
+
+        if (index >= value.length) {
+            return -1;
+        }
+
+        return index;
+    }
+
+    /**
+     * Converts the byte array provided to a unicode string.
+     * @param b the byte array to convert to a string
+     * @param includesNull determine if the byte string provided contains the
+     *        UNICODE null character at the end or not; if it does, it will be
+     *        removed
+     * @return a Unicode string
+     * @throws IllegalArgumentException if the byte array has an odd length
+     */
+    public static String convertToUnicode(byte[] b, boolean includesNull) {
+        if (b == null || b.length == 0) {
+            return null;
+        }
+        int arrayLength = b.length;
+        if (!((arrayLength % 2) == 0)) {
+            throw new IllegalArgumentException("Byte array not of a valid form");
+        }
+        arrayLength = (arrayLength >> 1);
+        if (includesNull) {
+            arrayLength -= 1;
+        }
+
+        char[] c = new char[arrayLength];
+        for (int i = 0; i < arrayLength; i++) {
+            int upper = b[2 * i];
+            int lower = b[(2 * i) + 1];
+            if (upper < 0) {
+                upper += 256;
+            }
+            if (lower < 0) {
+                lower += 256;
+            }
+
+            c[i] = (char)((upper << 8) | lower);
+        }
+
+        return new String(c);
+    }
+
+    /**
+     * Compute the MD5 hash of the byte array provided. Does not accumulate
+     * input.
+     * @param in the byte array to hash
+     * @return the MD5 hash of the byte array
+     */
+    public static byte[] computeMd5Hash(byte[] in) {
+        Md5MessageDigest md5 = new Md5MessageDigest();
+        return md5.digest(in);
+    }
+
+    /**
+     * Computes an authentication challenge header.
+     * @param nonce the challenge that will be provided to the peer; the
+     *        challenge must be 16 bytes long
+     * @param realm a short description that describes what password to use
+     * @param access if <code>true</code> then full access will be granted if
+     *        successful; if <code>false</code> then read only access will be
+     *        granted if successful
+     * @param userID if <code>true</code>, a user ID is required in the reply;
+     *        if <code>false</code>, no user ID is required
+     * @throws IllegalArgumentException if the challenge is not 16 bytes long;
+     *         if the realm can not be encoded in less then 255 bytes
+     * @throws IOException if the encoding scheme ISO 8859-1 is not supported
+     */
+    public static byte[] computeAuthenticationChallenge(byte[] nonce, String realm, boolean access,
+            boolean userID) throws IOException {
+        byte[] authChall = null;
+
+        if (nonce.length != 16) {
+            throw new IllegalArgumentException("Nonce must be 16 bytes long");
+        }
+
+        /*
+         * The authentication challenge is a byte sequence of the following form
+         * byte 0: 0x00 - the tag for the challenge
+         * byte 1: 0x10 - the length of the challenge; must be 16
+         * byte 2-17: the authentication challenge
+         * byte 18: 0x01 - the options tag; this is optional in the spec, but
+         *                 we are going to include it in every message
+         * byte 19: 0x01 - length of the options; must be 1
+         * byte 20: the value of the options; bit 0 is set if user ID is
+         *          required; bit 1 is set if access mode is read only
+         * byte 21: 0x02 - the tag for authentication realm; only included if
+         *                 an authentication realm is specified
+         * byte 22: the length of the authentication realm; only included if
+         *          the authentication realm is specified
+         * byte 23: the encoding scheme of the authentication realm; we will use
+         *          the ISO 8859-1 encoding scheme since it is part of the KVM
+         * byte 24 & up: the realm if one is specified.
+         */
+        if (realm == null) {
+            authChall = new byte[21];
+        } else {
+            if (realm.length() >= 255) {
+                throw new IllegalArgumentException("Realm must be less then 255 bytes");
+            }
+            authChall = new byte[24 + realm.length()];
+            authChall[21] = 0x02;
+            authChall[22] = (byte)(realm.length() + 1);
+            authChall[23] = 0x01; // ISO 8859-1 Encoding
+            System.arraycopy(realm.getBytes("ISO8859_1"), 0, authChall, 24, realm.length());
+        }
+
+        // Include the nonce field in the header
+        authChall[0] = 0x00;
+        authChall[1] = 0x10;
+        System.arraycopy(nonce, 0, authChall, 2, 16);
+
+        // Include the options header
+        authChall[18] = 0x01;
+        authChall[19] = 0x01;
+        authChall[20] = 0x00;
+
+        if (!access) {
+            authChall[20] = (byte)(authChall[20] | 0x02);
+        }
+        if (userID) {
+            authChall[20] = (byte)(authChall[20] | 0x01);
+        }
+
+        return authChall;
+    }
+}
diff --git a/obex/javax/obex/ObexSession.java b/obex/javax/obex/ObexSession.java
new file mode 100644
index 0000000..a7daeb5
--- /dev/null
+++ b/obex/javax/obex/ObexSession.java
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.IOException;
+
+/**
+ * The <code>ObexSession</code> interface characterizes the term
+ * "OBEX Connection" as defined in the IrDA Object Exchange Protocol v1.2, which
+ * could be the server-side view of an OBEX connection, or the client-side view
+ * of the same connection, which is established by server's accepting of a
+ * client issued "CONNECT".
+ * <P>
+ * This interface serves as the common super class for
+ * <CODE>ClientSession</CODE> and <CODE>ServerSession</CODE>.
+ * @hide
+ */
+public class ObexSession {
+
+    protected Authenticator mAuthenticator;
+
+    protected byte[] mChallengeDigest;
+
+    /**
+     * Called when the server received an authentication challenge header. This
+     * will cause the authenticator to handle the authentication challenge.
+     * @param header the header with the authentication challenge
+     * @return <code>true</code> if the last request should be resent;
+     *         <code>false</code> if the last request should not be resent
+     * @throws IOException
+     */
+    public boolean handleAuthChall(HeaderSet header) throws IOException {
+        if (mAuthenticator == null) {
+            return false;
+        }
+
+        /*
+         * An authentication challenge is made up of one required and two
+         * optional tag length value triplets. The tag 0x00 is required to be in
+         * the authentication challenge and it represents the challenge digest
+         * that was received. The tag 0x01 is the options tag. This tag tracks
+         * if user ID is required and if full access will be granted. The tag
+         * 0x02 is the realm, which provides a description of which user name
+         * and password to use.
+         */
+        byte[] challenge = ObexHelper.getTagValue((byte)0x00, header.mAuthChall);
+        byte[] option = ObexHelper.getTagValue((byte)0x01, header.mAuthChall);
+        byte[] description = ObexHelper.getTagValue((byte)0x02, header.mAuthChall);
+
+        String realm = null;
+        if (description != null) {
+            byte[] realmString = new byte[description.length - 1];
+            System.arraycopy(description, 1, realmString, 0, realmString.length);
+
+            switch (description[0] & 0xFF) {
+
+                case ObexHelper.OBEX_AUTH_REALM_CHARSET_ASCII:
+                    // ASCII encoding
+                    // Fall through
+                case ObexHelper.OBEX_AUTH_REALM_CHARSET_ISO_8859_1:
+                    // ISO-8859-1 encoding
+                    try {
+                        realm = new String(realmString, "ISO8859_1");
+                    } catch (Exception e) {
+                        throw new IOException("Unsupported Encoding Scheme");
+                    }
+                    break;
+
+                case ObexHelper.OBEX_AUTH_REALM_CHARSET_UNICODE:
+                    // UNICODE Encoding
+                    realm = ObexHelper.convertToUnicode(realmString, false);
+                    break;
+
+                default:
+                    throw new IOException("Unsupported Encoding Scheme");
+            }
+        }
+
+        boolean isUserIDRequired = false;
+        boolean isFullAccess = true;
+        if (option != null) {
+            if ((option[0] & 0x01) != 0) {
+                isUserIDRequired = true;
+            }
+
+            if ((option[0] & 0x02) != 0) {
+                isFullAccess = false;
+            }
+        }
+
+        PasswordAuthentication result = null;
+        header.mAuthChall = null;
+
+        try {
+            result = mAuthenticator
+                    .onAuthenticationChallenge(realm, isUserIDRequired, isFullAccess);
+        } catch (Exception e) {
+            return false;
+        }
+
+        /*
+         * If no password is provided then we not resent the request
+         */
+        if (result == null) {
+            return false;
+        }
+
+        byte[] password = result.getPassword();
+        if (password == null) {
+            return false;
+        }
+
+        byte[] userName = result.getUserName();
+
+        /*
+         * Create the authentication response header. It includes 1 required and
+         * 2 option tag length value triples. The required triple has a tag of
+         * 0x00 and is the response digest. The first optional tag is 0x01 and
+         * represents the user ID. If no user ID is provided, then no user ID
+         * will be sent. The second optional tag is 0x02 and is the challenge
+         * that was received. This will always be sent
+         */
+        if (userName != null) {
+            header.mAuthResp = new byte[38 + userName.length];
+            header.mAuthResp[36] = (byte)0x01;
+            header.mAuthResp[37] = (byte)userName.length;
+            System.arraycopy(userName, 0, header.mAuthResp, 38, userName.length);
+        } else {
+            header.mAuthResp = new byte[36];
+        }
+
+        // Create the secret String
+        byte[] digest = new byte[challenge.length + password.length + 1];
+        System.arraycopy(challenge, 0, digest, 0, challenge.length);
+        // Insert colon between challenge and password
+        digest[challenge.length] = (byte)0x3A;
+        System.arraycopy(password, 0, digest, challenge.length + 1, password.length);
+
+        // Add the Response Digest
+        header.mAuthResp[0] = (byte)0x00;
+        header.mAuthResp[1] = (byte)0x10;
+
+        System.arraycopy(ObexHelper.computeMd5Hash(digest), 0, header.mAuthResp, 2, 16);
+
+        // Add the challenge
+        header.mAuthResp[18] = (byte)0x02;
+        header.mAuthResp[19] = (byte)0x10;
+        System.arraycopy(challenge, 0, header.mAuthResp, 20, 16);
+
+        return true;
+    }
+
+    /**
+     * Called when the server received an authentication response header. This
+     * will cause the authenticator to handle the authentication response.
+     * @param authResp the authentication response
+     * @return <code>true</code> if the response passed; <code>false</code> if
+     *         the response failed
+     */
+    public boolean handleAuthResp(byte[] authResp) {
+        if (mAuthenticator == null) {
+            return false;
+        }
+        // get the correct password from the application
+        byte[] correctPassword = mAuthenticator.onAuthenticationResponse(ObexHelper.getTagValue(
+                (byte)0x01, authResp));
+        if (correctPassword == null) {
+            return false;
+        }
+
+        byte[] temp = new byte[correctPassword.length + 16];
+
+        System.arraycopy(mChallengeDigest, 0, temp, 0, 16);
+        System.arraycopy(correctPassword, 0, temp, 16, correctPassword.length);
+
+        byte[] correctResponse = ObexHelper.computeMd5Hash(temp);
+        byte[] actualResponse = ObexHelper.getTagValue((byte)0x00, authResp);
+
+        // compare the MD5 hash array .
+        for (int i = 0; i < 16; i++) {
+            if (correctResponse[i] != actualResponse[i]) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+}
diff --git a/obex/javax/obex/ObexTransport.java b/obex/javax/obex/ObexTransport.java
new file mode 100644
index 0000000..445e267
--- /dev/null
+++ b/obex/javax/obex/ObexTransport.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * The <code>ObexTransport</code> interface defines the underlying transport
+ * connection which carries the OBEX protocol( such as TCP, RFCOMM device file
+ * exposed by Bluetooth or USB in kernel, RFCOMM socket emulated in Android
+ * platform, Irda). This interface provides an abstract layer to be used by the
+ * <code>ObexConnection</code>. Each kind of medium shall have its own
+ * implementation to wrap and follow the same interface.
+ * <P>
+ * See section 1.2.2 of IrDA Object Exchange Protocol specification.
+ * <P>
+ * Different kind of medium may have different construction - for example, the
+ * RFCOMM device file medium may be constructed from a file descriptor or simply
+ * a string while the TCP medium usually from a socket.
+ * @hide
+ */
+public interface ObexTransport {
+
+    void create() throws IOException;
+
+    void listen() throws IOException;
+
+    void close() throws IOException;
+
+    void connect() throws IOException;
+
+    void disconnect() throws IOException;
+
+    InputStream openInputStream() throws IOException;
+
+    OutputStream openOutputStream() throws IOException;
+
+    DataInputStream openDataInputStream() throws IOException;
+
+    DataOutputStream openDataOutputStream() throws IOException;
+
+}
diff --git a/obex/javax/obex/Operation.java b/obex/javax/obex/Operation.java
new file mode 100644
index 0000000..20653f2
--- /dev/null
+++ b/obex/javax/obex/Operation.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * The <code>Operation</code> interface provides ways to manipulate a single
+ * OBEX PUT or GET operation. The implementation of this interface sends OBEX
+ * packets as they are built. If during the operation the peer in the operation
+ * ends the operation, an <code>IOException</code> is thrown on the next read
+ * from the input stream, write to the output stream, or call to
+ * <code>sendHeaders()</code>.
+ * <P>
+ * <STRONG>Definition of methods inherited from <code>ContentConnection</code>
+ * </STRONG>
+ * <P>
+ * <code>getEncoding()</code> will always return <code>null</code>. <BR>
+ * <code>getLength()</code> will return the length specified by the OBEX Length
+ * header or -1 if the OBEX Length header was not included. <BR>
+ * <code>getType()</code> will return the value specified in the OBEX Type
+ * header or <code>null</code> if the OBEX Type header was not included.<BR>
+ * <P>
+ * <STRONG>How Headers are Handled</STRONG>
+ * <P>
+ * As headers are received, they may be retrieved through the
+ * <code>getReceivedHeaders()</code> method. If new headers are set during the
+ * operation, the new headers will be sent during the next packet exchange.
+ * <P>
+ * <STRONG>PUT example</STRONG>
+ * <P>
+ * <PRE>
+ * void putObjectViaOBEX(ClientSession conn, HeaderSet head, byte[] obj) throws IOException {
+ *     // Include the length header
+ *     head.setHeader(head.LENGTH, new Long(obj.length));
+ *     // Initiate the PUT request
+ *     Operation op = conn.put(head);
+ *     // Open the output stream to put the object to it
+ *     DataOutputStream out = op.openDataOutputStream();
+ *     // Send the object to the server
+ *     out.write(obj);
+ *     // End the transaction
+ *     out.close();
+ *     op.close();
+ * }
+ * </PRE>
+ * <P>
+ * <STRONG>GET example</STRONG>
+ * <P>
+ * <PRE>
+ * byte[] getObjectViaOBEX(ClientSession conn, HeaderSet head) throws IOException {
+ *     // Send the initial GET request to the server
+ *     Operation op = conn.get(head);
+ *     // Retrieve the length of the object being sent back
+ *     int length = op.getLength();
+ *     // Create space for the object
+ *     byte[] obj = new byte[length];
+ *     // Get the object from the input stream
+ *     DataInputStream in = trans.openDataInputStream();
+ *     in.read(obj);
+ *     // End the transaction
+ *     in.close();
+ *     op.close();
+ *     return obj;
+ * }
+ * </PRE>
+ *
+ * <H3>Client PUT Operation Flow</H3> For PUT operations, a call to
+ * <code>close()</code> the <code>OutputStream</code> returned from
+ * <code>openOutputStream()</code> or <code>openDataOutputStream()</code> will
+ * signal that the request is done. (In OBEX terms, the End-Of-Body header
+ * should be sent and the final bit in the request will be set.) At this point,
+ * the reply from the server may begin to be processed. A call to
+ * <code>getResponseCode()</code> will do an implicit close on the
+ * <code>OutputStream</code> and therefore signal that the request is done.
+ * <H3>Client GET Operation Flow</H3> For GET operation, a call to
+ * <code>openInputStream()</code> or <code>openDataInputStream()</code> will
+ * signal that the request is done. (In OBEX terms, the final bit in the request
+ * will be set.) A call to <code>getResponseCode()</code> will cause an implicit
+ * close on the <code>InputStream</code>. No further data may be read at this
+ * point.
+ * @hide
+ */
+public interface Operation {
+
+    /**
+     * Sends an ABORT message to the server. By calling this method, the
+     * corresponding input and output streams will be closed along with this
+     * object. No headers are sent in the abort request. This will end the
+     * operation since <code>close()</code> will be called by this method.
+     * @throws IOException if the transaction has already ended or if an OBEX
+     *         server calls this method
+     */
+    void abort() throws IOException;
+
+    /**
+     * Returns the headers that have been received during the operation.
+     * Modifying the object returned has no effect on the headers that are sent
+     * or retrieved.
+     * @return the headers received during this <code>Operation</code>
+     * @throws IOException if this <code>Operation</code> has been closed
+     */
+    HeaderSet getReceivedHeader() throws IOException;
+
+    /**
+     * Specifies the headers that should be sent in the next OBEX message that
+     * is sent.
+     * @param headers the headers to send in the next message
+     * @throws IOException if this <code>Operation</code> has been closed or the
+     *         transaction has ended and no further messages will be exchanged
+     * @throws IllegalArgumentException if <code>headers</code> was not created
+     *         by a call to <code>ServerRequestHandler.createHeaderSet()</code>
+     *         or <code>ClientSession.createHeaderSet()</code>
+     * @throws NullPointerException if <code>headers</code> if <code>null</code>
+     */
+    void sendHeaders(HeaderSet headers) throws IOException;
+
+    /**
+     * Returns the response code received from the server. Response codes are
+     * defined in the <code>ResponseCodes</code> class.
+     * @see ResponseCodes
+     * @return the response code retrieved from the server
+     * @throws IOException if an error occurred in the transport layer during
+     *         the transaction; if this object was created by an OBEX server
+     */
+    int getResponseCode() throws IOException;
+
+    String getEncoding();
+
+    long getLength();
+
+    String getType();
+
+    InputStream openInputStream() throws IOException;
+
+    DataInputStream openDataInputStream() throws IOException;
+
+    OutputStream openOutputStream() throws IOException;
+
+    DataOutputStream openDataOutputStream() throws IOException;
+
+    void close() throws IOException;
+
+    int getMaxPacketSize();
+}
diff --git a/obex/javax/obex/PasswordAuthentication.java b/obex/javax/obex/PasswordAuthentication.java
new file mode 100644
index 0000000..326b1ff
--- /dev/null
+++ b/obex/javax/obex/PasswordAuthentication.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+/**
+ * This class holds user name and password combinations.
+ * @hide
+ */
+public final class PasswordAuthentication {
+
+    private byte[] mUserName;
+
+    private final byte[] mPassword;
+
+    /**
+     * Creates a new <code>PasswordAuthentication</code> with the user name and
+     * password provided.
+     * @param userName the user name to include; this may be <code>null</code>
+     * @param password the password to include in the response
+     * @throws NullPointerException if <code>password</code> is
+     *         <code>null</code>
+     */
+    public PasswordAuthentication(final byte[] userName, final byte[] password) {
+        if (userName != null) {
+            mUserName = new byte[userName.length];
+            System.arraycopy(userName, 0, mUserName, 0, userName.length);
+        }
+
+        mPassword = new byte[password.length];
+        System.arraycopy(password, 0, mPassword, 0, password.length);
+    }
+
+    /**
+     * Retrieves the user name that was specified in the constructor. The user
+     * name may be <code>null</code>.
+     * @return the user name
+     */
+    public byte[] getUserName() {
+        return mUserName;
+    }
+
+    /**
+     * Retrieves the password.
+     * @return the password
+     */
+    public byte[] getPassword() {
+        return mPassword;
+    }
+}
diff --git a/obex/javax/obex/PrivateInputStream.java b/obex/javax/obex/PrivateInputStream.java
new file mode 100644
index 0000000..5daee72
--- /dev/null
+++ b/obex/javax/obex/PrivateInputStream.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.InputStream;
+import java.io.IOException;
+
+/**
+ * This object provides an input stream to the Operation objects used in this
+ * package.
+ * @hide
+ */
+public final class PrivateInputStream extends InputStream {
+
+    private BaseStream mParent;
+
+    private byte[] mData;
+
+    private int mIndex;
+
+    private boolean mOpen;
+
+    /**
+     * Creates an input stream for the <code>Operation</code> to read from
+     * @param p the connection this input stream is for
+     */
+    public PrivateInputStream(BaseStream p) {
+        mParent = p;
+        mData = new byte[0];
+        mIndex = 0;
+        mOpen = true;
+    }
+
+    /**
+     * Returns the number of bytes that can be read (or skipped over) from this
+     * input stream without blocking by the next caller of a method for this
+     * input stream. The next caller might be the same thread or or another
+     * thread.
+     * @return the number of bytes that can be read from this input stream
+     *         without blocking
+     * @throws IOException if an I/O error occurs
+     */
+    @Override
+    public synchronized int available() throws IOException {
+        ensureOpen();
+        return mData.length - mIndex;
+    }
+
+    /**
+     * Reads the next byte of data from the input stream. The value byte is
+     * returned as an int in the range 0 to 255. If no byte is available because
+     * the end of the stream has been reached, the value -1 is returned. This
+     * method blocks until input data is available, the end of the stream is
+     * detected, or an exception is thrown.
+     * @return the byte read from the input stream or -1 if it reaches the end of
+     *         stream
+     * @throws IOException if an I/O error occurs
+     */
+    @Override
+    public synchronized int read() throws IOException {
+        ensureOpen();
+        while (mData.length == mIndex) {
+            if (!mParent.continueOperation(true, true)) {
+                return -1;
+            }
+        }
+        return (mData[mIndex++] & 0xFF);
+    }
+
+    @Override
+    public int read(byte[] b) throws IOException {
+        return read(b, 0, b.length);
+    }
+
+    @Override
+    public synchronized int read(byte[] b, int offset, int length) throws IOException {
+
+        if (b == null) {
+            throw new IOException("buffer is null");
+        }
+        if ((offset | length) < 0 || length > b.length - offset) {
+            throw new ArrayIndexOutOfBoundsException("index outof bound");
+        }
+        ensureOpen();
+
+        int currentDataLength = mData.length - mIndex;
+        int remainReadLength = length;
+        int offset1 = offset;
+        int result = 0;
+
+        while (currentDataLength <= remainReadLength) {
+            System.arraycopy(mData, mIndex, b, offset1, currentDataLength);
+            mIndex += currentDataLength;
+            offset1 += currentDataLength;
+            result += currentDataLength;
+            remainReadLength -= currentDataLength;
+
+            if (!mParent.continueOperation(true, true)) {
+                return result == 0 ? -1 : result;
+            }
+            currentDataLength = mData.length - mIndex;
+        }
+        if (remainReadLength > 0) {
+            System.arraycopy(mData, mIndex, b, offset1, remainReadLength);
+            mIndex += remainReadLength;
+            result += remainReadLength;
+        }
+        return result;
+    }
+
+    /**
+     * Allows the <code>OperationImpl</code> thread to add body data to the
+     * input stream.
+     * @param body the data to add to the stream
+     * @param start the start of the body to array to copy
+     */
+    public synchronized void writeBytes(byte[] body, int start) {
+
+        int length = (body.length - start) + (mData.length - mIndex);
+        byte[] temp = new byte[length];
+
+        System.arraycopy(mData, mIndex, temp, 0, mData.length - mIndex);
+        System.arraycopy(body, start, temp, mData.length - mIndex, body.length - start);
+
+        mData = temp;
+        mIndex = 0;
+        notifyAll();
+    }
+
+    /**
+     * Verifies that this stream is open
+     * @throws IOException if the stream is not open
+     */
+    private void ensureOpen() throws IOException {
+        mParent.ensureOpen();
+        if (!mOpen) {
+            throw new IOException("Input stream is closed");
+        }
+    }
+
+    /**
+     * Closes the input stream. If the input stream is already closed, do
+     * nothing.
+     * @throws IOException this will never happen
+     */
+    @Override
+    public void close() throws IOException {
+        mOpen = false;
+        mParent.streamClosed(true);
+    }
+}
diff --git a/obex/javax/obex/PrivateOutputStream.java b/obex/javax/obex/PrivateOutputStream.java
new file mode 100644
index 0000000..ca420af
--- /dev/null
+++ b/obex/javax/obex/PrivateOutputStream.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.ByteArrayOutputStream;
+
+/**
+ * This object provides an output stream to the Operation objects used in this
+ * package.
+ * @hide
+ */
+public final class PrivateOutputStream extends OutputStream {
+
+    private BaseStream mParent;
+
+    private ByteArrayOutputStream mArray;
+
+    private boolean mOpen;
+
+    private int mMaxPacketSize;
+
+    /**
+     * Creates an empty <code>PrivateOutputStream</code> to write to.
+     * @param p the connection that this stream runs over
+     */
+    public PrivateOutputStream(BaseStream p, int maxSize) {
+        mParent = p;
+        mArray = new ByteArrayOutputStream();
+        mMaxPacketSize = maxSize;
+        mOpen = true;
+    }
+
+    /**
+     * Determines how many bytes have been written to the output stream.
+     * @return the number of bytes written to the output stream
+     */
+    public int size() {
+        return mArray.size();
+    }
+
+    /**
+     * Writes the specified byte to this output stream. The general contract for
+     * write is that one byte is written to the output stream. The byte to be
+     * written is the eight low-order bits of the argument b. The 24 high-order
+     * bits of b are ignored.
+     * @param b the byte to write
+     * @throws IOException if an I/O error occurs
+     */
+    @Override
+    public synchronized void write(int b) throws IOException {
+        ensureOpen();
+        mParent.ensureNotDone();
+        mArray.write(b);
+        if (mArray.size() == mMaxPacketSize) {
+            mParent.continueOperation(true, false);
+        }
+    }
+
+    @Override
+    public void write(byte[] buffer) throws IOException {
+        write(buffer, 0, buffer.length);
+    }
+
+    @Override
+    public synchronized void write(byte[] buffer, int offset, int count) throws IOException {
+        int offset1 = offset;
+        int remainLength = count;
+
+        if (buffer == null) {
+            throw new IOException("buffer is null");
+        }
+        if ((offset | count) < 0 || count > buffer.length - offset) {
+            throw new IndexOutOfBoundsException("index outof bound");
+        }
+
+        ensureOpen();
+        mParent.ensureNotDone();
+        if (count < mMaxPacketSize) {
+            mArray.write(buffer, offset, count);
+        } else {
+            while (remainLength >= mMaxPacketSize) {
+                mArray.write(buffer, offset1, mMaxPacketSize);
+                offset1 += mMaxPacketSize;
+                remainLength = count - offset1;
+                mParent.continueOperation(true, false);
+            }
+            if (remainLength > 0) {
+                mArray.write(buffer, offset1, remainLength);
+            }
+        }
+    }
+
+    /**
+     * Reads the bytes that have been written to this stream.
+     * @param size the size of the array to return
+     * @return the byte array that is written
+     */
+    public synchronized byte[] readBytes(int size) {
+        if (mArray.size() > 0) {
+            byte[] temp = mArray.toByteArray();
+            mArray.reset();
+            byte[] result = new byte[size];
+            System.arraycopy(temp, 0, result, 0, size);
+            if (temp.length != size) {
+                mArray.write(temp, size, temp.length - size);
+            }
+            return result;
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * Verifies that this stream is open
+     * @throws IOException if the stream is not open
+     */
+    private void ensureOpen() throws IOException {
+        mParent.ensureOpen();
+        if (!mOpen) {
+            throw new IOException("Output stream is closed");
+        }
+    }
+
+    /**
+     * Closes the output stream. If the input stream is already closed, do
+     * nothing.
+     * @throws IOException this will never happen
+     */
+    @Override
+    public void close() throws IOException {
+        mOpen = false;
+        mParent.streamClosed(false);
+    }
+
+    /**
+     * Determines if the connection is closed
+     * @return <code>true</code> if the connection is closed; <code>false</code>
+     *         if the connection is open
+     */
+    public boolean isClosed() {
+        return !mOpen;
+    }
+}
diff --git a/obex/javax/obex/ResponseCodes.java b/obex/javax/obex/ResponseCodes.java
new file mode 100644
index 0000000..a2b9a37
--- /dev/null
+++ b/obex/javax/obex/ResponseCodes.java
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+/**
+ * The <code>ResponseCodes</code> class contains the list of valid response
+ * codes a server may send to a client.
+ * <P>
+ * <STRONG>IMPORTANT NOTE</STRONG>
+ * <P>
+ * The values in this interface represent the values defined in the IrOBEX
+ * specification, which is different with the HTTP specification.
+ * <P>
+ * <code>OBEX_DATABASE_FULL</code> and <code>OBEX_DATABASE_LOCKED</code> require
+ * further description since they are not defined in HTTP. The server will send
+ * an <code>OBEX_DATABASE_FULL</code> message when the client requests that
+ * something be placed into a database but the database is full (cannot take
+ * more data). <code>OBEX_DATABASE_LOCKED</code> will be returned when the
+ * client wishes to access a database, database table, or database record that
+ * has been locked.
+ * @hide
+ */
+public final class ResponseCodes {
+
+    /**
+     * Defines the OBEX CONTINUE response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_CONTINUE</code> is 0x90 (144).
+     */
+    public static final int OBEX_HTTP_CONTINUE = 0x90;
+
+    /**
+     * Defines the OBEX SUCCESS response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_OK</code> is 0xA0 (160).
+     */
+    public static final int OBEX_HTTP_OK = 0xA0;
+
+    /**
+     * Defines the OBEX CREATED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_CREATED</code> is 0xA1 (161).
+     */
+    public static final int OBEX_HTTP_CREATED = 0xA1;
+
+    /**
+     * Defines the OBEX ACCEPTED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_ACCEPTED</code> is 0xA2 (162).
+     */
+    public static final int OBEX_HTTP_ACCEPTED = 0xA2;
+
+    /**
+     * Defines the OBEX NON-AUTHORITATIVE INFORMATION response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_NOT_AUTHORITATIVE</code> is 0xA3 (163).
+     */
+    public static final int OBEX_HTTP_NOT_AUTHORITATIVE = 0xA3;
+
+    /**
+     * Defines the OBEX NO CONTENT response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_NO_CONTENT</code> is 0xA4 (164).
+     */
+    public static final int OBEX_HTTP_NO_CONTENT = 0xA4;
+
+    /**
+     * Defines the OBEX RESET CONTENT response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_RESET</code> is 0xA5 (165).
+     */
+    public static final int OBEX_HTTP_RESET = 0xA5;
+
+    /**
+     * Defines the OBEX PARTIAL CONTENT response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_PARTIAL</code> is 0xA6 (166).
+     */
+    public static final int OBEX_HTTP_PARTIAL = 0xA6;
+
+    /**
+     * Defines the OBEX MULTIPLE_CHOICES response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_MULT_CHOICE</code> is 0xB0 (176).
+     */
+    public static final int OBEX_HTTP_MULT_CHOICE = 0xB0;
+
+    /**
+     * Defines the OBEX MOVED PERMANENTLY response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_MOVED_PERM</code> is 0xB1 (177).
+     */
+    public static final int OBEX_HTTP_MOVED_PERM = 0xB1;
+
+    /**
+     * Defines the OBEX MOVED TEMPORARILY response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_MOVED_TEMP</code> is 0xB2 (178).
+     */
+    public static final int OBEX_HTTP_MOVED_TEMP = 0xB2;
+
+    /**
+     * Defines the OBEX SEE OTHER response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_SEE_OTHER</code> is 0xB3 (179).
+     */
+    public static final int OBEX_HTTP_SEE_OTHER = 0xB3;
+
+    /**
+     * Defines the OBEX NOT MODIFIED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_NOT_MODIFIED</code> is 0xB4 (180).
+     */
+    public static final int OBEX_HTTP_NOT_MODIFIED = 0xB4;
+
+    /**
+     * Defines the OBEX USE PROXY response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_USE_PROXY</code> is 0xB5 (181).
+     */
+    public static final int OBEX_HTTP_USE_PROXY = 0xB5;
+
+    /**
+     * Defines the OBEX BAD REQUEST response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_BAD_REQUEST</code> is 0xC0 (192).
+     */
+    public static final int OBEX_HTTP_BAD_REQUEST = 0xC0;
+
+    /**
+     * Defines the OBEX UNAUTHORIZED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_UNAUTHORIZED</code> is 0xC1 (193).
+     */
+    public static final int OBEX_HTTP_UNAUTHORIZED = 0xC1;
+
+    /**
+     * Defines the OBEX PAYMENT REQUIRED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_PAYMENT_REQUIRED</code> is 0xC2 (194).
+     */
+    public static final int OBEX_HTTP_PAYMENT_REQUIRED = 0xC2;
+
+    /**
+     * Defines the OBEX FORBIDDEN response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_FORBIDDEN</code> is 0xC3 (195).
+     */
+    public static final int OBEX_HTTP_FORBIDDEN = 0xC3;
+
+    /**
+     * Defines the OBEX NOT FOUND response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_NOT_FOUND</code> is 0xC4 (196).
+     */
+    public static final int OBEX_HTTP_NOT_FOUND = 0xC4;
+
+    /**
+     * Defines the OBEX METHOD NOT ALLOWED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_BAD_METHOD</code> is 0xC5 (197).
+     */
+    public static final int OBEX_HTTP_BAD_METHOD = 0xC5;
+
+    /**
+     * Defines the OBEX NOT ACCEPTABLE response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_NOT_ACCEPTABLE</code> is 0xC6 (198).
+     */
+    public static final int OBEX_HTTP_NOT_ACCEPTABLE = 0xC6;
+
+    /**
+     * Defines the OBEX PROXY AUTHENTICATION REQUIRED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_PROXY_AUTH</code> is 0xC7 (199).
+     */
+    public static final int OBEX_HTTP_PROXY_AUTH = 0xC7;
+
+    /**
+     * Defines the OBEX REQUEST TIME OUT response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_TIMEOUT</code> is 0xC8 (200).
+     */
+    public static final int OBEX_HTTP_TIMEOUT = 0xC8;
+
+    /**
+     * Defines the OBEX METHOD CONFLICT response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_CONFLICT</code> is 0xC9 (201).
+     */
+    public static final int OBEX_HTTP_CONFLICT = 0xC9;
+
+    /**
+     * Defines the OBEX METHOD GONE response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_GONE</code> is 0xCA (202).
+     */
+    public static final int OBEX_HTTP_GONE = 0xCA;
+
+    /**
+     * Defines the OBEX METHOD LENGTH REQUIRED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_LENGTH_REQUIRED</code> is 0xCB (203).
+     */
+    public static final int OBEX_HTTP_LENGTH_REQUIRED = 0xCB;
+
+    /**
+     * Defines the OBEX PRECONDITION FAILED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_PRECON_FAILED</code> is 0xCC (204).
+     */
+    public static final int OBEX_HTTP_PRECON_FAILED = 0xCC;
+
+    /**
+     * Defines the OBEX REQUESTED ENTITY TOO LARGE response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_ENTITY_TOO_LARGE</code> is 0xCD (205).
+     */
+    public static final int OBEX_HTTP_ENTITY_TOO_LARGE = 0xCD;
+
+    /**
+     * Defines the OBEX REQUESTED URL TOO LARGE response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_REQ_TOO_LARGE</code> is 0xCE (206).
+     */
+    public static final int OBEX_HTTP_REQ_TOO_LARGE = 0xCE;
+
+    /**
+     * Defines the OBEX UNSUPPORTED MEDIA TYPE response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_UNSUPPORTED_TYPE</code> is 0xCF (207).
+     */
+    public static final int OBEX_HTTP_UNSUPPORTED_TYPE = 0xCF;
+
+    /**
+     * Defines the OBEX INTERNAL SERVER ERROR response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_INTERNAL_ERROR</code> is 0xD0 (208).
+     */
+    public static final int OBEX_HTTP_INTERNAL_ERROR = 0xD0;
+
+    /**
+     * Defines the OBEX NOT IMPLEMENTED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_NOT_IMPLEMENTED</code> is 0xD1 (209).
+     */
+    public static final int OBEX_HTTP_NOT_IMPLEMENTED = 0xD1;
+
+    /**
+     * Defines the OBEX BAD GATEWAY response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_BAD_GATEWAY</code> is 0xD2 (210).
+     */
+    public static final int OBEX_HTTP_BAD_GATEWAY = 0xD2;
+
+    /**
+     * Defines the OBEX SERVICE UNAVAILABLE response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_UNAVAILABLE</code> is 0xD3 (211).
+     */
+    public static final int OBEX_HTTP_UNAVAILABLE = 0xD3;
+
+    /**
+     * Defines the OBEX GATEWAY TIMEOUT response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_GATEWAY_TIMEOUT</code> is 0xD4 (212).
+     */
+    public static final int OBEX_HTTP_GATEWAY_TIMEOUT = 0xD4;
+
+    /**
+     * Defines the OBEX HTTP VERSION NOT SUPPORTED response code.
+     * <P>
+     * The value of <code>OBEX_HTTP_VERSION</code> is 0xD5 (213).
+     */
+    public static final int OBEX_HTTP_VERSION = 0xD5;
+
+    /**
+     * Defines the OBEX DATABASE FULL response code.
+     * <P>
+     * The value of <code>OBEX_DATABASE_FULL</code> is 0xE0 (224).
+     */
+    public static final int OBEX_DATABASE_FULL = 0xE0;
+
+    /**
+     * Defines the OBEX DATABASE LOCKED response code.
+     * <P>
+     * The value of <code>OBEX_DATABASE_LOCKED</code> is 0xE1 (225).
+     */
+    public static final int OBEX_DATABASE_LOCKED = 0xE1;
+
+    /**
+     * Constructor does nothing.
+     */
+    private ResponseCodes() {
+    }
+}
diff --git a/obex/javax/obex/ServerOperation.java b/obex/javax/obex/ServerOperation.java
new file mode 100644
index 0000000..8710c64
--- /dev/null
+++ b/obex/javax/obex/ServerOperation.java
@@ -0,0 +1,686 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.DataInputStream;
+import java.io.OutputStream;
+import java.io.DataOutputStream;
+import java.io.ByteArrayOutputStream;
+
+/**
+ * This class implements the Operation interface for server side connections.
+ * <P>
+ * <STRONG>Request Codes</STRONG> There are four different request codes that
+ * are in this class. 0x02 is a PUT request that signals that the request is not
+ * complete and requires an additional OBEX packet. 0x82 is a PUT request that
+ * says that request is complete. In this case, the server can begin sending the
+ * response. The 0x03 is a GET request that signals that the request is not
+ * finished. When the server receives a 0x83, the client is signaling the server
+ * that it is done with its request. TODO: Extend the ClientOperation and reuse
+ * the methods defined TODO: in that class.
+ * @hide
+ */
+public final class ServerOperation implements Operation, BaseStream {
+
+    public boolean isAborted;
+
+    public HeaderSet requestHeader;
+
+    public HeaderSet replyHeader;
+
+    public boolean finalBitSet;
+
+    private InputStream mInput;
+
+    private ServerSession mParent;
+
+    private int mMaxPacketLength;
+
+    private int mResponseSize;
+
+    private boolean mClosed;
+
+    private boolean mGetOperation;
+
+    private PrivateInputStream mPrivateInput;
+
+    private PrivateOutputStream mPrivateOutput;
+
+    private boolean mPrivateOutputOpen;
+
+    private String mExceptionString;
+
+    private ServerRequestHandler mListener;
+
+    private boolean mRequestFinished;
+
+    private boolean mHasBody;
+
+    /**
+     * Creates new ServerOperation
+     * @param p the parent that created this object
+     * @param in the input stream to read from
+     * @param out the output stream to write to
+     * @param request the initial request that was received from the client
+     * @param maxSize the max packet size that the client will accept
+     * @param listen the listener that is responding to the request
+     * @throws IOException if an IO error occurs
+     */
+    public ServerOperation(ServerSession p, InputStream in, int request, int maxSize,
+            ServerRequestHandler listen) throws IOException {
+
+        isAborted = false;
+        mParent = p;
+        mInput = in;
+        mMaxPacketLength = maxSize;
+        mClosed = false;
+        requestHeader = new HeaderSet();
+        replyHeader = new HeaderSet();
+        mPrivateInput = new PrivateInputStream(this);
+        mResponseSize = 3;
+        mListener = listen;
+        mRequestFinished = false;
+        mPrivateOutputOpen = false;
+        mHasBody = false;
+        int bytesReceived;
+
+        /*
+         * Determine if this is a PUT request
+         */
+        if ((request == 0x02) || (request == 0x82)) {
+            /*
+             * It is a PUT request.
+             */
+            mGetOperation = false;
+        } else {
+            /*
+             * It is a GET request.
+             */
+            mGetOperation = true;
+        }
+
+        /*
+         * Determine if the final bit is set
+         */
+        if ((request & 0x80) == 0) {
+            finalBitSet = false;
+        } else {
+            finalBitSet = true;
+            mRequestFinished = true;
+        }
+
+        int length = in.read();
+        length = (length << 8) + in.read();
+
+        /*
+         * Determine if the packet length is larger than this device can receive
+         */
+        if (length > ObexHelper.MAX_PACKET_SIZE_INT) {
+            mParent.sendResponse(ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE, null);
+            throw new IOException("Packet received was too large");
+        }
+
+        /*
+         * Determine if any headers were sent in the initial request
+         */
+        if (length > 3) {
+            byte[] data = new byte[length - 3];
+            bytesReceived = in.read(data);
+
+            while (bytesReceived != data.length) {
+                bytesReceived += in.read(data, bytesReceived, data.length - bytesReceived);
+            }
+
+            byte[] body = ObexHelper.updateHeaderSet(requestHeader, data);
+
+            if (body != null) {
+                mHasBody = true;
+            }
+
+            if (requestHeader.mConnectionID != null) {
+                mListener.setConnectionId(ObexHelper.convertToLong(requestHeader.mConnectionID));
+            } else {
+                mListener.setConnectionId(0);
+            }
+
+            if (requestHeader.mAuthResp != null) {
+                if (!mParent.handleAuthResp(requestHeader.mAuthResp)) {
+                    mExceptionString = "Authentication Failed";
+                    mParent.sendResponse(ResponseCodes.OBEX_HTTP_UNAUTHORIZED, null);
+                    mClosed = true;
+                    requestHeader.mAuthResp = null;
+                    return;
+                }
+            }
+
+            if (requestHeader.mAuthChall != null) {
+                mParent.handleAuthChall(requestHeader);
+                // send the  authResp to the client
+                replyHeader.mAuthResp = new byte[requestHeader.mAuthResp.length];
+                System.arraycopy(requestHeader.mAuthResp, 0, replyHeader.mAuthResp, 0,
+                        replyHeader.mAuthResp.length);
+                requestHeader.mAuthResp = null;
+                requestHeader.mAuthChall = null;
+
+            }
+
+            if (body != null) {
+                mPrivateInput.writeBytes(body, 1);
+            } else {
+                while ((!mGetOperation) && (!finalBitSet)) {
+                    sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
+                    if (mPrivateInput.available() > 0) {
+                        break;
+                    }
+                }
+            }
+        }
+
+        while ((!mGetOperation) && (!finalBitSet) && (mPrivateInput.available() == 0)) {
+            sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
+            if (mPrivateInput.available() > 0) {
+                break;
+            }
+        }
+
+        // wait for get request finished !!!!
+        while (mGetOperation && !finalBitSet) {
+            sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
+        }
+        if (finalBitSet && mGetOperation) {
+            mRequestFinished = true;
+        }
+    }
+
+    public boolean isValidBody() {
+        return mHasBody;
+    }
+
+    /**
+     * Determines if the operation should continue or should wait. If it should
+     * continue, this method will continue the operation.
+     * @param sendEmpty if <code>true</code> then this will continue the
+     *        operation even if no headers will be sent; if <code>false</code>
+     *        then this method will only continue the operation if there are
+     *        headers to send
+     * @param inStream if<code>true</code> the stream is input stream, otherwise
+     *        output stream
+     * @return <code>true</code> if the operation was completed;
+     *         <code>false</code> if no operation took place
+     */
+    public synchronized boolean continueOperation(boolean sendEmpty, boolean inStream)
+            throws IOException {
+        if (!mGetOperation) {
+            if (!finalBitSet) {
+                if (sendEmpty) {
+                    sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
+                    return true;
+                } else {
+                    if ((mResponseSize > 3) || (mPrivateOutput.size() > 0)) {
+                        sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
+                        return true;
+                    } else {
+                        return false;
+                    }
+                }
+            } else {
+                return false;
+            }
+        } else {
+            sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
+            return true;
+        }
+    }
+
+    /**
+     * Sends a reply to the client. If the reply is a OBEX_HTTP_CONTINUE, it
+     * will wait for a response from the client before ending.
+     * @param type the response code to send back to the client
+     * @return <code>true</code> if the final bit was not set on the reply;
+     *         <code>false</code> if no reply was received because the operation
+     *         ended, an abort was received, or the final bit was set in the
+     *         reply
+     * @throws IOException if an IO error occurs
+     */
+    public synchronized boolean sendReply(int type) throws IOException {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        int bytesReceived;
+
+        long id = mListener.getConnectionId();
+        if (id == -1) {
+            replyHeader.mConnectionID = null;
+        } else {
+            replyHeader.mConnectionID = ObexHelper.convertToByteArray(id);
+        }
+
+        byte[] headerArray = ObexHelper.createHeader(replyHeader, true);
+        int bodyLength = -1;
+        int orginalBodyLength = -1;
+
+        if (mPrivateOutput != null) {
+            bodyLength = mPrivateOutput.size();
+            orginalBodyLength = bodyLength;
+        }
+
+        if ((ObexHelper.BASE_PACKET_LENGTH + headerArray.length) > mMaxPacketLength) {
+
+            int end = 0;
+            int start = 0;
+
+            while (end != headerArray.length) {
+                end = ObexHelper.findHeaderEnd(headerArray, start, mMaxPacketLength
+                        - ObexHelper.BASE_PACKET_LENGTH);
+                if (end == -1) {
+
+                    mClosed = true;
+
+                    if (mPrivateInput != null) {
+                        mPrivateInput.close();
+                    }
+
+                    if (mPrivateOutput != null) {
+                        mPrivateOutput.close();
+                    }
+                    mParent.sendResponse(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR, null);
+                    throw new IOException("OBEX Packet exceeds max packet size");
+                }
+                byte[] sendHeader = new byte[end - start];
+                System.arraycopy(headerArray, start, sendHeader, 0, sendHeader.length);
+
+                mParent.sendResponse(type, sendHeader);
+                start = end;
+            }
+
+            if (bodyLength > 0) {
+                return true;
+            } else {
+                return false;
+            }
+
+        } else {
+            out.write(headerArray);
+        }
+
+        if ((finalBitSet) || (headerArray.length < (mMaxPacketLength - 20))) {
+            if (bodyLength > 0) {
+                /*
+                 * Determine if I can send the whole body or just part of
+                 * the body.  Remember that there is the 3 bytes for the
+                 * response message and 3 bytes for the header ID and length
+                 */
+                if (bodyLength > (mMaxPacketLength - headerArray.length - 6)) {
+                    bodyLength = mMaxPacketLength - headerArray.length - 6;
+                }
+
+                byte[] body = mPrivateOutput.readBytes(bodyLength);
+
+                /*
+                 * Since this is a put request if the final bit is set or
+                 * the output stream is closed we need to send the 0x49
+                 * (End of Body) otherwise, we need to send 0x48 (Body)
+                 */
+                if ((finalBitSet) || (mPrivateOutput.isClosed())) {
+                    out.write(0x49);
+                } else {
+                    out.write(0x48);
+                }
+
+                bodyLength += 3;
+                out.write((byte)(bodyLength >> 8));
+                out.write((byte)bodyLength);
+                out.write(body);
+            }
+        }
+
+        if ((finalBitSet) && (type == ResponseCodes.OBEX_HTTP_OK) && (orginalBodyLength <= 0)) {
+            out.write(0x49);
+            orginalBodyLength = 3;
+            out.write((byte)(orginalBodyLength >> 8));
+            out.write((byte)orginalBodyLength);
+
+        }
+
+        mResponseSize = 3;
+        mParent.sendResponse(type, out.toByteArray());
+
+        if (type == ResponseCodes.OBEX_HTTP_CONTINUE) {
+            int headerID = mInput.read();
+            int length = mInput.read();
+            length = (length << 8) + mInput.read();
+            if ((headerID != ObexHelper.OBEX_OPCODE_PUT)
+                    && (headerID != ObexHelper.OBEX_OPCODE_PUT_FINAL)
+                    && (headerID != ObexHelper.OBEX_OPCODE_GET)
+                    && (headerID != ObexHelper.OBEX_OPCODE_GET_FINAL)) {
+
+                if (length > 3) {
+                    byte[] temp = new byte[length];
+                    bytesReceived = mInput.read(temp);
+
+                    while (bytesReceived != length) {
+                        bytesReceived += mInput.read(temp, bytesReceived, length - bytesReceived);
+                    }
+                }
+
+                /*
+                 * Determine if an ABORT was sent as the reply
+                 */
+                if (headerID == ObexHelper.OBEX_OPCODE_ABORT) {
+                    mParent.sendResponse(ResponseCodes.OBEX_HTTP_OK, null);
+                    mClosed = true;
+                    isAborted = true;
+                    mExceptionString = "Abort Received";
+                    throw new IOException("Abort Received");
+                } else {
+                    mParent.sendResponse(ResponseCodes.OBEX_HTTP_BAD_REQUEST, null);
+                    mClosed = true;
+                    mExceptionString = "Bad Request Received";
+                    throw new IOException("Bad Request Received");
+                }
+            } else {
+
+                if ((headerID == ObexHelper.OBEX_OPCODE_PUT_FINAL)
+                        || (headerID == ObexHelper.OBEX_OPCODE_GET_FINAL)) {
+                    finalBitSet = true;
+                }
+
+                /*
+                 * Determine if the packet length is larger then this device can receive
+                 */
+                if (length > ObexHelper.MAX_PACKET_SIZE_INT) {
+                    mParent.sendResponse(ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE, null);
+                    throw new IOException("Packet received was too large");
+                }
+
+                /*
+                 * Determine if any headers were sent in the initial request
+                 */
+                if (length > 3) {
+                    byte[] data = new byte[length - 3];
+                    bytesReceived = mInput.read(data);
+
+                    while (bytesReceived != data.length) {
+                        bytesReceived += mInput.read(data, bytesReceived, data.length
+                                - bytesReceived);
+                    }
+                    byte[] body = ObexHelper.updateHeaderSet(requestHeader, data);
+                    if (body != null) {
+                        mHasBody = true;
+                    }
+                    if (requestHeader.mConnectionID != null) {
+                        mListener.setConnectionId(ObexHelper
+                                .convertToLong(requestHeader.mConnectionID));
+                    } else {
+                        mListener.setConnectionId(1);
+                    }
+
+                    if (requestHeader.mAuthResp != null) {
+                        if (!mParent.handleAuthResp(requestHeader.mAuthResp)) {
+                            mExceptionString = "Authentication Failed";
+                            mParent.sendResponse(ResponseCodes.OBEX_HTTP_UNAUTHORIZED, null);
+                            mClosed = true;
+                            requestHeader.mAuthResp = null;
+                            return false;
+                        }
+                        requestHeader.mAuthResp = null;
+                    }
+
+                    if (requestHeader.mAuthChall != null) {
+                        mParent.handleAuthChall(requestHeader);
+                        // send the auhtResp to the client
+                        replyHeader.mAuthResp = new byte[requestHeader.mAuthResp.length];
+                        System.arraycopy(requestHeader.mAuthResp, 0, replyHeader.mAuthResp, 0,
+                                replyHeader.mAuthResp.length);
+                        requestHeader.mAuthResp = null;
+                        requestHeader.mAuthChall = null;
+                    }
+
+                    if (body != null) {
+                        mPrivateInput.writeBytes(body, 1);
+                    }
+                }
+            }
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Sends an ABORT message to the server. By calling this method, the
+     * corresponding input and output streams will be closed along with this
+     * object.
+     * @throws IOException if the transaction has already ended or if an OBEX
+     *         server called this method
+     */
+    public void abort() throws IOException {
+        throw new IOException("Called from a server");
+    }
+
+    /**
+     * Returns the headers that have been received during the operation.
+     * Modifying the object returned has no effect on the headers that are sent
+     * or retrieved.
+     * @return the headers received during this <code>Operation</code>
+     * @throws IOException if this <code>Operation</code> has been closed
+     */
+    public HeaderSet getReceivedHeader() throws IOException {
+        ensureOpen();
+        return requestHeader;
+    }
+
+    /**
+     * Specifies the headers that should be sent in the next OBEX message that
+     * is sent.
+     * @param headers the headers to send in the next message
+     * @throws IOException if this <code>Operation</code> has been closed or the
+     *         transaction has ended and no further messages will be exchanged
+     * @throws IllegalArgumentException if <code>headers</code> was not created
+     *         by a call to <code>ServerRequestHandler.createHeaderSet()</code>
+     */
+    public void sendHeaders(HeaderSet headers) throws IOException {
+        ensureOpen();
+
+        if (headers == null) {
+            throw new IOException("Headers may not be null");
+        }
+
+        int[] headerList = headers.getHeaderList();
+        if (headerList != null) {
+            for (int i = 0; i < headerList.length; i++) {
+                replyHeader.setHeader(headerList[i], headers.getHeader(headerList[i]));
+            }
+
+        }
+    }
+
+    /**
+     * Retrieves the response code retrieved from the server. Response codes are
+     * defined in the <code>ResponseCodes</code> interface.
+     * @return the response code retrieved from the server
+     * @throws IOException if an error occurred in the transport layer during
+     *         the transaction; if this method is called on a
+     *         <code>HeaderSet</code> object created by calling
+     *         <code>createHeaderSet</code> in a <code>ClientSession</code>
+     *         object; if this is called from a server
+     */
+    public int getResponseCode() throws IOException {
+        throw new IOException("Called from a server");
+    }
+
+    /**
+     * Always returns <code>null</code>
+     * @return <code>null</code>
+     */
+    public String getEncoding() {
+        return null;
+    }
+
+    /**
+     * Returns the type of content that the resource connected to is providing.
+     * E.g. if the connection is via HTTP, then the value of the content-type
+     * header field is returned.
+     * @return the content type of the resource that the URL references, or
+     *         <code>null</code> if not known
+     */
+    public String getType() {
+        try {
+            return (String)requestHeader.getHeader(HeaderSet.TYPE);
+        } catch (IOException e) {
+            return null;
+        }
+    }
+
+    /**
+     * Returns the length of the content which is being provided. E.g. if the
+     * connection is via HTTP, then the value of the content-length header field
+     * is returned.
+     * @return the content length of the resource that this connection's URL
+     *         references, or -1 if the content length is not known
+     */
+    public long getLength() {
+        try {
+            Long temp = (Long)requestHeader.getHeader(HeaderSet.LENGTH);
+
+            if (temp == null) {
+                return -1;
+            } else {
+                return temp.longValue();
+            }
+        } catch (IOException e) {
+            return -1;
+        }
+    }
+
+    public int getMaxPacketSize() {
+        return mMaxPacketLength - 6;
+    }
+
+    /**
+     * Open and return an input stream for a connection.
+     * @return an input stream
+     * @throws IOException if an I/O error occurs
+     */
+    public InputStream openInputStream() throws IOException {
+        ensureOpen();
+        return mPrivateInput;
+    }
+
+    /**
+     * Open and return a data input stream for a connection.
+     * @return an input stream
+     * @throws IOException if an I/O error occurs
+     */
+    public DataInputStream openDataInputStream() throws IOException {
+        return new DataInputStream(openInputStream());
+    }
+
+    /**
+     * Open and return an output stream for a connection.
+     * @return an output stream
+     * @throws IOException if an I/O error occurs
+     */
+    public OutputStream openOutputStream() throws IOException {
+        ensureOpen();
+
+        if (mPrivateOutputOpen) {
+            throw new IOException("no more input streams available, stream already opened");
+        }
+
+        if (!mRequestFinished) {
+            throw new IOException("no  output streams available ,request not finished");
+        }
+
+        if (mPrivateOutput == null) {
+            mPrivateOutput = new PrivateOutputStream(this, mMaxPacketLength - 6);
+        }
+        mPrivateOutputOpen = true;
+        return mPrivateOutput;
+    }
+
+    /**
+     * Open and return a data output stream for a connection.
+     * @return an output stream
+     * @throws IOException if an I/O error occurs
+     */
+    public DataOutputStream openDataOutputStream() throws IOException {
+        return new DataOutputStream(openOutputStream());
+    }
+
+    /**
+     * Closes the connection and ends the transaction
+     * @throws IOException if the operation has already ended or is closed
+     */
+    public void close() throws IOException {
+        ensureOpen();
+        mClosed = true;
+    }
+
+    /**
+     * Verifies that the connection is open and no exceptions should be thrown.
+     * @throws IOException if an exception needs to be thrown
+     */
+    public void ensureOpen() throws IOException {
+        if (mExceptionString != null) {
+            throw new IOException(mExceptionString);
+        }
+        if (mClosed) {
+            throw new IOException("Operation has already ended");
+        }
+    }
+
+    /**
+     * Verifies that additional information may be sent. In other words, the
+     * operation is not done.
+     * <P>
+     * Included to implement the BaseStream interface only. It does not do
+     * anything on the server side since the operation of the Operation object
+     * is not done until after the handler returns from its method.
+     * @throws IOException if the operation is completed
+     */
+    public void ensureNotDone() throws IOException {
+    }
+
+    /**
+     * Called when the output or input stream is closed. It does not do anything
+     * on the server side since the operation of the Operation object is not
+     * done until after the handler returns from its method.
+     * @param inStream <code>true</code> if the input stream is closed;
+     *        <code>false</code> if the output stream is closed
+     * @throws IOException if an IO error occurs
+     */
+    public void streamClosed(boolean inStream) throws IOException {
+
+    }
+}
diff --git a/obex/javax/obex/ServerRequestHandler.java b/obex/javax/obex/ServerRequestHandler.java
new file mode 100644
index 0000000..d93e5b6
--- /dev/null
+++ b/obex/javax/obex/ServerRequestHandler.java
@@ -0,0 +1,271 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+/**
+ * The <code>ServerRequestHandler</code> class defines an event listener that
+ * will respond to OBEX requests made to the server.
+ * <P>
+ * The <code>onConnect()</code>, <code>onSetPath()</code>,
+ * <code>onDelete()</code>, <code>onGet()</code>, and <code>onPut()</code>
+ * methods may return any response code defined in the
+ * <code>ResponseCodes</code> class except for <code>OBEX_HTTP_CONTINUE</code>.
+ * If <code>OBEX_HTTP_CONTINUE</code> or a value not defined in the
+ * <code>ResponseCodes</code> class is returned, the server implementation will
+ * send an <code>OBEX_HTTP_INTERNAL_ERROR</code> response to the client.
+ * <P>
+ * <STRONG>Connection ID and Target Headers</STRONG>
+ * <P>
+ * According to the IrOBEX specification, a packet may not contain a Connection
+ * ID and Target header. Since the Connection ID header is managed by the
+ * implementation, it will not send a Connection ID header, if a Connection ID
+ * was specified, in a packet that has a Target header. In other words, if an
+ * application adds a Target header to a <code>HeaderSet</code> object used in
+ * an OBEX operation and a Connection ID was specified, no Connection ID will be
+ * sent in the packet containing the Target header.
+ * <P>
+ * <STRONG>CREATE-EMPTY Requests</STRONG>
+ * <P>
+ * A CREATE-EMPTY request allows clients to create empty objects on the server.
+ * When a CREATE-EMPTY request is received, the <code>onPut()</code> method will
+ * be called by the implementation. To differentiate between a normal PUT
+ * request and a CREATE-EMPTY request, an application must open the
+ * <code>InputStream</code> from the <code>Operation</code> object passed to the
+ * <code>onPut()</code> method. For a PUT request, the application will be able
+ * to read Body data from this <code>InputStream</code>. For a CREATE-EMPTY
+ * request, there will be no Body data to read. Therefore, a call to
+ * <code>InputStream.read()</code> will return -1.
+ * @hide
+ */
+public class ServerRequestHandler {
+
+    private long mConnectionId;
+
+    /**
+     * Creates a <code>ServerRequestHandler</code>.
+     */
+    protected ServerRequestHandler() {
+        /*
+         * A connection ID of -1 implies there is no conenction ID
+         */
+        mConnectionId = -1;
+    }
+
+    /**
+     * Sets the connection ID header to include in the reply packets.
+     * @param connectionId the connection ID to use; -1 if no connection ID
+     *        should be sent
+     * @throws IllegalArgumentException if <code>id</code> is not in the range
+     *         -1 to 2<sup>32</sup>-1
+     */
+    public void setConnectionId(final long connectionId) {
+        if ((connectionId < -1) || (connectionId > 0xFFFFFFFFL)) {
+            throw new IllegalArgumentException("Illegal Connection ID");
+        }
+        mConnectionId = connectionId;
+    }
+
+    /**
+     * Retrieves the connection ID that is being used in the present connection.
+     * This method will return -1 if no connection ID is being used.
+     * @return the connection id being used or -1 if no connection ID is being
+     *         used
+     */
+    public long getConnectionId() {
+        return mConnectionId;
+    }
+
+    /**
+     * Called when a CONNECT request is received.
+     * <P>
+     * If this method is not implemented by the class that extends this class,
+     * <code>onConnect()</code> will always return an <code>OBEX_HTTP_OK</code>
+     * response code.
+     * <P>
+     * The headers received in the request can be retrieved from the
+     * <code>request</code> argument. The headers that should be sent in the
+     * reply must be specified in the <code>reply</code> argument.
+     * @param request contains the headers sent by the client;
+     *        <code>request</code> will never be <code>null</code>
+     * @param reply the headers that should be sent in the reply;
+     *        <code>reply</code> will never be <code>null</code>
+     * @return a response code defined in <code>ResponseCodes</code> that will
+     *         be returned to the client; if an invalid response code is
+     *         provided, the <code>OBEX_HTTP_INTERNAL_ERROR</code> response code
+     *         will be used
+     */
+    public int onConnect(HeaderSet request, HeaderSet reply) {
+        return ResponseCodes.OBEX_HTTP_OK;
+    }
+
+    /**
+     * Called when a DISCONNECT request is received.
+     * <P>
+     * The headers received in the request can be retrieved from the
+     * <code>request</code> argument. The headers that should be sent in the
+     * reply must be specified in the <code>reply</code> argument.
+     * @param request contains the headers sent by the client;
+     *        <code>request</code> will never be <code>null</code>
+     * @param reply the headers that should be sent in the reply;
+     *        <code>reply</code> will never be <code>null</code>
+     */
+    public void onDisconnect(HeaderSet request, HeaderSet reply) {
+    }
+
+    /**
+     * Called when a SETPATH request is received.
+     * <P>
+     * If this method is not implemented by the class that extends this class,
+     * <code>onSetPath()</code> will always return an
+     * <code>OBEX_HTTP_NOT_IMPLEMENTED</code> response code.
+     * <P>
+     * The headers received in the request can be retrieved from the
+     * <code>request</code> argument. The headers that should be sent in the
+     * reply must be specified in the <code>reply</code> argument.
+     * @param request contains the headers sent by the client;
+     *        <code>request</code> will never be <code>null</code>
+     * @param reply the headers that should be sent in the reply;
+     *        <code>reply</code> will never be <code>null</code>
+     * @param backup <code>true</code> if the client requests that the server
+     *        back up one directory before changing to the path described by
+     *        <code>name</code>; <code>false</code> to apply the request to the
+     *        present path
+     * @param create <code>true</code> if the path should be created if it does
+     *        not already exist; <code>false</code> if the path should not be
+     *        created if it does not exist and an error code should be returned
+     * @return a response code defined in <code>ResponseCodes</code> that will
+     *         be returned to the client; if an invalid response code is
+     *         provided, the <code>OBEX_HTTP_INTERNAL_ERROR</code> response code
+     *         will be used
+     */
+    public int onSetPath(HeaderSet request, HeaderSet reply, boolean backup, boolean create) {
+
+        return ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED;
+    }
+
+    /**
+     * Called when a DELETE request is received.
+     * <P>
+     * If this method is not implemented by the class that extends this class,
+     * <code>onDelete()</code> will always return an
+     * <code>OBEX_HTTP_NOT_IMPLEMENTED</code> response code.
+     * <P>
+     * The headers received in the request can be retrieved from the
+     * <code>request</code> argument. The headers that should be sent in the
+     * reply must be specified in the <code>reply</code> argument.
+     * @param request contains the headers sent by the client;
+     *        <code>request</code> will never be <code>null</code>
+     * @param reply the headers that should be sent in the reply;
+     *        <code>reply</code> will never be <code>null</code>
+     * @return a response code defined in <code>ResponseCodes</code> that will
+     *         be returned to the client; if an invalid response code is
+     *         provided, the <code>OBEX_HTTP_INTERNAL_ERROR</code> response code
+     *         will be used
+     */
+    public int onDelete(HeaderSet request, HeaderSet reply) {
+        return ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED;
+    }
+
+    /**
+     * Called when a PUT request is received.
+     * <P>
+     * If this method is not implemented by the class that extends this class,
+     * <code>onPut()</code> will always return an
+     * <code>OBEX_HTTP_NOT_IMPLEMENTED</code> response code.
+     * <P>
+     * If an ABORT request is received during the processing of a PUT request,
+     * <code>op</code> will be closed by the implementation.
+     * @param operation contains the headers sent by the client and allows new
+     *        headers to be sent in the reply; <code>op</code> will never be
+     *        <code>null</code>
+     * @return a response code defined in <code>ResponseCodes</code> that will
+     *         be returned to the client; if an invalid response code is
+     *         provided, the <code>OBEX_HTTP_INTERNAL_ERROR</code> response code
+     *         will be used
+     */
+    public int onPut(Operation operation) {
+        return ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED;
+    }
+
+    /**
+     * Called when a GET request is received.
+     * <P>
+     * If this method is not implemented by the class that extends this class,
+     * <code>onGet()</code> will always return an
+     * <code>OBEX_HTTP_NOT_IMPLEMENTED</code> response code.
+     * <P>
+     * If an ABORT request is received during the processing of a GET request,
+     * <code>op</code> will be closed by the implementation.
+     * @param operation contains the headers sent by the client and allows new
+     *        headers to be sent in the reply; <code>op</code> will never be
+     *        <code>null</code>
+     * @return a response code defined in <code>ResponseCodes</code> that will
+     *         be returned to the client; if an invalid response code is
+     *         provided, the <code>OBEX_HTTP_INTERNAL_ERROR</code> response code
+     *         will be used
+     */
+    public int onGet(Operation operation) {
+        return ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED;
+    }
+
+    /**
+     * Called when this object attempts to authenticate a client and the
+     * authentication request fails because the response digest in the
+     * authentication response header was wrong.
+     * <P>
+     * If this method is not implemented by the class that extends this class,
+     * this method will do nothing.
+     * @param userName the user name returned in the authentication response;
+     *        <code>null</code> if no user name was provided in the response
+     */
+    public void onAuthenticationFailure(byte[] userName) {
+    }
+
+    /**
+     * Called by ServerSession to update the status of current transaction
+     * <P>
+     * If this method is not implemented by the class that extends this class,
+     * this method will do nothing.
+     */
+    public void updateStatus(String message) {
+    }
+
+    /**
+     * Called when session is closed.
+     * <P>
+     * If this method is not implemented by the class that extends this class,
+     * this method will do nothing.
+     */
+    public void onClose() {
+    }
+}
diff --git a/obex/javax/obex/ServerSession.java b/obex/javax/obex/ServerSession.java
new file mode 100644
index 0000000..423d5a7
--- /dev/null
+++ b/obex/javax/obex/ServerSession.java
@@ -0,0 +1,669 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import android.util.Log;
+
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * This class in an implementation of the OBEX ServerSession.
+ * @hide
+ */
+public final class ServerSession extends ObexSession implements Runnable {
+
+    private static final String TAG = "Obex ServerSession";
+
+    private ObexTransport mTransport;
+
+    private InputStream mInput;
+
+    private OutputStream mOutput;
+
+    private ServerRequestHandler mListener;
+
+    private Thread mProcessThread;
+
+    private int mMaxPacketLength;
+
+    private boolean mClosed;
+
+    /**
+     * Creates new ServerSession.
+     * @param trans the connection to the client
+     * @param handler the event listener that will process requests
+     * @param auth the authenticator to use with this connection
+     * @throws IOException if an error occurred while opening the input and
+     *         output streams
+     */
+    public ServerSession(ObexTransport trans, ServerRequestHandler handler, Authenticator auth)
+            throws IOException {
+        mAuthenticator = auth;
+        mTransport = trans;
+        mInput = mTransport.openInputStream();
+        mOutput = mTransport.openOutputStream();
+        mListener = handler;
+        mMaxPacketLength = 256;
+
+        mClosed = false;
+        mProcessThread = new Thread(this);
+        mProcessThread.start();
+    }
+
+    /**
+     * Processes requests made to the server and forwards them to the
+     * appropriate event listener.
+     */
+    public void run() {
+        try {
+
+            boolean done = false;
+            while (!done && !mClosed) {
+                int requestType = mInput.read();
+                switch (requestType) {
+                    case ObexHelper.OBEX_OPCODE_CONNECT:
+                        handleConnectRequest();
+                        break;
+
+                    case ObexHelper.OBEX_OPCODE_DISCONNECT:
+                        handleDisconnectRequest();
+                        done = true;
+                        break;
+
+                    case ObexHelper.OBEX_OPCODE_GET:
+                    case ObexHelper.OBEX_OPCODE_GET_FINAL:
+                        handleGetRequest(requestType);
+                        break;
+
+                    case ObexHelper.OBEX_OPCODE_PUT:
+                    case ObexHelper.OBEX_OPCODE_PUT_FINAL:
+                        handlePutRequest(requestType);
+                        break;
+
+                    case ObexHelper.OBEX_OPCODE_SETPATH:
+                        handleSetPathRequest();
+                        break;
+
+                    case -1:
+                        done = true;
+                        break;
+
+                    default:
+
+                        /*
+                         * Received a request type that is not recognized so I am
+                         * just going to read the packet and send a not implemented
+                         * to the client
+                         */
+                        int length = mInput.read();
+                        length = (length << 8) + mInput.read();
+                        for (int i = 3; i < length; i++) {
+                            mInput.read();
+                        }
+                        sendResponse(ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED, null);
+                }
+            }
+
+        } catch (NullPointerException e) {
+            Log.d(TAG, e.toString());
+        } catch (Exception e) {
+            Log.d(TAG, e.toString());
+        }
+        close();
+    }
+
+    /**
+     * Handles a PUT request from a client. This method will provide a
+     * <code>ServerOperation</code> object to the request handler. The
+     * <code>ServerOperation</code> object will handle the rest of the request.
+     * It will also send replies and receive requests until the final reply
+     * should be sent. When the final reply should be sent, this method will get
+     * the response code to use and send the reply. The
+     * <code>ServerOperation</code> object will always reply with a
+     * OBEX_HTTP_CONTINUE reply. It will only reply if further information is
+     * needed.
+     * @param type the type of request received; either 0x02 or 0x82
+     * @throws IOException if an error occurred at the transport layer
+     */
+    private void handlePutRequest(int type) throws IOException {
+        ServerOperation op = new ServerOperation(this, mInput, type, mMaxPacketLength, mListener);
+        try {
+            int response = -1;
+
+            if ((op.finalBitSet) && !op.isValidBody()) {
+                response = validateResponseCode(mListener
+                        .onDelete(op.requestHeader, op.replyHeader));
+            } else {
+                response = validateResponseCode(mListener.onPut(op));
+            }
+            if (response != ResponseCodes.OBEX_HTTP_OK) {
+                op.sendReply(response);
+            } else if (!op.isAborted) {
+                // wait for the final bit
+                while (!op.finalBitSet) {
+                    op.sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
+                }
+                op.sendReply(response);
+            }
+        } catch (Exception e) {
+            /*To fix bugs in aborted cases,
+             *(client abort file transfer prior to the last packet which has the end of body header,
+             *internal error should not be sent because server has already replied with
+             *OK response in "sendReply")
+             */
+            if (!op.isAborted) {
+                sendResponse(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR, null);
+            }
+        }
+    }
+
+    /**
+     * Handles a GET request from a client. This method will provide a
+     * <code>ServerOperation</code> object to the request handler. The
+     * <code>ServerOperation</code> object will handle the rest of the request.
+     * It will also send replies and receive requests until the final reply
+     * should be sent. When the final reply should be sent, this method will get
+     * the response code to use and send the reply. The
+     * <code>ServerOperation</code> object will always reply with a
+     * OBEX_HTTP_CONTINUE reply. It will only reply if further information is
+     * needed.
+     * @param type the type of request received; either 0x03 or 0x83
+     * @throws IOException if an error occurred at the transport layer
+     */
+    private void handleGetRequest(int type) throws IOException {
+        ServerOperation op = new ServerOperation(this, mInput, type, mMaxPacketLength, mListener);
+        try {
+            int response = validateResponseCode(mListener.onGet(op));
+
+            if (!op.isAborted) {
+                op.sendReply(response);
+            }
+        } catch (Exception e) {
+            sendResponse(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR, null);
+        }
+    }
+
+    /**
+     * Send standard response.
+     * @param code the response code to send
+     * @param header the headers to include in the response
+     * @throws IOException if an IO error occurs
+     */
+    public void sendResponse(int code, byte[] header) throws IOException {
+        int totalLength = 3;
+        byte[] data = null;
+
+        if (header != null) {
+            totalLength += header.length;
+            data = new byte[totalLength];
+            data[0] = (byte)code;
+            data[1] = (byte)(totalLength >> 8);
+            data[2] = (byte)totalLength;
+            System.arraycopy(header, 0, data, 3, header.length);
+        } else {
+            data = new byte[totalLength];
+            data[0] = (byte)code;
+            data[1] = (byte)0x00;
+            data[2] = (byte)totalLength;
+        }
+        mOutput.write(data);
+        mOutput.flush();
+    }
+
+    /**
+     * Handles a SETPATH request from a client. This method will read the rest
+     * of the request from the client. Assuming the request is valid, it will
+     * create a <code>HeaderSet</code> object to pass to the
+     * <code>ServerRequestHandler</code> object. After the handler processes the
+     * request, this method will create a reply message to send to the server
+     * with the response code provided.
+     * @throws IOException if an error occurred at the transport layer
+     */
+    private void handleSetPathRequest() throws IOException {
+        int length;
+        int flags;
+        @SuppressWarnings("unused")
+        int constants;
+        int totalLength = 3;
+        byte[] head = null;
+        int code = -1;
+        int bytesReceived;
+        HeaderSet request = new HeaderSet();
+        HeaderSet reply = new HeaderSet();
+
+        length = mInput.read();
+        length = (length << 8) + mInput.read();
+        flags = mInput.read();
+        constants = mInput.read();
+
+        if (length > ObexHelper.MAX_PACKET_SIZE_INT) {
+            code = ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE;
+            totalLength = 3;
+        } else {
+            if (length > 5) {
+                byte[] headers = new byte[length - 5];
+                bytesReceived = mInput.read(headers);
+
+                while (bytesReceived != headers.length) {
+                    bytesReceived += mInput.read(headers, bytesReceived, headers.length
+                            - bytesReceived);
+                }
+
+                ObexHelper.updateHeaderSet(request, headers);
+
+                if (request.mConnectionID != null) {
+                    mListener.setConnectionId(ObexHelper.convertToLong(request.mConnectionID));
+                } else {
+                    mListener.setConnectionId(-1);
+                }
+                // the Auth chan is initiated by the server, client sent back the authResp .
+                if (request.mAuthResp != null) {
+                    if (!handleAuthResp(request.mAuthResp)) {
+                        code = ResponseCodes.OBEX_HTTP_UNAUTHORIZED;
+                        mListener.onAuthenticationFailure(ObexHelper.getTagValue((byte)0x01,
+                                request.mAuthResp));
+                    }
+                    request.mAuthResp = null;
+                }
+            }
+
+            if (code != ResponseCodes.OBEX_HTTP_UNAUTHORIZED) {
+                // the Auth challenge is initiated by the client
+                // the server will send back the authResp to the client
+                if (request.mAuthChall != null) {
+                    handleAuthChall(request);
+                    reply.mAuthResp = new byte[request.mAuthResp.length];
+                    System.arraycopy(request.mAuthResp, 0, reply.mAuthResp, 0,
+                            reply.mAuthResp.length);
+                    request.mAuthChall = null;
+                    request.mAuthResp = null;
+                }
+                boolean backup = false;
+                boolean create = true;
+                if (!((flags & 1) == 0)) {
+                    backup = true;
+                }
+                if ((flags & 2) == 0) {
+                    create = false;
+                }
+
+                try {
+                    code = mListener.onSetPath(request, reply, backup, create);
+                } catch (Exception e) {
+                    sendResponse(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR, null);
+                    return;
+                }
+
+                code = validateResponseCode(code);
+
+                if (reply.nonce != null) {
+                    mChallengeDigest = new byte[16];
+                    System.arraycopy(reply.nonce, 0, mChallengeDigest, 0, 16);
+                } else {
+                    mChallengeDigest = null;
+                }
+
+                long id = mListener.getConnectionId();
+                if (id == -1) {
+                    reply.mConnectionID = null;
+                } else {
+                    reply.mConnectionID = ObexHelper.convertToByteArray(id);
+                }
+
+                head = ObexHelper.createHeader(reply, false);
+                totalLength += head.length;
+
+                if (totalLength > mMaxPacketLength) {
+                    totalLength = 3;
+                    head = null;
+                    code = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
+                }
+            }
+        }
+
+        // Compute Length of OBEX SETPATH packet
+        byte[] replyData = new byte[totalLength];
+        replyData[0] = (byte)code;
+        replyData[1] = (byte)(totalLength >> 8);
+        replyData[2] = (byte)totalLength;
+        if (head != null) {
+            System.arraycopy(head, 0, replyData, 3, head.length);
+        }
+        /*
+         * Write the OBEX SETPATH packet to the server. Byte 0: response code
+         * Byte 1&2: Connect Packet Length Byte 3 to n: headers
+         */
+        mOutput.write(replyData);
+        mOutput.flush();
+    }
+
+    /**
+     * Handles a disconnect request from a client. This method will read the
+     * rest of the request from the client. Assuming the request is valid, it
+     * will create a <code>HeaderSet</code> object to pass to the
+     * <code>ServerRequestHandler</code> object. After the handler processes the
+     * request, this method will create a reply message to send to the server.
+     * @throws IOException if an error occurred at the transport layer
+     */
+    private void handleDisconnectRequest() throws IOException {
+        int length;
+        int code = ResponseCodes.OBEX_HTTP_OK;
+        int totalLength = 3;
+        byte[] head = null;
+        int bytesReceived;
+        HeaderSet request = new HeaderSet();
+        HeaderSet reply = new HeaderSet();
+
+        length = mInput.read();
+        length = (length << 8) + mInput.read();
+
+        if (length > ObexHelper.MAX_PACKET_SIZE_INT) {
+            code = ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE;
+            totalLength = 3;
+        } else {
+            if (length > 3) {
+                byte[] headers = new byte[length - 3];
+                bytesReceived = mInput.read(headers);
+
+                while (bytesReceived != headers.length) {
+                    bytesReceived += mInput.read(headers, bytesReceived, headers.length
+                            - bytesReceived);
+                }
+
+                ObexHelper.updateHeaderSet(request, headers);
+            }
+
+            if (request.mConnectionID != null) {
+                mListener.setConnectionId(ObexHelper.convertToLong(request.mConnectionID));
+            } else {
+                mListener.setConnectionId(1);
+            }
+
+            if (request.mAuthResp != null) {
+                if (!handleAuthResp(request.mAuthResp)) {
+                    code = ResponseCodes.OBEX_HTTP_UNAUTHORIZED;
+                    mListener.onAuthenticationFailure(ObexHelper.getTagValue((byte)0x01,
+                            request.mAuthResp));
+                }
+                request.mAuthResp = null;
+            }
+
+            if (code != ResponseCodes.OBEX_HTTP_UNAUTHORIZED) {
+
+                if (request.mAuthChall != null) {
+                    handleAuthChall(request);
+                    request.mAuthChall = null;
+                }
+
+                try {
+                    mListener.onDisconnect(request, reply);
+                } catch (Exception e) {
+                    sendResponse(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR, null);
+                    return;
+                }
+
+                long id = mListener.getConnectionId();
+                if (id == -1) {
+                    reply.mConnectionID = null;
+                } else {
+                    reply.mConnectionID = ObexHelper.convertToByteArray(id);
+                }
+
+                head = ObexHelper.createHeader(reply, false);
+                totalLength += head.length;
+
+                if (totalLength > mMaxPacketLength) {
+                    totalLength = 3;
+                    head = null;
+                    code = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
+                }
+            }
+        }
+
+        // Compute Length of OBEX CONNECT packet
+        byte[] replyData;
+        if (head != null) {
+            replyData = new byte[3 + head.length];
+        } else {
+            replyData = new byte[3];
+        }
+        replyData[0] = (byte)code;
+        replyData[1] = (byte)(totalLength >> 8);
+        replyData[2] = (byte)totalLength;
+        if (head != null) {
+            System.arraycopy(head, 0, replyData, 3, head.length);
+        }
+        /*
+         * Write the OBEX DISCONNECT packet to the server. Byte 0: response code
+         * Byte 1&2: Connect Packet Length Byte 3 to n: headers
+         */
+        mOutput.write(replyData);
+        mOutput.flush();
+    }
+
+    /**
+     * Handles a connect request from a client. This method will read the rest
+     * of the request from the client. Assuming the request is valid, it will
+     * create a <code>HeaderSet</code> object to pass to the
+     * <code>ServerRequestHandler</code> object. After the handler processes the
+     * request, this method will create a reply message to send to the server
+     * with the response code provided.
+     * @throws IOException if an error occurred at the transport layer
+     */
+    private void handleConnectRequest() throws IOException {
+        int packetLength;
+        @SuppressWarnings("unused")
+        int version;
+        @SuppressWarnings("unused")
+        int flags;
+        int totalLength = 7;
+        byte[] head = null;
+        int code = -1;
+        HeaderSet request = new HeaderSet();
+        HeaderSet reply = new HeaderSet();
+        int bytesReceived;
+
+        /*
+         * Read in the length of the OBEX packet, OBEX version, flags, and max
+         * packet length
+         */
+        packetLength = mInput.read();
+        packetLength = (packetLength << 8) + mInput.read();
+        version = mInput.read();
+        flags = mInput.read();
+        mMaxPacketLength = mInput.read();
+        mMaxPacketLength = (mMaxPacketLength << 8) + mInput.read();
+
+        // should we check it?
+        if (mMaxPacketLength > ObexHelper.MAX_PACKET_SIZE_INT) {
+            mMaxPacketLength = ObexHelper.MAX_PACKET_SIZE_INT;
+        }
+
+        if (packetLength > ObexHelper.MAX_PACKET_SIZE_INT) {
+            code = ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE;
+            totalLength = 7;
+        } else {
+            if (packetLength > 7) {
+                byte[] headers = new byte[packetLength - 7];
+                bytesReceived = mInput.read(headers);
+
+                while (bytesReceived != headers.length) {
+                    bytesReceived += mInput.read(headers, bytesReceived, headers.length
+                            - bytesReceived);
+                }
+
+                ObexHelper.updateHeaderSet(request, headers);
+            }
+
+            if (request.mConnectionID != null) {
+                mListener.setConnectionId(ObexHelper.convertToLong(request.mConnectionID));
+            } else {
+                mListener.setConnectionId(1);
+            }
+
+            if (request.mAuthResp != null) {
+                if (!handleAuthResp(request.mAuthResp)) {
+                    code = ResponseCodes.OBEX_HTTP_UNAUTHORIZED;
+                    mListener.onAuthenticationFailure(ObexHelper.getTagValue((byte)0x01,
+                            request.mAuthResp));
+                }
+                request.mAuthResp = null;
+            }
+
+            if (code != ResponseCodes.OBEX_HTTP_UNAUTHORIZED) {
+                if (request.mAuthChall != null) {
+                    handleAuthChall(request);
+                    reply.mAuthResp = new byte[request.mAuthResp.length];
+                    System.arraycopy(request.mAuthResp, 0, reply.mAuthResp, 0,
+                            reply.mAuthResp.length);
+                    request.mAuthChall = null;
+                    request.mAuthResp = null;
+                }
+
+                try {
+                    code = mListener.onConnect(request, reply);
+                    code = validateResponseCode(code);
+
+                    if (reply.nonce != null) {
+                        mChallengeDigest = new byte[16];
+                        System.arraycopy(reply.nonce, 0, mChallengeDigest, 0, 16);
+                    } else {
+                        mChallengeDigest = null;
+                    }
+                    long id = mListener.getConnectionId();
+                    if (id == -1) {
+                        reply.mConnectionID = null;
+                    } else {
+                        reply.mConnectionID = ObexHelper.convertToByteArray(id);
+                    }
+
+                    head = ObexHelper.createHeader(reply, false);
+                    totalLength += head.length;
+
+                    if (totalLength > mMaxPacketLength) {
+                        totalLength = 7;
+                        head = null;
+                        code = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
+                    }
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    totalLength = 7;
+                    head = null;
+                    code = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
+                }
+
+            }
+        }
+
+        // Compute Length of OBEX CONNECT packet
+        byte[] length = ObexHelper.convertToByteArray(totalLength);
+
+        /*
+         * Write the OBEX CONNECT packet to the server. Byte 0: response code
+         * Byte 1&2: Connect Packet Length Byte 3: OBEX Version Number
+         * (Presently, 0x10) Byte 4: Flags (For TCP 0x00) Byte 5&6: Max OBEX
+         * Packet Length (Defined in MAX_PACKET_SIZE) Byte 7 to n: headers
+         */
+        byte[] sendData = new byte[totalLength];
+        sendData[0] = (byte)code;
+        sendData[1] = length[2];
+        sendData[2] = length[3];
+        sendData[3] = (byte)0x10;
+        sendData[4] = (byte)0x00;
+        sendData[5] = (byte)(ObexHelper.MAX_PACKET_SIZE_INT >> 8);
+        sendData[6] = (byte)(ObexHelper.MAX_PACKET_SIZE_INT & 0xFF);
+
+        if (head != null) {
+            System.arraycopy(head, 0, sendData, 7, head.length);
+        }
+
+        mOutput.write(sendData);
+        mOutput.flush();
+    }
+
+    /**
+     * Closes the server session - in detail close I/O streams and the
+     * underlying transport layer. Internal flag is also set so that later
+     * attempt to read/write will throw an exception.
+     */
+    public synchronized void close() {
+        if (mListener != null) {
+            mListener.onClose();
+        }
+        try {
+            mInput.close();
+            mOutput.close();
+            mTransport.close();
+            mClosed = true;
+        } catch (Exception e) {
+        }
+        mTransport = null;
+        mInput = null;
+        mOutput = null;
+        mListener = null;
+    }
+
+    /**
+     * Verifies that the response code is valid. If it is not valid, it will
+     * return the <code>OBEX_HTTP_INTERNAL_ERROR</code> response code.
+     * @param code the response code to check
+     * @return the valid response code or <code>OBEX_HTTP_INTERNAL_ERROR</code>
+     *         if <code>code</code> is not valid
+     */
+    private int validateResponseCode(int code) {
+
+        if ((code >= ResponseCodes.OBEX_HTTP_OK) && (code <= ResponseCodes.OBEX_HTTP_PARTIAL)) {
+            return code;
+        }
+        if ((code >= ResponseCodes.OBEX_HTTP_MULT_CHOICE)
+                && (code <= ResponseCodes.OBEX_HTTP_USE_PROXY)) {
+            return code;
+        }
+        if ((code >= ResponseCodes.OBEX_HTTP_BAD_REQUEST)
+                && (code <= ResponseCodes.OBEX_HTTP_UNSUPPORTED_TYPE)) {
+            return code;
+        }
+        if ((code >= ResponseCodes.OBEX_HTTP_INTERNAL_ERROR)
+                && (code <= ResponseCodes.OBEX_HTTP_VERSION)) {
+            return code;
+        }
+        if ((code >= ResponseCodes.OBEX_DATABASE_FULL)
+                && (code <= ResponseCodes.OBEX_DATABASE_LOCKED)) {
+            return code;
+        }
+        return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
+    }
+
+}
diff --git a/obex/javax/obex/SessionNotifier.java b/obex/javax/obex/SessionNotifier.java
new file mode 100644
index 0000000..9836dd6
--- /dev/null
+++ b/obex/javax/obex/SessionNotifier.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2008-2009, Motorola, Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package javax.obex;
+
+import java.io.IOException;
+
+/**
+ * The <code>SessionNotifier</code> interface defines a connection notifier for
+ * server-side OBEX connections. When a <code>SessionNotifier</code> is created
+ * and calls <code>acceptAndOpen()</code>, it will begin listening for clients
+ * to create a connection at the transport layer. When the transport layer
+ * connection is received, the <code>acceptAndOpen()</code> method will return a
+ * <code>javax.microedition.io.Connection</code> that is the connection to the
+ * client. The <code>acceptAndOpen()</code> method also takes a
+ * <code>ServerRequestHandler</code> argument that will process the requests
+ * from the client that connects to the server.
+ * @hide
+ */
+public interface SessionNotifier {
+
+    /**
+     * Waits for a transport layer connection to be established and specifies
+     * the handler to handle the requests from the client. No authenticator is
+     * associated with this connection, therefore, it is implementation
+     * dependent as to how an authentication challenge and authentication
+     * response header will be received and processed.
+     * <P>
+     * <H4>Additional Note for OBEX over Bluetooth</H4> If this method is called
+     * on a <code>SessionNotifier</code> object that does not have a
+     * <code>ServiceRecord</code> in the SDDB, the <code>ServiceRecord</code>
+     * for this object will be added to the SDDB. This method requests the BCC
+     * to put the local device in connectable mode so that it will respond to
+     * connection attempts by clients.
+     * <P>
+     * The following checks are done to verify that the service record provided
+     * is valid. If any of these checks fail, then a
+     * <code>ServiceRegistrationException</code> is thrown.
+     * <UL>
+     * <LI>ServiceClassIDList and ProtocolDescriptorList, the mandatory service
+     * attributes for a <code>btgoep</code> service record, must be present in
+     * the <code>ServiceRecord</code> associated with this notifier.
+     * <LI>L2CAP, RFCOMM and OBEX must all be in the ProtocolDescriptorList
+     * <LI>The <code>ServiceRecord</code> associated with this notifier must not
+     * have changed the RFCOMM server channel number
+     * </UL>
+     * <P>
+     * This method will not ensure that <code>ServiceRecord</code> associated
+     * with this notifier is a completely valid service record. It is the
+     * responsibility of the application to ensure that the service record
+     * follows all of the applicable syntactic and semantic rules for service
+     * record correctness.
+     * @param handler the request handler that will respond to OBEX requests
+     * @return the connection to the client
+     * @throws IOException if an error occurs in the transport layer
+     * @throws NullPointerException if <code>handler</code> is <code>null</code>
+     */
+    ObexSession acceptAndOpen(ServerRequestHandler handler) throws IOException;
+
+    /**
+     * Waits for a transport layer connection to be established and specifies
+     * the handler to handle the requests from the client and the
+     * <code>Authenticator</code> to use to respond to authentication challenge
+     * and authentication response headers.
+     * <P>
+     * <H4>Additional Note for OBEX over Bluetooth</H4> If this method is called
+     * on a <code>SessionNotifier</code> object that does not have a
+     * <code>ServiceRecord</code> in the SDDB, the <code>ServiceRecord</code>
+     * for this object will be added to the SDDB. This method requests the BCC
+     * to put the local device in connectable mode so that it will respond to
+     * connection attempts by clients.
+     * <P>
+     * The following checks are done to verify that the service record provided
+     * is valid. If any of these checks fail, then a
+     * <code>ServiceRegistrationException</code> is thrown.
+     * <UL>
+     * <LI>ServiceClassIDList and ProtocolDescriptorList, the mandatory service
+     * attributes for a <code>btgoep</code> service record, must be present in
+     * the <code>ServiceRecord</code> associated with this notifier.
+     * <LI>L2CAP, RFCOMM and OBEX must all be in the ProtocolDescriptorList
+     * <LI>The <code>ServiceRecord</code> associated with this notifier must not
+     * have changed the RFCOMM server channel number
+     * </UL>
+     * <P>
+     * This method will not ensure that <code>ServiceRecord</code> associated
+     * with this notifier is a completely valid service record. It is the
+     * responsibility of the application to ensure that the service record
+     * follows all of the applicable syntactic and semantic rules for service
+     * record correctness.
+     * @param handler the request handler that will respond to OBEX requests
+     * @param auth the <code>Authenticator</code> to use with this connection;
+     *        if <code>null</code> then no <code>Authenticator</code> will be
+     *        used
+     * @return the connection to the client
+     * @throws IOException if an error occurs in the transport layer
+     * @throws NullPointerException if <code>handler</code> is <code>null</code>
+     */
+    ObexSession acceptAndOpen(ServerRequestHandler handler, Authenticator auth) throws IOException;
+}
diff --git a/opengl/include/EGL/eglext.h b/opengl/include/EGL/eglext.h
index 25cfcb8..545fd0e 100644
--- a/opengl/include/EGL/eglext.h
+++ b/opengl/include/EGL/eglext.h
@@ -131,6 +131,30 @@
 /* Interfaces defined by EGL_KHR_image above */
 #endif
 
+
+#ifndef EGL_ANDROID_image_native_buffer
+#define EGL_ANDROID_image_native_buffer 1
+struct android_native_buffer_t;
+#define EGL_NATIVE_BUFFER_ANDROID       0x3140  /* eglCreateImageKHR target */
+#endif
+
+#ifndef EGL_ANDROID_get_render_buffer
+#define EGL_ANDROID_get_render_buffer 1
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLClientBuffer EGLAPIENTRY eglGetRenderBufferANDROID(EGLDisplay dpy, EGLSurface draw);
+#endif
+typedef EGLClientBuffer (EGLAPIENTRYP PFNEGLGETRENDERBUFFERANDROIDPROC) (EGLDisplay dpy, EGLSurface draw);
+#endif
+
+#ifndef EGL_ANDROID_swap_rectangle
+#define EGL_ANDROID_swap_rectangle 1
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglSetSwapRectangleANDROID (EGLDisplay dpy, EGLSurface draw, EGLint left, EGLint top, EGLint width, EGLint height);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSETSWAPRECTANGLEANDROIDPROC) (EGLDisplay dpy, EGLSurface draw, EGLint left, EGLint top, EGLint width, EGLint height);
+#endif
+
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/opengl/include/EGL/eglnatives.h b/opengl/include/EGL/eglnatives.h
deleted file mode 100644
index 21622dc..0000000
--- a/opengl/include/EGL/eglnatives.h
+++ /dev/null
@@ -1,271 +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.
- */
-
-#ifndef ANDROID_EGLNATIVES_H
-#define ANDROID_EGLNATIVES_H
-
-#include <sys/types.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*****************************************************************************/
-
-/* flags returned from swapBuffer */
-#define EGL_NATIVES_FLAG_SIZE_CHANGED       0x00000001
-
-/* surface flags */
-#define EGL_NATIVES_FLAG_DESTROY_BACKBUFFER 0x00000001
-
-enum native_pixel_format_t
-{
-    NATIVE_PIXEL_FORMAT_RGBA_8888   = 1,
-    NATIVE_PIXEL_FORMAT_RGB_565     = 4,
-    NATIVE_PIXEL_FORMAT_BGRA_8888   = 5,
-    NATIVE_PIXEL_FORMAT_RGBA_5551   = 6,
-    NATIVE_PIXEL_FORMAT_RGBA_4444   = 7,
-    NATIVE_PIXEL_FORMAT_YCbCr_422_SP= 0x10,
-    NATIVE_PIXEL_FORMAT_YCbCr_420_SP= 0x11,
-};
-
-enum native_memory_type_t
-{
-    NATIVE_MEMORY_TYPE_PMEM         = 0,
-    NATIVE_MEMORY_TYPE_GPU          = 1,
-    NATIVE_MEMORY_TYPE_FB           = 2,
-    NATIVE_MEMORY_TYPE_HEAP         = 128
-};
-
-
-struct egl_native_window_t
-{
-    /*
-     * magic must be set to 0x600913
-     */
-    uint32_t    magic;
-    
-    /*
-     * must be sizeof(egl_native_window_t)
-     */
-    uint32_t    version;
-
-    /*
-     * ident is reserved for the Android platform
-     */
-    uint32_t    ident;
-    
-    /*
-     * width, height and stride of the window in pixels
-     * Any of these value can be nul in which case GL commands are
-     * accepted and processed as usual, but not rendering occurs.
-     */
-    int         width;      // w=h=0 is legal
-    int         height;
-    int         stride;
-
-    /*
-     * format of the native window (see ui/PixelFormat.h)
-     */
-    int         format;
-    
-    /*
-     * Offset of the bits in the VRAM
-     */
-    intptr_t    offset;
-    
-    /*
-     * flags describing some attributes of this surface
-     * EGL_NATIVES_FLAG_DESTROY_BACKBUFFER: backbuffer not preserved after 
-     * eglSwapBuffers
-     */
-    uint32_t    flags;
-    
-    /*
-     * horizontal and vertical resolution in DPI
-     */
-    float       xdpi;
-    float       ydpi;
-    
-    /*
-     * refresh rate in frames per second (Hz)
-     */
-    float       fps;
-    
-    
-    /*
-     *  Base memory virtual address of the surface in the CPU side
-     */
-    intptr_t    base;
-    
-    /*
-     *  Heap the offset above is based from
-     */
-    int         fd;
-    
-    /*
-     *  Memory type the surface resides into
-     */
-    uint8_t     memory_type;
-    
-    /*
-     * Reserved for future use. MUST BE ZERO.
-     */
-    uint8_t     reserved_pad[3];
-    int         reserved[8];
-    
-    /*
-     * Vertical stride (only relevant with planar formats) 
-     */
-    
-    int         vstride;
-
-    /*
-     * Hook called by EGL to hold a reference on this structure
-     */
-    void        (*incRef)(struct egl_native_window_t* window);
-
-    /*
-     * Hook called by EGL to release a reference on this structure
-     */
-    void        (*decRef)(struct egl_native_window_t* window);
-
-    /*
-     * Hook called by EGL to perform a page flip. This function
-     * may update the size attributes above, in which case it returns
-     * the EGL_NATIVES_FLAG_SIZE_CHANGED bit set.
-     */
-    uint32_t    (*swapBuffers)(struct egl_native_window_t* window);
-    
-    /*
-     * Reserved for future use. MUST BE ZERO.
-     */
-    void        (*reserved_proc_0)(void);
-
-    /*
-     * Reserved for future use. MUST BE ZERO.
-     */
-    void        (*reserved_proc_1)(void);
-    
-    /*
-     * Reserved for future use. MUST BE ZERO.
-     */
-    void        (*reserved_proc_2)(void);
-
-    
-    /*
-     * Hook called by EGL when the native surface is associated to EGL
-     * (eglCreateWindowSurface). Can be NULL.
-     */
-    void        (*connect)(struct egl_native_window_t* window);
-
-    /*
-     * Hook called by EGL when eglDestroySurface is called.  Can be NULL.
-     */
-    void        (*disconnect)(struct egl_native_window_t* window);
-    
-    /*
-     * Reserved for future use. MUST BE ZERO.
-     */
-    void        (*reserved_proc[11])(void);
-    
-    /*
-     *  Some storage reserved for the oem driver.
-     */
-    intptr_t    oem[4];
-};
-
-
-struct egl_native_pixmap_t
-{
-    int32_t     version;    /* must be 32 */
-    int32_t     width;
-    int32_t     height;
-    int32_t     stride;
-    uint8_t*    data;
-    uint8_t     format;
-    uint8_t     rfu[3];
-    union {
-        uint32_t    compressedFormat;
-        int32_t     vstride;
-    };
-    int32_t     reserved;
-};
-
-/*****************************************************************************/
-
-/* 
- * This a convenience function to create a NativeWindowType surface
- * that maps to the whole screen
- * This function is actually implemented in libui.so
- */
-
-struct egl_native_window_t* android_createDisplaySurface();
-
-/*****************************************************************************/
-
-
-/*
- * OEM's egl's library (libhgl.so) must imlement these hooks to allocate
- * the GPU memory they need  
- */
-
-
-typedef struct
-{
-    // for internal use
-    void*   user;
-    // virtual address of this area
-    void*   base;
-    // size of this area in bytes
-    size_t  size;
-    // physical address of this area
-    void*   phys;
-    // offset in this area available to the GPU
-    size_t  offset;
-    // fd of this area
-    int     fd;
-} gpu_area_t;
-
-typedef struct
-{
-    // area where GPU registers are mapped
-    gpu_area_t regs;
-    // number of extra areas (currently limited to 2)
-    int32_t count;
-    // extra GPU areas (currently limited to 2)
-    gpu_area_t gpu[2];
-} request_gpu_t;
-
-
-typedef request_gpu_t* (*OEM_EGL_acquire_gpu_t)(void* user);
-typedef int (*OEM_EGL_release_gpu_t)(void* user, request_gpu_t* handle);
-typedef void (*register_gpu_t)
-        (void* user, OEM_EGL_acquire_gpu_t, OEM_EGL_release_gpu_t);
-
-void oem_register_gpu(
-        void* user,
-        OEM_EGL_acquire_gpu_t acquire,
-        OEM_EGL_release_gpu_t release);
-
-
-/*****************************************************************************/
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* ANDROID_EGLNATIVES_H */
diff --git a/opengl/include/EGL/eglplatform.h b/opengl/include/EGL/eglplatform.h
index ac00901..53e9e6116 100644
--- a/opengl/include/EGL/eglplatform.h
+++ b/opengl/include/EGL/eglplatform.h
@@ -89,9 +89,10 @@
 
 #elif defined(ANDROID)
 
-#include <EGL/eglnatives.h>
+struct android_native_window_t;
+struct egl_native_pixmap_t;
 
-typedef struct egl_native_window_t*     EGLNativeWindowType;
+typedef struct android_native_window_t* EGLNativeWindowType;
 typedef struct egl_native_pixmap_t*     EGLNativePixmapType;
 typedef void*                           EGLNativeDisplayType;
 
diff --git a/opengl/include/GLES/glplatform.h b/opengl/include/GLES/glplatform.h
index 0924cae..198e679 100644
--- a/opengl/include/GLES/glplatform.h
+++ b/opengl/include/GLES/glplatform.h
@@ -28,12 +28,6 @@
 
 #define GL_APIENTRY KHRONOS_APIENTRY
 
-// XXX: this should probably not be here
-#define GL_DIRECT_TEXTURE_2D_QUALCOMM               0x7E80
-
-// XXX: not sure how this is intended to be used
-#define GL_GLEXT_PROTOTYPES
-
 #endif
 
 #endif /* __glplatform_h_ */
diff --git a/opengl/include/GLES2/gl2.h b/opengl/include/GLES2/gl2.h
new file mode 100644
index 0000000..0182a67
--- /dev/null
+++ b/opengl/include/GLES2/gl2.h
@@ -0,0 +1,620 @@
+#ifndef __gl2_h_
+#define __gl2_h_
+
+/* $Revision: 7173 $ on $Date:: 2009-01-09 11:18:21 -0800 #$ */
+
+#include <GLES2/gl2platform.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * This document is licensed under the SGI Free Software B License Version
+ * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
+ */
+
+/*-------------------------------------------------------------------------
+ * Data type definitions
+ *-----------------------------------------------------------------------*/
+
+typedef void             GLvoid;
+typedef unsigned int     GLenum;
+typedef unsigned char    GLboolean;
+typedef unsigned int     GLbitfield;
+typedef khronos_int8_t   GLbyte;
+typedef short            GLshort;
+typedef int              GLint;
+typedef int              GLsizei;
+typedef khronos_uint8_t  GLubyte;
+typedef unsigned short   GLushort;
+typedef unsigned int     GLuint;
+typedef khronos_float_t  GLfloat;
+typedef khronos_float_t  GLclampf;
+typedef khronos_int32_t  GLfixed;
+
+/* GL types for handling large vertex buffer objects */
+typedef khronos_intptr_t GLintptr;
+typedef khronos_ssize_t  GLsizeiptr;
+
+/* OpenGL ES core versions */
+#define GL_ES_VERSION_2_0                 1
+
+/* ClearBufferMask */
+#define GL_DEPTH_BUFFER_BIT               0x00000100
+#define GL_STENCIL_BUFFER_BIT             0x00000400
+#define GL_COLOR_BUFFER_BIT               0x00004000
+
+/* Boolean */
+#define GL_FALSE                          0
+#define GL_TRUE                           1
+
+/* BeginMode */
+#define GL_POINTS                         0x0000
+#define GL_LINES                          0x0001
+#define GL_LINE_LOOP                      0x0002
+#define GL_LINE_STRIP                     0x0003
+#define GL_TRIANGLES                      0x0004
+#define GL_TRIANGLE_STRIP                 0x0005
+#define GL_TRIANGLE_FAN                   0x0006
+
+/* AlphaFunction (not supported in ES20) */
+/*      GL_NEVER */
+/*      GL_LESS */
+/*      GL_EQUAL */
+/*      GL_LEQUAL */
+/*      GL_GREATER */
+/*      GL_NOTEQUAL */
+/*      GL_GEQUAL */
+/*      GL_ALWAYS */
+
+/* BlendingFactorDest */
+#define GL_ZERO                           0
+#define GL_ONE                            1
+#define GL_SRC_COLOR                      0x0300
+#define GL_ONE_MINUS_SRC_COLOR            0x0301
+#define GL_SRC_ALPHA                      0x0302
+#define GL_ONE_MINUS_SRC_ALPHA            0x0303
+#define GL_DST_ALPHA                      0x0304
+#define GL_ONE_MINUS_DST_ALPHA            0x0305
+
+/* BlendingFactorSrc */
+/*      GL_ZERO */
+/*      GL_ONE */
+#define GL_DST_COLOR                      0x0306
+#define GL_ONE_MINUS_DST_COLOR            0x0307
+#define GL_SRC_ALPHA_SATURATE             0x0308
+/*      GL_SRC_ALPHA */
+/*      GL_ONE_MINUS_SRC_ALPHA */
+/*      GL_DST_ALPHA */
+/*      GL_ONE_MINUS_DST_ALPHA */
+
+/* BlendEquationSeparate */
+#define GL_FUNC_ADD                       0x8006
+#define GL_BLEND_EQUATION                 0x8009
+#define GL_BLEND_EQUATION_RGB             0x8009    /* same as BLEND_EQUATION */
+#define GL_BLEND_EQUATION_ALPHA           0x883D
+
+/* BlendSubtract */
+#define GL_FUNC_SUBTRACT                  0x800A
+#define GL_FUNC_REVERSE_SUBTRACT          0x800B
+
+/* Separate Blend Functions */
+#define GL_BLEND_DST_RGB                  0x80C8
+#define GL_BLEND_SRC_RGB                  0x80C9
+#define GL_BLEND_DST_ALPHA                0x80CA
+#define GL_BLEND_SRC_ALPHA                0x80CB
+#define GL_CONSTANT_COLOR                 0x8001
+#define GL_ONE_MINUS_CONSTANT_COLOR       0x8002
+#define GL_CONSTANT_ALPHA                 0x8003
+#define GL_ONE_MINUS_CONSTANT_ALPHA       0x8004
+#define GL_BLEND_COLOR                    0x8005
+
+/* Buffer Objects */
+#define GL_ARRAY_BUFFER                   0x8892
+#define GL_ELEMENT_ARRAY_BUFFER           0x8893
+#define GL_ARRAY_BUFFER_BINDING           0x8894
+#define GL_ELEMENT_ARRAY_BUFFER_BINDING   0x8895
+
+#define GL_STREAM_DRAW                    0x88E0
+#define GL_STATIC_DRAW                    0x88E4
+#define GL_DYNAMIC_DRAW                   0x88E8
+
+#define GL_BUFFER_SIZE                    0x8764
+#define GL_BUFFER_USAGE                   0x8765
+
+#define GL_CURRENT_VERTEX_ATTRIB          0x8626
+
+/* CullFaceMode */
+#define GL_FRONT                          0x0404
+#define GL_BACK                           0x0405
+#define GL_FRONT_AND_BACK                 0x0408
+
+/* DepthFunction */
+/*      GL_NEVER */
+/*      GL_LESS */
+/*      GL_EQUAL */
+/*      GL_LEQUAL */
+/*      GL_GREATER */
+/*      GL_NOTEQUAL */
+/*      GL_GEQUAL */
+/*      GL_ALWAYS */
+
+/* EnableCap */
+#define GL_TEXTURE_2D                     0x0DE1
+#define GL_CULL_FACE                      0x0B44
+#define GL_BLEND                          0x0BE2
+#define GL_DITHER                         0x0BD0
+#define GL_STENCIL_TEST                   0x0B90
+#define GL_DEPTH_TEST                     0x0B71
+#define GL_SCISSOR_TEST                   0x0C11
+#define GL_POLYGON_OFFSET_FILL            0x8037
+#define GL_SAMPLE_ALPHA_TO_COVERAGE       0x809E
+#define GL_SAMPLE_COVERAGE                0x80A0
+
+/* ErrorCode */
+#define GL_NO_ERROR                       0
+#define GL_INVALID_ENUM                   0x0500
+#define GL_INVALID_VALUE                  0x0501
+#define GL_INVALID_OPERATION              0x0502
+#define GL_OUT_OF_MEMORY                  0x0505
+
+/* FrontFaceDirection */
+#define GL_CW                             0x0900
+#define GL_CCW                            0x0901
+
+/* GetPName */
+#define GL_LINE_WIDTH                     0x0B21
+#define GL_ALIASED_POINT_SIZE_RANGE       0x846D
+#define GL_ALIASED_LINE_WIDTH_RANGE       0x846E
+#define GL_CULL_FACE_MODE                 0x0B45
+#define GL_FRONT_FACE                     0x0B46
+#define GL_DEPTH_RANGE                    0x0B70
+#define GL_DEPTH_WRITEMASK                0x0B72
+#define GL_DEPTH_CLEAR_VALUE              0x0B73
+#define GL_DEPTH_FUNC                     0x0B74
+#define GL_STENCIL_CLEAR_VALUE            0x0B91
+#define GL_STENCIL_FUNC                   0x0B92
+#define GL_STENCIL_FAIL                   0x0B94
+#define GL_STENCIL_PASS_DEPTH_FAIL        0x0B95
+#define GL_STENCIL_PASS_DEPTH_PASS        0x0B96
+#define GL_STENCIL_REF                    0x0B97
+#define GL_STENCIL_VALUE_MASK             0x0B93
+#define GL_STENCIL_WRITEMASK              0x0B98
+#define GL_STENCIL_BACK_FUNC              0x8800
+#define GL_STENCIL_BACK_FAIL              0x8801
+#define GL_STENCIL_BACK_PASS_DEPTH_FAIL   0x8802
+#define GL_STENCIL_BACK_PASS_DEPTH_PASS   0x8803
+#define GL_STENCIL_BACK_REF               0x8CA3
+#define GL_STENCIL_BACK_VALUE_MASK        0x8CA4
+#define GL_STENCIL_BACK_WRITEMASK         0x8CA5
+#define GL_VIEWPORT                       0x0BA2
+#define GL_SCISSOR_BOX                    0x0C10
+/*      GL_SCISSOR_TEST */
+#define GL_COLOR_CLEAR_VALUE              0x0C22
+#define GL_COLOR_WRITEMASK                0x0C23
+#define GL_UNPACK_ALIGNMENT               0x0CF5
+#define GL_PACK_ALIGNMENT                 0x0D05
+#define GL_MAX_TEXTURE_SIZE               0x0D33
+#define GL_MAX_VIEWPORT_DIMS              0x0D3A
+#define GL_SUBPIXEL_BITS                  0x0D50
+#define GL_RED_BITS                       0x0D52
+#define GL_GREEN_BITS                     0x0D53
+#define GL_BLUE_BITS                      0x0D54
+#define GL_ALPHA_BITS                     0x0D55
+#define GL_DEPTH_BITS                     0x0D56
+#define GL_STENCIL_BITS                   0x0D57
+#define GL_POLYGON_OFFSET_UNITS           0x2A00
+/*      GL_POLYGON_OFFSET_FILL */
+#define GL_POLYGON_OFFSET_FACTOR          0x8038
+#define GL_TEXTURE_BINDING_2D             0x8069
+#define GL_SAMPLE_BUFFERS                 0x80A8
+#define GL_SAMPLES                        0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE          0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT         0x80AB
+
+/* GetTextureParameter */
+/*      GL_TEXTURE_MAG_FILTER */
+/*      GL_TEXTURE_MIN_FILTER */
+/*      GL_TEXTURE_WRAP_S */
+/*      GL_TEXTURE_WRAP_T */
+
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS     0x86A3
+
+/* HintMode */
+#define GL_DONT_CARE                      0x1100
+#define GL_FASTEST                        0x1101
+#define GL_NICEST                         0x1102
+
+/* HintTarget */
+#define GL_GENERATE_MIPMAP_HINT            0x8192
+
+/* DataType */
+#define GL_BYTE                           0x1400
+#define GL_UNSIGNED_BYTE                  0x1401
+#define GL_SHORT                          0x1402
+#define GL_UNSIGNED_SHORT                 0x1403
+#define GL_INT                            0x1404
+#define GL_UNSIGNED_INT                   0x1405
+#define GL_FLOAT                          0x1406
+#define GL_FIXED                          0x140C
+
+/* PixelFormat */
+#define GL_DEPTH_COMPONENT                0x1902
+#define GL_ALPHA                          0x1906
+#define GL_RGB                            0x1907
+#define GL_RGBA                           0x1908
+#define GL_LUMINANCE                      0x1909
+#define GL_LUMINANCE_ALPHA                0x190A
+
+/* PixelType */
+/*      GL_UNSIGNED_BYTE */
+#define GL_UNSIGNED_SHORT_4_4_4_4         0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1         0x8034
+#define GL_UNSIGNED_SHORT_5_6_5           0x8363
+
+/* Shaders */
+#define GL_FRAGMENT_SHADER                  0x8B30
+#define GL_VERTEX_SHADER                    0x8B31
+#define GL_MAX_VERTEX_ATTRIBS               0x8869
+#define GL_MAX_VERTEX_UNIFORM_VECTORS       0x8DFB
+#define GL_MAX_VARYING_VECTORS              0x8DFC
+#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
+#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS   0x8B4C
+#define GL_MAX_TEXTURE_IMAGE_UNITS          0x8872
+#define GL_MAX_FRAGMENT_UNIFORM_VECTORS     0x8DFD
+#define GL_SHADER_TYPE                      0x8B4F
+#define GL_DELETE_STATUS                    0x8B80
+#define GL_LINK_STATUS                      0x8B82
+#define GL_VALIDATE_STATUS                  0x8B83
+#define GL_ATTACHED_SHADERS                 0x8B85
+#define GL_ACTIVE_UNIFORMS                  0x8B86
+#define GL_ACTIVE_UNIFORM_MAX_LENGTH        0x8B87
+#define GL_ACTIVE_ATTRIBUTES                0x8B89
+#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH      0x8B8A
+#define GL_SHADING_LANGUAGE_VERSION         0x8B8C
+#define GL_CURRENT_PROGRAM                  0x8B8D
+
+/* StencilFunction */
+#define GL_NEVER                          0x0200
+#define GL_LESS                           0x0201
+#define GL_EQUAL                          0x0202
+#define GL_LEQUAL                         0x0203
+#define GL_GREATER                        0x0204
+#define GL_NOTEQUAL                       0x0205
+#define GL_GEQUAL                         0x0206
+#define GL_ALWAYS                         0x0207
+
+/* StencilOp */
+/*      GL_ZERO */
+#define GL_KEEP                           0x1E00
+#define GL_REPLACE                        0x1E01
+#define GL_INCR                           0x1E02
+#define GL_DECR                           0x1E03
+#define GL_INVERT                         0x150A
+#define GL_INCR_WRAP                      0x8507
+#define GL_DECR_WRAP                      0x8508
+
+/* StringName */
+#define GL_VENDOR                         0x1F00
+#define GL_RENDERER                       0x1F01
+#define GL_VERSION                        0x1F02
+#define GL_EXTENSIONS                     0x1F03
+
+/* TextureMagFilter */
+#define GL_NEAREST                        0x2600
+#define GL_LINEAR                         0x2601
+
+/* TextureMinFilter */
+/*      GL_NEAREST */
+/*      GL_LINEAR */
+#define GL_NEAREST_MIPMAP_NEAREST         0x2700
+#define GL_LINEAR_MIPMAP_NEAREST          0x2701
+#define GL_NEAREST_MIPMAP_LINEAR          0x2702
+#define GL_LINEAR_MIPMAP_LINEAR           0x2703
+
+/* TextureParameterName */
+#define GL_TEXTURE_MAG_FILTER             0x2800
+#define GL_TEXTURE_MIN_FILTER             0x2801
+#define GL_TEXTURE_WRAP_S                 0x2802
+#define GL_TEXTURE_WRAP_T                 0x2803
+
+/* TextureTarget */
+/*      GL_TEXTURE_2D */
+#define GL_TEXTURE                        0x1702
+
+#define GL_TEXTURE_CUBE_MAP               0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP       0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X    0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X    0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y    0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y    0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z    0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z    0x851A
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE      0x851C
+
+/* TextureUnit */
+#define GL_TEXTURE0                       0x84C0
+#define GL_TEXTURE1                       0x84C1
+#define GL_TEXTURE2                       0x84C2
+#define GL_TEXTURE3                       0x84C3
+#define GL_TEXTURE4                       0x84C4
+#define GL_TEXTURE5                       0x84C5
+#define GL_TEXTURE6                       0x84C6
+#define GL_TEXTURE7                       0x84C7
+#define GL_TEXTURE8                       0x84C8
+#define GL_TEXTURE9                       0x84C9
+#define GL_TEXTURE10                      0x84CA
+#define GL_TEXTURE11                      0x84CB
+#define GL_TEXTURE12                      0x84CC
+#define GL_TEXTURE13                      0x84CD
+#define GL_TEXTURE14                      0x84CE
+#define GL_TEXTURE15                      0x84CF
+#define GL_TEXTURE16                      0x84D0
+#define GL_TEXTURE17                      0x84D1
+#define GL_TEXTURE18                      0x84D2
+#define GL_TEXTURE19                      0x84D3
+#define GL_TEXTURE20                      0x84D4
+#define GL_TEXTURE21                      0x84D5
+#define GL_TEXTURE22                      0x84D6
+#define GL_TEXTURE23                      0x84D7
+#define GL_TEXTURE24                      0x84D8
+#define GL_TEXTURE25                      0x84D9
+#define GL_TEXTURE26                      0x84DA
+#define GL_TEXTURE27                      0x84DB
+#define GL_TEXTURE28                      0x84DC
+#define GL_TEXTURE29                      0x84DD
+#define GL_TEXTURE30                      0x84DE
+#define GL_TEXTURE31                      0x84DF
+#define GL_ACTIVE_TEXTURE                 0x84E0
+
+/* TextureWrapMode */
+#define GL_REPEAT                         0x2901
+#define GL_CLAMP_TO_EDGE                  0x812F
+#define GL_MIRRORED_REPEAT                0x8370
+
+/* Uniform Types */
+#define GL_FLOAT_VEC2                     0x8B50
+#define GL_FLOAT_VEC3                     0x8B51
+#define GL_FLOAT_VEC4                     0x8B52
+#define GL_INT_VEC2                       0x8B53
+#define GL_INT_VEC3                       0x8B54
+#define GL_INT_VEC4                       0x8B55
+#define GL_BOOL                           0x8B56
+#define GL_BOOL_VEC2                      0x8B57
+#define GL_BOOL_VEC3                      0x8B58
+#define GL_BOOL_VEC4                      0x8B59
+#define GL_FLOAT_MAT2                     0x8B5A
+#define GL_FLOAT_MAT3                     0x8B5B
+#define GL_FLOAT_MAT4                     0x8B5C
+#define GL_SAMPLER_2D                     0x8B5E
+#define GL_SAMPLER_CUBE                   0x8B60
+
+/* Vertex Arrays */
+#define GL_VERTEX_ATTRIB_ARRAY_ENABLED        0x8622
+#define GL_VERTEX_ATTRIB_ARRAY_SIZE           0x8623
+#define GL_VERTEX_ATTRIB_ARRAY_STRIDE         0x8624
+#define GL_VERTEX_ATTRIB_ARRAY_TYPE           0x8625
+#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED     0x886A
+#define GL_VERTEX_ATTRIB_ARRAY_POINTER        0x8645
+#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
+
+/* Read Format */
+#define GL_IMPLEMENTATION_COLOR_READ_TYPE   0x8B9A
+#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B
+
+/* Shader Source */
+#define GL_COMPILE_STATUS                 0x8B81
+#define GL_INFO_LOG_LENGTH                0x8B84
+#define GL_SHADER_SOURCE_LENGTH           0x8B88
+#define GL_SHADER_COMPILER                0x8DFA
+
+/* Shader Binary */
+#define GL_SHADER_BINARY_FORMATS          0x8DF8
+#define GL_NUM_SHADER_BINARY_FORMATS      0x8DF9
+
+/* Shader Precision-Specified Types */
+#define GL_LOW_FLOAT                      0x8DF0
+#define GL_MEDIUM_FLOAT                   0x8DF1
+#define GL_HIGH_FLOAT                     0x8DF2
+#define GL_LOW_INT                        0x8DF3
+#define GL_MEDIUM_INT                     0x8DF4
+#define GL_HIGH_INT                       0x8DF5
+
+/* Framebuffer Object. */
+#define GL_FRAMEBUFFER                    0x8D40
+#define GL_RENDERBUFFER                   0x8D41
+
+#define GL_RGBA4                          0x8056
+#define GL_RGB5_A1                        0x8057
+#define GL_RGB565                         0x8D62
+#define GL_DEPTH_COMPONENT16              0x81A5
+#define GL_STENCIL_INDEX                  0x1901
+#define GL_STENCIL_INDEX8                 0x8D48
+
+#define GL_RENDERBUFFER_WIDTH             0x8D42
+#define GL_RENDERBUFFER_HEIGHT            0x8D43
+#define GL_RENDERBUFFER_INTERNAL_FORMAT   0x8D44
+#define GL_RENDERBUFFER_RED_SIZE          0x8D50
+#define GL_RENDERBUFFER_GREEN_SIZE        0x8D51
+#define GL_RENDERBUFFER_BLUE_SIZE         0x8D52
+#define GL_RENDERBUFFER_ALPHA_SIZE        0x8D53
+#define GL_RENDERBUFFER_DEPTH_SIZE        0x8D54
+#define GL_RENDERBUFFER_STENCIL_SIZE      0x8D55
+
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE           0x8CD0
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME           0x8CD1
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL         0x8CD2
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3
+
+#define GL_COLOR_ATTACHMENT0              0x8CE0
+#define GL_DEPTH_ATTACHMENT               0x8D00
+#define GL_STENCIL_ATTACHMENT             0x8D20
+
+#define GL_NONE                           0
+
+#define GL_FRAMEBUFFER_COMPLETE                      0x8CD5
+#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT         0x8CD6
+#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
+#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS         0x8CD9
+#define GL_FRAMEBUFFER_UNSUPPORTED                   0x8CDD
+
+#define GL_FRAMEBUFFER_BINDING            0x8CA6
+#define GL_RENDERBUFFER_BINDING           0x8CA7
+#define GL_MAX_RENDERBUFFER_SIZE          0x84E8
+
+#define GL_INVALID_FRAMEBUFFER_OPERATION  0x0506
+
+/*-------------------------------------------------------------------------
+ * GL core functions.
+ *-----------------------------------------------------------------------*/
+
+GL_APICALL void         GL_APIENTRY glActiveTexture (GLenum texture);
+GL_APICALL void         GL_APIENTRY glAttachShader (GLuint program, GLuint shader);
+GL_APICALL void         GL_APIENTRY glBindAttribLocation (GLuint program, GLuint index, const char* name);
+GL_APICALL void         GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer);
+GL_APICALL void         GL_APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer);
+GL_APICALL void         GL_APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer);
+GL_APICALL void         GL_APIENTRY glBindTexture (GLenum target, GLuint texture);
+GL_APICALL void         GL_APIENTRY glBlendColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+GL_APICALL void         GL_APIENTRY glBlendEquation ( GLenum mode );
+GL_APICALL void         GL_APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
+GL_APICALL void         GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor);
+GL_APICALL void         GL_APIENTRY glBlendFuncSeparate (GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+GL_APICALL void         GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void* data, GLenum usage);
+GL_APICALL void         GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void* data);
+GL_APICALL GLenum       GL_APIENTRY glCheckFramebufferStatus (GLenum target);
+GL_APICALL void         GL_APIENTRY glClear (GLbitfield mask);
+GL_APICALL void         GL_APIENTRY glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+GL_APICALL void         GL_APIENTRY glClearDepthf (GLclampf depth);
+GL_APICALL void         GL_APIENTRY glClearStencil (GLint s);
+GL_APICALL void         GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+GL_APICALL void         GL_APIENTRY glCompileShader (GLuint shader);
+GL_APICALL void         GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data);
+GL_APICALL void         GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data);
+GL_APICALL void         GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+GL_APICALL void         GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GL_APICALL GLuint       GL_APIENTRY glCreateProgram (void);
+GL_APICALL GLuint       GL_APIENTRY glCreateShader (GLenum type);
+GL_APICALL void         GL_APIENTRY glCullFace (GLenum mode);
+GL_APICALL void         GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint* buffers);
+GL_APICALL void         GL_APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint* framebuffers);
+GL_APICALL void         GL_APIENTRY glDeleteProgram (GLuint program);
+GL_APICALL void         GL_APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint* renderbuffers);
+GL_APICALL void         GL_APIENTRY glDeleteShader (GLuint shader);
+GL_APICALL void         GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint* textures);
+GL_APICALL void         GL_APIENTRY glDepthFunc (GLenum func);
+GL_APICALL void         GL_APIENTRY glDepthMask (GLboolean flag);
+GL_APICALL void         GL_APIENTRY glDepthRangef (GLclampf zNear, GLclampf zFar);
+GL_APICALL void         GL_APIENTRY glDetachShader (GLuint program, GLuint shader);
+GL_APICALL void         GL_APIENTRY glDisable (GLenum cap);
+GL_APICALL void         GL_APIENTRY glDisableVertexAttribArray (GLuint index);
+GL_APICALL void         GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count);
+GL_APICALL void         GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void* indices);
+GL_APICALL void         GL_APIENTRY glEnable (GLenum cap);
+GL_APICALL void         GL_APIENTRY glEnableVertexAttribArray (GLuint index);
+GL_APICALL void         GL_APIENTRY glFinish (void);
+GL_APICALL void         GL_APIENTRY glFlush (void);
+GL_APICALL void         GL_APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+GL_APICALL void         GL_APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+GL_APICALL void         GL_APIENTRY glFrontFace (GLenum mode);
+GL_APICALL void         GL_APIENTRY glGenBuffers (GLsizei n, GLuint* buffers);
+GL_APICALL void         GL_APIENTRY glGenerateMipmap (GLenum target);
+GL_APICALL void         GL_APIENTRY glGenFramebuffers (GLsizei n, GLuint* framebuffers);
+GL_APICALL void         GL_APIENTRY glGenRenderbuffers (GLsizei n, GLuint* renderbuffers);
+GL_APICALL void         GL_APIENTRY glGenTextures (GLsizei n, GLuint* textures);
+GL_APICALL void         GL_APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name);
+GL_APICALL void         GL_APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name);
+GL_APICALL void         GL_APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders);
+GL_APICALL int          GL_APIENTRY glGetAttribLocation (GLuint program, const char* name);
+GL_APICALL void         GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean* params);
+GL_APICALL void         GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint* params);
+GL_APICALL GLenum       GL_APIENTRY glGetError (void);
+GL_APICALL void         GL_APIENTRY glGetFloatv (GLenum pname, GLfloat* params);
+GL_APICALL void         GL_APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetIntegerv (GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufsize, GLsizei* length, char* infolog);
+GL_APICALL void         GL_APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog);
+GL_APICALL void         GL_APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision);
+GL_APICALL void         GL_APIENTRY glGetShaderSource (GLuint shader, GLsizei bufsize, GLsizei* length, char* source);
+GL_APICALL const GLubyte* GL_APIENTRY glGetString (GLenum name);
+GL_APICALL void         GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat* params);
+GL_APICALL void         GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat* params);
+GL_APICALL void         GL_APIENTRY glGetUniformiv (GLuint program, GLint location, GLint* params);
+GL_APICALL int          GL_APIENTRY glGetUniformLocation (GLuint program, const char* name);
+GL_APICALL void         GL_APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat* params);
+GL_APICALL void         GL_APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void** pointer);
+GL_APICALL void         GL_APIENTRY glHint (GLenum target, GLenum mode);
+GL_APICALL GLboolean    GL_APIENTRY glIsBuffer (GLuint buffer);
+GL_APICALL GLboolean    GL_APIENTRY glIsEnabled (GLenum cap);
+GL_APICALL GLboolean    GL_APIENTRY glIsFramebuffer (GLuint framebuffer);
+GL_APICALL GLboolean    GL_APIENTRY glIsProgram (GLuint program);
+GL_APICALL GLboolean    GL_APIENTRY glIsRenderbuffer (GLuint renderbuffer);
+GL_APICALL GLboolean    GL_APIENTRY glIsShader (GLuint shader);
+GL_APICALL GLboolean    GL_APIENTRY glIsTexture (GLuint texture);
+GL_APICALL void         GL_APIENTRY glLineWidth (GLfloat width);
+GL_APICALL void         GL_APIENTRY glLinkProgram (GLuint program);
+GL_APICALL void         GL_APIENTRY glPixelStorei (GLenum pname, GLint param);
+GL_APICALL void         GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units);
+GL_APICALL void         GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels);
+GL_APICALL void         GL_APIENTRY glReleaseShaderCompiler (void);
+GL_APICALL void         GL_APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+GL_APICALL void         GL_APIENTRY glSampleCoverage (GLclampf value, GLboolean invert);
+GL_APICALL void         GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
+GL_APICALL void         GL_APIENTRY glShaderBinary (GLsizei n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLsizei length);
+GL_APICALL void         GL_APIENTRY glShaderSource (GLuint shader, GLsizei count, const char** string, const GLint* length);
+GL_APICALL void         GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask);
+GL_APICALL void         GL_APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask);
+GL_APICALL void         GL_APIENTRY glStencilMask (GLuint mask);
+GL_APICALL void         GL_APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask);
+GL_APICALL void         GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass);
+GL_APICALL void         GL_APIENTRY glStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
+GL_APICALL void         GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat,  GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels);
+GL_APICALL void         GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param);
+GL_APICALL void         GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat* params);
+GL_APICALL void         GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
+GL_APICALL void         GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint* params);
+GL_APICALL void         GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels);
+GL_APICALL void         GL_APIENTRY glUniform1f (GLint location, GLfloat x);
+GL_APICALL void         GL_APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat* v);
+GL_APICALL void         GL_APIENTRY glUniform1i (GLint location, GLint x);
+GL_APICALL void         GL_APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint* v);
+GL_APICALL void         GL_APIENTRY glUniform2f (GLint location, GLfloat x, GLfloat y);
+GL_APICALL void         GL_APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat* v);
+GL_APICALL void         GL_APIENTRY glUniform2i (GLint location, GLint x, GLint y);
+GL_APICALL void         GL_APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint* v);
+GL_APICALL void         GL_APIENTRY glUniform3f (GLint location, GLfloat x, GLfloat y, GLfloat z);
+GL_APICALL void         GL_APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat* v);
+GL_APICALL void         GL_APIENTRY glUniform3i (GLint location, GLint x, GLint y, GLint z);
+GL_APICALL void         GL_APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint* v);
+GL_APICALL void         GL_APIENTRY glUniform4f (GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GL_APICALL void         GL_APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat* v);
+GL_APICALL void         GL_APIENTRY glUniform4i (GLint location, GLint x, GLint y, GLint z, GLint w);
+GL_APICALL void         GL_APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint* v);
+GL_APICALL void         GL_APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
+GL_APICALL void         GL_APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
+GL_APICALL void         GL_APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
+GL_APICALL void         GL_APIENTRY glUseProgram (GLuint program);
+GL_APICALL void         GL_APIENTRY glValidateProgram (GLuint program);
+GL_APICALL void         GL_APIENTRY glVertexAttrib1f (GLuint indx, GLfloat x);
+GL_APICALL void         GL_APIENTRY glVertexAttrib1fv (GLuint indx, const GLfloat* values);
+GL_APICALL void         GL_APIENTRY glVertexAttrib2f (GLuint indx, GLfloat x, GLfloat y);
+GL_APICALL void         GL_APIENTRY glVertexAttrib2fv (GLuint indx, const GLfloat* values);
+GL_APICALL void         GL_APIENTRY glVertexAttrib3f (GLuint indx, GLfloat x, GLfloat y, GLfloat z);
+GL_APICALL void         GL_APIENTRY glVertexAttrib3fv (GLuint indx, const GLfloat* values);
+GL_APICALL void         GL_APIENTRY glVertexAttrib4f (GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GL_APICALL void         GL_APIENTRY glVertexAttrib4fv (GLuint indx, const GLfloat* values);
+GL_APICALL void         GL_APIENTRY glVertexAttribPointer (GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr);
+GL_APICALL void         GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gl2_h_ */
diff --git a/opengl/include/GLES2/gl2ext.h b/opengl/include/GLES2/gl2ext.h
new file mode 100644
index 0000000..72f1ae7
--- /dev/null
+++ b/opengl/include/GLES2/gl2ext.h
@@ -0,0 +1,518 @@
+#ifndef __gl2ext_h_
+#define __gl2ext_h_
+
+/* $Revision: 8271 $ on $Date:: 2009-05-21 09:33:40 -0700 #$ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * This document is licensed under the SGI Free Software B License Version
+ * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
+ */
+
+#ifndef GL_APIENTRYP
+#   define GL_APIENTRYP GL_APIENTRY*
+#endif
+
+/*------------------------------------------------------------------------*
+ * OES extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_OES_compressed_ETC1_RGB8_texture */
+#ifndef GL_OES_compressed_ETC1_RGB8_texture
+#define GL_ETC1_RGB8_OES                                        0x8D64
+#endif
+
+/* GL_OES_compressed_paletted_texture */
+#ifndef GL_OES_compressed_paletted_texture
+#define GL_PALETTE4_RGB8_OES                                    0x8B90
+#define GL_PALETTE4_RGBA8_OES                                   0x8B91
+#define GL_PALETTE4_R5_G6_B5_OES                                0x8B92
+#define GL_PALETTE4_RGBA4_OES                                   0x8B93
+#define GL_PALETTE4_RGB5_A1_OES                                 0x8B94
+#define GL_PALETTE8_RGB8_OES                                    0x8B95
+#define GL_PALETTE8_RGBA8_OES                                   0x8B96
+#define GL_PALETTE8_R5_G6_B5_OES                                0x8B97
+#define GL_PALETTE8_RGBA4_OES                                   0x8B98
+#define GL_PALETTE8_RGB5_A1_OES                                 0x8B99
+#endif
+
+/* GL_OES_depth24 */
+#ifndef GL_OES_depth24
+#define GL_DEPTH_COMPONENT24_OES                                0x81A6
+#endif
+
+/* GL_OES_depth32 */
+#ifndef GL_OES_depth32
+#define GL_DEPTH_COMPONENT32_OES                                0x81A7
+#endif
+
+/* GL_OES_depth_texture */
+/* No new tokens introduced by this extension. */
+
+/* GL_OES_EGL_image */
+#ifndef GL_OES_EGL_image
+typedef void* GLeglImageOES;
+#endif
+
+/* GL_OES_get_program_binary */
+#ifndef GL_OES_get_program_binary
+#define GL_PROGRAM_BINARY_LENGTH_OES                            0x8741
+#define GL_NUM_PROGRAM_BINARY_FORMATS_OES                       0x87FE
+#define GL_PROGRAM_BINARY_FORMATS_OES                           0x87FF
+#endif
+
+/* GL_OES_mapbuffer */
+#ifndef GL_OES_mapbuffer
+#define GL_WRITE_ONLY_OES                                       0x88B9
+#define GL_BUFFER_ACCESS_OES                                    0x88BB
+#define GL_BUFFER_MAPPED_OES                                    0x88BC
+#define GL_BUFFER_MAP_POINTER_OES                               0x88BD
+#endif
+
+/* GL_OES_packed_depth_stencil */
+#ifndef GL_OES_packed_depth_stencil
+#define GL_DEPTH_STENCIL_OES                                    0x84F9
+#define GL_UNSIGNED_INT_24_8_OES                                0x84FA
+#define GL_DEPTH24_STENCIL8_OES                                 0x88F0
+#endif
+
+/* GL_OES_rgb8_rgba8 */
+#ifndef GL_OES_rgb8_rgba8
+#define GL_RGB8_OES                                             0x8051
+#define GL_RGBA8_OES                                            0x8058
+#endif
+
+/* GL_OES_standard_derivatives */
+#ifndef GL_OES_standard_derivatives
+#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES                  0x8B8B
+#endif
+
+/* GL_OES_stencil1 */
+#ifndef GL_OES_stencil1
+#define GL_STENCIL_INDEX1_OES                                   0x8D46
+#endif
+
+/* GL_OES_stencil4 */
+#ifndef GL_OES_stencil4
+#define GL_STENCIL_INDEX4_OES                                   0x8D47
+#endif
+
+/* GL_OES_texture3D */
+#ifndef GL_OES_texture3D
+#define GL_TEXTURE_WRAP_R_OES                                   0x8072
+#define GL_TEXTURE_3D_OES                                       0x806F
+#define GL_TEXTURE_BINDING_3D_OES                               0x806A
+#define GL_MAX_3D_TEXTURE_SIZE_OES                              0x8073
+#define GL_SAMPLER_3D_OES                                       0x8B5F
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES        0x8CD4
+#endif
+
+/* GL_OES_texture_half_float */
+#ifndef GL_OES_texture_half_float
+#define GL_HALF_FLOAT_OES                                       0x8D61
+#endif
+
+/* GL_OES_vertex_half_float */
+/* GL_HALF_FLOAT_OES defined in GL_OES_texture_half_float already. */
+
+/* GL_OES_vertex_type_10_10_10_2 */
+#ifndef GL_OES_vertex_type_10_10_10_2
+#define GL_UNSIGNED_INT_10_10_10_2_OES                          0x8DF6
+#define GL_INT_10_10_10_2_OES                                   0x8DF7
+#endif
+
+/*------------------------------------------------------------------------*
+ * AMD extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_AMD_compressed_3DC_texture */
+#ifndef GL_AMD_compressed_3DC_texture
+#define GL_3DC_X_AMD                                            0x87F9
+#define GL_3DC_XY_AMD                                           0x87FA
+#endif
+
+/* GL_AMD_compressed_ATC_texture */
+#ifndef GL_AMD_compressed_ATC_texture
+#define GL_ATC_RGB_AMD                                          0x8C92
+#define GL_ATC_RGBA_EXPLICIT_ALPHA_AMD                          0x8C93
+#define GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD                      0x87EE
+#endif
+
+/* GL_AMD_program_binary_Z400 */
+#ifndef GL_AMD_program_binary_Z400
+#define GL_Z400_BINARY_AMD                                      0x8740
+#endif
+
+/* GL_AMD_performance_monitor */
+#ifndef GL_AMD_performance_monitor
+#define GL_COUNTER_TYPE_AMD                                     0x8BC0
+#define GL_COUNTER_RANGE_AMD                                    0x8BC1
+#define GL_UNSIGNED_INT64_AMD                                   0x8BC2
+#define GL_PERCENTAGE_AMD                                       0x8BC3
+#define GL_PERFMON_RESULT_AVAILABLE_AMD                         0x8BC4
+#define GL_PERFMON_RESULT_SIZE_AMD                              0x8BC5
+#define GL_PERFMON_RESULT_AMD                                   0x8BC6
+#endif
+
+/*------------------------------------------------------------------------*
+ * EXT extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_EXT_texture_filter_anisotropic */
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_TEXTURE_MAX_ANISOTROPY_EXT                           0x84FE
+#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT                       0x84FF
+#endif
+
+/* GL_EXT_texture_type_2_10_10_10_REV */
+#ifndef GL_EXT_texture_type_2_10_10_10_REV
+#define GL_UNSIGNED_INT_2_10_10_10_REV_EXT                      0x8368
+#endif
+
+/* GL_EXT_texture_format_BGRA8888 */
+#ifndef GL_EXT_texture_format_BGRA8888
+#define GL_BGRA                                                 0x80E1
+#endif
+
+/*------------------------------------------------------------------------*
+ * IMG extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_IMG_read_format */
+#ifndef GL_IMG_read_format
+#define GL_BGRA                                                 0x80E1
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV                           0x8365
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV                           0x8366
+#endif
+
+/* GL_IMG_texture_compression_pvrtc */
+#ifndef GL_IMG_texture_compression_pvrtc
+#define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG                      0x8C00
+#define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG                      0x8C01
+#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG                     0x8C02
+#define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG                     0x8C03
+#endif
+
+/*------------------------------------------------------------------------*
+ * NV extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_NV_fence */
+#ifndef GL_NV_fence
+#define GL_ALL_COMPLETED_NV                                     0x84F2
+#define GL_FENCE_STATUS_NV                                      0x84F3
+#define GL_FENCE_CONDITION_NV                                   0x84F4
+#endif
+
+/*------------------------------------------------------------------------*
+ * QCOM extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_QCOM_driver_control */
+/* No new tokens introduced by this extension. */
+
+/* GL_QCOM_perfmon_global_mode */
+#ifndef GL_QCOM_perfmon_global_mode
+#define GL_PERFMON_GLOBAL_MODE_QCOM                             0x8FA0
+#endif
+
+/*------------------------------------------------------------------------*
+ * End of extension tokens, start of corresponding extension functions
+ *------------------------------------------------------------------------*/
+
+/*------------------------------------------------------------------------*
+ * OES extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_OES_compressed_ETC1_RGB8_texture */
+#ifndef GL_OES_compressed_ETC1_RGB8_texture
+#define GL_OES_compressed_ETC1_RGB8_texture 1
+#endif
+
+/* GL_OES_compressed_paletted_texture */
+#ifndef GL_OES_compressed_paletted_texture
+#define GL_OES_compressed_paletted_texture 1
+#endif
+
+/* GL_OES_EGL_image */
+#ifndef GL_OES_EGL_image
+#define GL_OES_EGL_image 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glEGLImageTargetTexture2DOES (GLenum target, GLeglImageOES image);
+GL_APICALL void GL_APIENTRY glEGLImageTargetRenderbufferStorageOES (GLenum target, GLeglImageOES image);
+#endif
+typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);
+typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
+#endif
+
+/* GL_OES_depth24 */
+#ifndef GL_OES_depth24
+#define GL_OES_depth24 1
+#endif
+
+/* GL_OES_depth32 */
+#ifndef GL_OES_depth32
+#define GL_OES_depth32 1
+#endif
+
+/* GL_OES_depth_texture */
+#ifndef GL_OES_depth_texture
+#define GL_OES_depth_texture 1
+#endif
+
+/* GL_OES_element_index_uint */
+#ifndef GL_OES_element_index_uint
+#define GL_OES_element_index_uint 1
+#endif
+
+/* GL_OES_fbo_render_mipmap */
+#ifndef GL_OES_fbo_render_mipmap
+#define GL_OES_fbo_render_mipmap 1
+#endif
+
+/* GL_OES_fragment_precision_high */
+#ifndef GL_OES_fragment_precision_high
+#define GL_OES_fragment_precision_high 1
+#endif
+
+/* GL_OES_get_program_binary */
+#ifndef GL_OES_get_program_binary
+#define GL_OES_get_program_binary 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetProgramBinaryOES (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);
+GL_APICALL void GL_APIENTRY glProgramBinaryOES (GLuint program, GLenum binaryFormat, const void *binary, GLint length);
+#endif
+typedef void (GL_APIENTRYP PFNGLGETPROGRAMBINARYOESPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);
+typedef void (GL_APIENTRYP PFNGLPROGRAMBINARYOESPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLint length);
+#endif
+
+/* GL_OES_mapbuffer */
+#ifndef GL_OES_mapbuffer
+#define GL_OES_mapbuffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void* GL_APIENTRY glMapBufferOES (GLenum target, GLenum access);
+GL_APICALL GLboolean GL_APIENTRY glUnmapBufferOES (GLenum target);
+GL_APICALL void GL_APIENTRY glGetBufferPointervOES (GLenum target, GLenum pname, void** params);
+#endif
+typedef void* (GL_APIENTRYP PFNGLMAPBUFFEROESPROC) (GLenum target, GLenum access);
+typedef GLboolean (GL_APIENTRYP PFNGLUNMAPBUFFEROESPROC) (GLenum target);
+typedef void (GL_APIENTRYP PFNGLGETBUFFERPOINTERVOESPROC) (GLenum target, GLenum pname, void** params);
+#endif
+
+/* GL_OES_packed_depth_stencil */
+#ifndef GL_OES_packed_depth_stencil
+#define GL_OES_packed_depth_stencil 1
+#endif
+
+/* GL_OES_rgb8_rgba8 */
+#ifndef GL_OES_rgb8_rgba8
+#define GL_OES_rgb8_rgba8 1
+#endif
+
+/* GL_OES_standard_derivatives */
+#ifndef GL_OES_standard_derivatives
+#define GL_OES_standard_derivatives 1
+#endif
+
+/* GL_OES_stencil1 */
+#ifndef GL_OES_stencil1
+#define GL_OES_stencil1 1
+#endif
+
+/* GL_OES_stencil4 */
+#ifndef GL_OES_stencil4
+#define GL_OES_stencil4 1
+#endif
+
+/* GL_OES_texture_3D */
+#ifndef GL_OES_texture_3D
+#define GL_OES_texture_3D 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels);
+GL_APICALL void GL_APIENTRY glTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* pixels);
+GL_APICALL void GL_APIENTRY glCopyTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glCompressedTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void* data);
+GL_APICALL void GL_APIENTRY glCompressedTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void* data);
+GL_APICALL void GL_APIENTRY glFramebufferTexture3DOES (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+#endif
+typedef void (GL_APIENTRYP PFNGLTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels);
+typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* pixels);
+typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void* data);
+typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void* data);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DOES) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+#endif
+
+/* GL_OES_texture_float_linear */
+#ifndef GL_OES_texture_float_linear
+#define GL_OES_texture_float_linear 1
+#endif
+
+/* GL_OES_texture_half_float_linear */
+#ifndef GL_OES_texture_half_float_linear
+#define GL_OES_texture_half_float_linear 1
+#endif
+
+/* GL_OES_texture_float */
+#ifndef GL_OES_texture_float
+#define GL_OES_texture_float 1
+#endif
+
+/* GL_OES_texture_half_float */
+#ifndef GL_OES_texture_half_float
+#define GL_OES_texture_half_float 1
+#endif
+
+/* GL_OES_texture_npot */
+#ifndef GL_OES_texture_npot
+#define GL_OES_texture_npot 1
+#endif
+
+/* GL_OES_vertex_half_float */
+#ifndef GL_OES_vertex_half_float
+#define GL_OES_vertex_half_float 1
+#endif
+
+/* GL_OES_vertex_type_10_10_10_2 */
+#ifndef GL_OES_vertex_type_10_10_10_2
+#define GL_OES_vertex_type_10_10_10_2 1
+#endif
+
+/*------------------------------------------------------------------------*
+ * AMD extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_AMD_compressed_3DC_texture */
+#ifndef GL_AMD_compressed_3DC_texture
+#define GL_AMD_compressed_3DC_texture 1
+#endif
+
+/* GL_AMD_compressed_ATC_texture */
+#ifndef GL_AMD_compressed_ATC_texture
+#define GL_AMD_compressed_ATC_texture 1
+#endif
+
+/* GL_AMD_program_binary_Z400 */
+#ifndef GL_AMD_program_binary_Z400
+#define GL_AMD_program_binary_Z400 1
+#endif
+
+/* AMD_performance_monitor */
+#ifndef GL_AMD_performance_monitor
+#define GL_AMD_performance_monitor 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, char *groupString);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, char *counterString);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, void *data);
+GL_APICALL void GL_APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors);
+GL_APICALL void GL_APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors);
+GL_APICALL void GL_APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *countersList);
+GL_APICALL void GL_APIENTRY glBeginPerfMonitorAMD (GLuint monitor);
+GL_APICALL void GL_APIENTRY glEndPerfMonitorAMD (GLuint monitor);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);
+#endif
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, char *groupString);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, char *counterString);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void *data);
+typedef void (GL_APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);
+typedef void (GL_APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);
+typedef void (GL_APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *countersList);
+typedef void (GL_APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor);
+typedef void (GL_APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);
+#endif
+
+/*------------------------------------------------------------------------*
+ * EXT extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_EXT_texture_filter_anisotropic */
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_EXT_texture_filter_anisotropic 1
+#endif
+
+/* GL_EXT_texture_type_2_10_10_10_REV */
+#ifndef GL_EXT_texture_type_2_10_10_10_REV
+#define GL_EXT_texture_type_2_10_10_10_REV 1
+#endif
+
+/* GL_EXT_texture_format_BGRA8888 */
+#ifndef GL_EXT_texture_format_BGRA8888
+#define GL_EXT_texture_format_BGRA8888 1
+#endif
+
+/*------------------------------------------------------------------------*
+ * IMG extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_IMG_read_format */
+#ifndef GL_IMG_read_format
+#define GL_IMG_read_format 1
+#endif
+
+/* GL_IMG_texture_compression_pvrtc */
+#ifndef GL_IMG_texture_compression_pvrtc
+#define GL_IMG_texture_compression_pvrtc 1
+#endif
+
+/*------------------------------------------------------------------------*
+ * NV extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_NV_fence */
+#ifndef GL_NV_fence
+#define GL_NV_fence 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDeleteFencesNV (GLsizei n, const GLuint *fences);
+GL_APICALL void GL_APIENTRY glGenFencesNV (GLsizei n, GLuint *fences);
+GL_APICALL GLboolean GL_APIENTRY glIsFenceNV (GLuint fence);
+GL_APICALL GLboolean GL_APIENTRY glTestFenceNV (GLuint fence);
+GL_APICALL void GL_APIENTRY glGetFenceivNV (GLuint fence, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glFinishFenceNV (GLuint fence);
+GL_APICALL void GL_APIENTRY glSetFenceNV (GLuint fence, GLenum condition);
+#endif
+typedef void (GL_APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);
+typedef void (GL_APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);
+typedef GLboolean (GL_APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);
+typedef GLboolean (GL_APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);
+typedef void (GL_APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
+typedef void (GL_APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
+#endif
+
+/*------------------------------------------------------------------------*
+ * QCOM extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_QCOM_driver_control */
+#ifndef GL_QCOM_driver_control
+#define GL_QCOM_driver_control 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetDriverControlsQCOM (GLint *num, GLsizei size, GLuint *driverControls);
+GL_APICALL void GL_APIENTRY glGetDriverControlStringQCOM (GLuint driverControl, GLsizei bufSize, GLsizei *length, char *driverControlString);
+GL_APICALL void GL_APIENTRY glEnableDriverControlQCOM (GLuint driverControl);
+GL_APICALL void GL_APIENTRY glDisableDriverControlQCOM (GLuint driverControl);
+#endif
+typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSQCOMPROC) (GLint *num, GLsizei size, GLuint *driverControls);
+typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSTRINGQCOMPROC) (GLuint driverControl, GLsizei bufSize, GLsizei *length, char *driverControlString);
+typedef void (GL_APIENTRYP PFNGLENABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl);
+typedef void (GL_APIENTRYP PFNGLDISABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl);
+#endif
+
+/* GL_QCOM_perfmon_global_mode */
+#ifndef GL_QCOM_perfmon_global_mode
+#define GL_QCOM_perfmon_global_mode 1
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gl2ext_h_ */
diff --git a/opengl/include/GLES2/gl2platform.h b/opengl/include/GLES2/gl2platform.h
new file mode 100644
index 0000000..3e9036c
--- /dev/null
+++ b/opengl/include/GLES2/gl2platform.h
@@ -0,0 +1,29 @@
+#ifndef __gl2platform_h_
+#define __gl2platform_h_
+
+/* $Revision: 7173 $ on $Date:: 2009-01-09 11:18:21 -0800 #$ */
+
+/*
+ * This document is licensed under the SGI Free Software B License Version
+ * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
+ */
+
+/* Platform-specific types and definitions for OpenGL ES 2.X  gl2.h
+ * Last modified on 2008/12/19
+ *
+ * Adopters may modify khrplatform.h and this file to suit their platform.
+ * You are encouraged to submit all modifications to the Khronos group so that
+ * they can be included in future versions of this file.  Please submit changes
+ * by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla)
+ * by filing a bug against product "OpenGL-ES" component "Registry".
+ */
+
+#include <KHR/khrplatform.h>
+
+#ifndef GL_APICALL
+#define GL_APICALL  KHRONOS_APICALL
+#endif
+
+#define GL_APIENTRY KHRONOS_APIENTRY
+
+#endif /* __gl2platform_h_ */
diff --git a/opengl/libagl/Android.mk b/opengl/libagl/Android.mk
index 3ce0414..2522656 100644
--- a/opengl/libagl/Android.mk
+++ b/opengl/libagl/Android.mk
@@ -6,6 +6,9 @@
 
 include $(CLEAR_VARS)
 
+# Set to 1 to use gralloc and copybits
+LIBAGL_USE_GRALLOC_COPYBITS := 1
+
 LOCAL_SRC_FILES:= \
 	egl.cpp                     \
 	state.cpp		            \
@@ -29,13 +32,23 @@
 
 ifneq ($(TARGET_SIMULATOR),true)
     # we need to access the private Bionic header <bionic_tls.h>
-    LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../bionic/libc/private
+    LOCAL_C_INCLUDES += bionic/libc/private
 endif
 
-LOCAL_SHARED_LIBRARIES := libcutils libutils libpixelflinger
+ifeq ($(LIBAGL_USE_GRALLOC_COPYBITS),1)
+    LOCAL_CFLAGS += -DLIBAGL_USE_GRALLOC_COPYBITS
+    LOCAL_SRC_FILES += copybit.cpp
+endif
+
+LOCAL_CFLAGS += -DLOG_TAG=\"libagl\"
+LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+
+LOCAL_SHARED_LIBRARIES := libcutils libhardware libutils libpixelflinger
 LOCAL_CFLAGS += -fvisibility=hidden
 
 LOCAL_LDLIBS := -lpthread -ldl
-LOCAL_MODULE:= libagl
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/egl
+LOCAL_MODULE:= libGLES_android
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/opengl/libagl/TextureObjectManager.cpp b/opengl/libagl/TextureObjectManager.cpp
index ce31854..255ccac 100644
--- a/opengl/libagl/TextureObjectManager.cpp
+++ b/opengl/libagl/TextureObjectManager.cpp
@@ -1,16 +1,16 @@
 /*
  ** Copyright 2006, 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 
+ ** 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 
+ **     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 
+ ** 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.
  */
 
@@ -19,11 +19,13 @@
 #include "context.h"
 #include "TextureObjectManager.h"
 
+#include <private/ui/android_natives_priv.h>
+
 namespace android {
 // ----------------------------------------------------------------------------
 
 EGLTextureObject::EGLTextureObject()
-    : mCount(0), mSize(0)
+    : mSize(0)
 {
     init();
 }
@@ -53,6 +55,10 @@
     memset(crop_rect, 0, sizeof(crop_rect));
     generate_mipmap = GL_FALSE;
     direct = GL_FALSE;
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+    try_copybit = false;
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
+    buffer = 0;
 }
 
 void EGLTextureObject::copyParameters(const sp<EGLTextureObject>& old)
@@ -123,6 +129,7 @@
     }
     surface = *s;
     internalformat = 0;
+    buffer = 0;
 
     // we should keep the crop_rect, but it's delicate because
     // the new size of the surface could make it invalid.
@@ -141,12 +148,26 @@
     return NO_ERROR;
 }
 
+status_t EGLTextureObject::setImage(android_native_buffer_t* native_buffer)
+{
+    GGLSurface sur;
+    sur.version = sizeof(GGLSurface);
+    sur.width = native_buffer->width;
+    sur.height= native_buffer->height;
+    sur.stride= native_buffer->stride;
+    sur.format= native_buffer->format;
+    sur.data  = 0;
+    setSurface(&sur);
+    buffer = native_buffer;
+    return NO_ERROR;
+}
+
 status_t EGLTextureObject::reallocate(
         GLint level, int w, int h, int s,
         int format, int compressedFormat, int bpr)
 {
     const size_t size = h * bpr;
-    if (level == 0) 
+    if (level == 0)
     {
         if (size!=mSize || !surface.data) {
             if (mSize && surface.data) {
@@ -177,9 +198,9 @@
                 return NO_MEMORY;
         }
 
-        LOGW_IF(level-1 >= mNumExtraLod, 
+        LOGW_IF(level-1 >= mNumExtraLod,
                 "specifying mipmap level %d, but # of level is %d",
-                level, mNumExtraLod+1);        
+                level, mNumExtraLod+1);
 
         GGLSurface& mipmap = editMip(level);
         if (mipmap.data)
@@ -224,7 +245,7 @@
 // ----------------------------------------------------------------------------
 
 EGLSurfaceManager::EGLSurfaceManager()
-    : TokenManager(), mCount(0)
+    : TokenManager()
 {
 }
 
diff --git a/opengl/libagl/TextureObjectManager.h b/opengl/libagl/TextureObjectManager.h
index 74ed1a4..279e040 100644
--- a/opengl/libagl/TextureObjectManager.h
+++ b/opengl/libagl/TextureObjectManager.h
@@ -1,16 +1,16 @@
 /*
 ** Copyright 2006, 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 
+** 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 
+**     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 
+** 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.
 */
 
@@ -30,6 +30,8 @@
 #include <private/pixelflinger/ggl_context.h>
 
 #include <GLES/gl.h>
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
 
 #include "Tokenizer.h"
 #include "TokenManager.h"
@@ -39,22 +41,20 @@
 
 // ----------------------------------------------------------------------------
 
-class EGLTextureObject
+class EGLTextureObject : public LightRefBase<EGLTextureObject>
 {
 public:
                     EGLTextureObject();
                    ~EGLTextureObject();
 
-    // protocol for sp<>
-    inline  void        incStrong(const void* id) const;
-    inline  void        decStrong(const void* id) const;
-    inline  uint32_t    getStrongCount() const;
+    status_t    setSurface(GGLSurface const* s);
+    status_t    setImage(android_native_buffer_t* buffer);
+    void        setImageBits(void* vaddr) { surface.data = (GGLubyte*)vaddr; }
 
-    status_t            setSurface(GGLSurface const* s);
     status_t            reallocate(GLint level,
                             int w, int h, int s,
                             int format, int compressedFormat, int bpr);
-    inline  size_t      size() const;
+    inline  size_t      size() const { return mSize; }
     const GGLSurface&   mip(int lod) const;
     GGLSurface&         editMip(int lod);
     bool                hasMipmaps() const { return mMipmaps!=0; }
@@ -65,7 +65,6 @@
         status_t        allocateMipmaps();
             void        freeMipmaps();
             void        init();
-    mutable int32_t     mCount;
     size_t              mSize;
     GGLSurface          *mMipmaps;
     int                 mNumExtraLod;
@@ -81,36 +80,22 @@
     GLint               crop_rect[4];
     GLint               generate_mipmap;
     GLint               direct;
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+    bool                try_copybit;
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
+    android_native_buffer_t* buffer;
 };
 
-void EGLTextureObject::incStrong(const void* id) const {
-    android_atomic_inc(&mCount);
-}
-void EGLTextureObject::decStrong(const void* id) const {
-    if (android_atomic_dec(&mCount) == 1) {
-        delete this;
-    }
-}
-uint32_t EGLTextureObject::getStrongCount() const {
-    return mCount;
-}
-size_t EGLTextureObject::size() const {
-    return mSize;
-}
-
 // ----------------------------------------------------------------------------
 
-class EGLSurfaceManager : public TokenManager
+class EGLSurfaceManager :
+    public LightRefBase<EGLSurfaceManager>,
+    public TokenManager
 {
 public:
                 EGLSurfaceManager();
                 ~EGLSurfaceManager();
 
-    // protocol for sp<>
-    inline  void    incStrong(const void* id) const;
-    inline  void    decStrong(const void* id) const;
-    typedef void    weakref_type;
-
     sp<EGLTextureObject>    createTexture(GLuint name);
     sp<EGLTextureObject>    removeTexture(GLuint name);
     sp<EGLTextureObject>    replaceTexture(GLuint name);
@@ -118,21 +103,10 @@
     sp<EGLTextureObject>    texture(GLuint name);
 
 private:
-    mutable int32_t                             mCount;
     mutable Mutex                               mLock;
     KeyedVector< GLuint, sp<EGLTextureObject> > mTextures;
 };
 
-void EGLSurfaceManager::incStrong(const void* id) const {
-    android_atomic_inc(&mCount);
-}
-void EGLSurfaceManager::decStrong(const void* id) const {
-    if (android_atomic_dec(&mCount) == 1) {
-        delete this;
-    }
-}
-
-
 // ----------------------------------------------------------------------------
 }; // namespace android
 
diff --git a/opengl/libagl/array.cpp b/opengl/libagl/array.cpp
index 3e9c6a5..f414ee5 100644
--- a/opengl/libagl/array.cpp
+++ b/opengl/libagl/array.cpp
@@ -1,16 +1,16 @@
-/* 
+/*
 ** Copyright 2006, 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 
+** 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 
+**     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 
+** 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.
 */
 
@@ -26,6 +26,9 @@
 #include "primitives.h"
 #include "texture.h"
 #include "BufferObjectManager.h"
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+#include "copybit.h"
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
 
 // ----------------------------------------------------------------------------
 
@@ -250,7 +253,7 @@
     v[2] = GGL_S_TO_X(p[2]);
 }
 
-typedef array_t::fetcher_t fn_t; 
+typedef array_t::fetcher_t fn_t;
 
 static const fn_t color_fct[2][16] = { // size={3,4}, type={ub,f,x}
     { 0, (fn_t)fetchExpand3ub, 0, 0, 0, 0,
@@ -334,7 +337,7 @@
     this->bounds = count;
 }
 
-inline void array_t::resolve() 
+inline void array_t::resolve()
 {
     physical_pointer = (bo) ? (bo->data + uintptr_t(pointer)) : pointer;
 }
@@ -465,7 +468,7 @@
         // We compute directly the index of a "free" entry from the locked
         // state of v[2] and v[3].
         v = c->vc.vBuffer + 2;
-        v += v[0].locked | (v[1].locked<<1);       
+        v += v[0].locked | (v[1].locked<<1);
     }
     // note: compileElement clears v->flags
     c->arrays.compileElement(c, v, index);
@@ -480,7 +483,7 @@
 
 #if VC_CACHE_TYPE == VC_CACHE_TYPE_INDEXED
 
-    vertex_t* const v = c->vc.vCache + 
+    vertex_t* const v = c->vc.vCache +
             (index & (vertex_cache_t::VERTEX_CACHE_SIZE-1));
 
     if (ggl_likely(v->index == index)) {
@@ -491,7 +494,7 @@
 
 #elif VC_CACHE_TYPE == VC_CACHE_TYPE_LRU
 
-    vertex_t* v = c->vc.vCache + 
+    vertex_t* v = c->vc.vCache +
             (index & ((vertex_cache_t::VERTEX_CACHE_SIZE-1)>>1))*2;
 
     // always record LRU in v[0]
@@ -532,12 +535,12 @@
         return;
 
     // vertex cache size must be multiple of 1
-    const GLsizei vcs = 
+    const GLsizei vcs =
             (vertex_cache_t::VERTEX_BUFFER_SIZE +
              vertex_cache_t::VERTEX_CACHE_SIZE);
     do {
         vertex_t* v = c->vc.vBuffer;
-        GLsizei num = count > vcs ? vcs : count; 
+        GLsizei num = count > vcs ? vcs : count;
         c->arrays.cull = vertex_t::CLIP_ALL;
         c->arrays.compileElements(c, v, first, num);
         first += num;
@@ -569,13 +572,13 @@
     count -= 1;
 
     // vertex cache size must be multiple of 1
-    const GLsizei vcs = 
+    const GLsizei vcs =
         (vertex_cache_t::VERTEX_BUFFER_SIZE +
          vertex_cache_t::VERTEX_CACHE_SIZE - 1);
     do {
-        v0 = c->vc.vBuffer + 0; 
+        v0 = c->vc.vBuffer + 0;
         v  = c->vc.vBuffer + 1;
-        GLsizei num = count > vcs ? vcs : count; 
+        GLsizei num = count > vcs ? vcs : count;
         c->arrays.compileElements(c, v, first, num);
         first += num;
         count -= num;
@@ -602,7 +605,7 @@
         return;
     drawPrimitivesLineStrip(c, first, count);
     if (ggl_likely(count >= 3)) {
-        vertex_t* v0 = c->vc.vBuffer; 
+        vertex_t* v0 = c->vc.vBuffer;
         vertex_t* v1 = c->vc.vBuffer + 1;
         c->arrays.compileElement(c, v1, first);
         const uint32_t cc = v0->flags & v1->flags;
@@ -617,12 +620,12 @@
         return;
 
     // vertex cache size must be multiple of 2
-    const GLsizei vcs = 
+    const GLsizei vcs =
         ((vertex_cache_t::VERTEX_BUFFER_SIZE +
         vertex_cache_t::VERTEX_CACHE_SIZE) / 2) * 2;
     do {
         vertex_t* v = c->vc.vBuffer;
-        GLsizei num = count > vcs ? vcs : count; 
+        GLsizei num = count > vcs ? vcs : count;
         c->arrays.cull = vertex_t::CLIP_ALL;
         c->arrays.compileElements(c, v, first, num);
         first += num;
@@ -662,14 +665,14 @@
     // because it allows us to preserve the same winding when the whole
     // batch is culled. We also need 2 extra vertices in the array, because
     // we always keep the two first ones.
-    const GLsizei vcs = 
+    const GLsizei vcs =
         ((vertex_cache_t::VERTEX_BUFFER_SIZE +
           vertex_cache_t::VERTEX_CACHE_SIZE - 2) / 2) * 2;
     do {
-        v0 = c->vc.vBuffer + 0; 
-        v1 = c->vc.vBuffer + 1; 
+        v0 = c->vc.vBuffer + 0;
+        v1 = c->vc.vBuffer + 1;
         v  = c->vc.vBuffer + 2;
-        GLsizei num = count > vcs ? vcs : count; 
+        GLsizei num = count > vcs ? vcs : count;
         c->arrays.compileElements(c, v, first, num);
         first += num;
         count -= num;
@@ -697,13 +700,19 @@
     } while (count > 0);
 }
 
-void drawPrimitivesTriangleStrip(ogles_context_t* c, 
+void drawPrimitivesTriangleStrip(ogles_context_t* c,
         GLint first, GLsizei count) {
     drawPrimitivesTriangleFanOrStrip(c, first, count, 1);
 }
 
 void drawPrimitivesTriangleFan(ogles_context_t* c,
         GLint first, GLsizei count) {
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+    if (drawTriangleFanWithCopybit(c, first, count)) {
+        return;
+    }
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
+
     drawPrimitivesTriangleFanOrStrip(c, first, count, 2);
 }
 
@@ -713,12 +722,12 @@
         return;
 
     // vertex cache size must be multiple of 3
-    const GLsizei vcs = 
+    const GLsizei vcs =
         ((vertex_cache_t::VERTEX_BUFFER_SIZE +
         vertex_cache_t::VERTEX_CACHE_SIZE) / 3) * 3;
     do {
         vertex_t* v = c->vc.vBuffer;
-        GLsizei num = count > vcs ? vcs : count; 
+        GLsizei num = count > vcs ? vcs : count;
         c->arrays.cull = vertex_t::CLIP_ALL;
         c->arrays.compileElements(c, v, first, num);
         first += num;
@@ -779,11 +788,11 @@
 {
     if (ggl_unlikely(count < 2))
         return;
-    
+
     vertex_t * const v = c->vc.vBuffer;
     vertex_t* v0 = v;
     vertex_t* v1;
-    
+
     const int type = (c->arrays.indicesType == GL_UNSIGNED_BYTE);
     c->arrays.compileElement(c, v0, read_index(type, indices));
     count -= 1;
@@ -806,11 +815,11 @@
         drawIndexedPrimitivesLines(c, count, indices);
         return;
     }
- 
+
     vertex_t * const v = c->vc.vBuffer;
     vertex_t* v0 = v;
     vertex_t* v1;
-    
+
     const int type = (c->arrays.indicesType == GL_UNSIGNED_BYTE);
     c->arrays.compileElement(c, v0, read_index(type, indices));
     count -= 1;
@@ -825,7 +834,7 @@
     } while (count);
     v1->locked = 0;
 
-    v1 = c->vc.vBuffer; 
+    v1 = c->vc.vBuffer;
     const uint32_t cc = v0->flags & v1->flags;
     if (ggl_likely(!(cc & vertex_t::CLIP_ALL)))
         c->prims.renderLine(c, v0, v1);
@@ -861,7 +870,7 @@
 
     if (ggl_unlikely(count < 3))
         return;
-    
+
     vertex_t * const v = c->vc.vBuffer;
     vertex_t* v0 = v;
     vertex_t* v1 = v+1;
@@ -985,17 +994,17 @@
     const GLfixed* vp = (const GLfixed*)c->arrays.vertex.element(first);
     const size_t stride = c->arrays.vertex.stride / 4;
 //    const GLfixed* const& m = c->transforms.mvp.matrix.m;
-    
+
     GLfixed m[16];
     memcpy(&m, c->transforms.mvp.matrix.m, sizeof(m));
-    
+
     do {
         const GLfixed rx = vp[0];
         const GLfixed ry = vp[1];
         const GLfixed rz = vp[2];
         vp += stride;
         v->index = first++;
-        v->clip.x = mla3a(rx, m[ 0], ry, m[ 4], rz, m[ 8], m[12]); 
+        v->clip.x = mla3a(rx, m[ 0], ry, m[ 4], rz, m[ 8], m[12]);
         v->clip.y = mla3a(rx, m[ 1], ry, m[ 5], rz, m[ 9], m[13]);
         v->clip.z = mla3a(rx, m[ 2], ry, m[ 6], rz, m[10], m[14]);
         v->clip.w = mla3a(rx, m[ 3], ry, m[ 7], rz, m[11], m[15]);
@@ -1023,7 +1032,7 @@
 #pragma mark clippers
 #endif
 
-static void clipVec4(vec4_t& nv, 
+static void clipVec4(vec4_t& nv,
         GLfixed t, const vec4_t& s, const vec4_t& p)
 {
     for (int i=0; i<4 ; i++)
@@ -1086,10 +1095,10 @@
     // automatically turn it off (in fact we could when the 4th coordinate
     // is not spcified in the vertex array).
     // W interpolation is never needed for points.
-    GLboolean perspective = 
+    GLboolean perspective =
         c->perspective && mode!=GL_POINTS && (enables & GGL_ENABLE_TMUS);
     c->rasterizer.procs.enableDisable(c, GGL_W_LERP, perspective);
-    
+
     // set anti-aliasing
     GLboolean smooth = GL_FALSE;
     switch (mode) {
@@ -1120,7 +1129,7 @@
     if (enables & GGL_ENABLE_TMUS) { // needs texture transforms
         want |= transform_state_t::TEXTURE;
     }
-    if (c->clipPlanes.enable || (enables & GGL_ENABLE_FOG)) { 
+    if (c->clipPlanes.enable || (enables & GGL_ENABLE_FOG)) {
         want |= transform_state_t::MODELVIEW; // needs eye coords
     }
     ogles_validate_transform(c, want);
@@ -1139,18 +1148,18 @@
 
     c->arrays.mv_transform =
         c->transforms.modelview.transform.pointv[c->arrays.vertex.size - 2];
-    
+
     /*
      * ***********************************************************************
      *  pick fetchers
      * ***********************************************************************
      */
-    
+
     array_machine_t& am = c->arrays;
     am.vertex.fetch = fetchNop;
     am.normal.fetch = currentNormal;
     am.color.fetch = currentColor;
-    
+
     if (am.vertex.enable) {
         am.vertex.resolve();
         if (am.vertex.bo || am.vertex.pointer) {
@@ -1366,9 +1375,18 @@
     if ((c->cull.enable) && (c->cull.cullFace == GL_FRONT_AND_BACK))
         return; // all triangles are culled
 
+
     validate_arrays(c, mode);
+
+    const uint32_t enables = c->rasterizer.state.enables;
+    if (enables & GGL_ENABLE_TMUS)
+        ogles_lock_textures(c);
+
     drawArraysPrims[mode](c, first, count);
 
+    if (enables & GGL_ENABLE_TMUS)
+        ogles_unlock_textures(c);
+
 #if VC_CACHE_STATISTICS
     c->vc.total = count;
     c->vc.dump_stats(mode);
@@ -1413,15 +1431,23 @@
     // clear the vertex-cache
     c->vc.clear();
     validate_arrays(c, mode);
-    
+
     // if indices are in a buffer object, the pointer is treated as an
     // offset in that buffer.
     if (c->arrays.element_array_buffer) {
         indices = c->arrays.element_array_buffer->data + uintptr_t(indices);
     }
 
-    drawElementsPrims[mode](c, count, indices);
+    const uint32_t enables = c->rasterizer.state.enables;
+    if (enables & GGL_ENABLE_TMUS)
+        ogles_lock_textures(c);
 
+    drawElementsPrims[mode](c, count, indices);
+    
+    if (enables & GGL_ENABLE_TMUS)
+        ogles_unlock_textures(c);
+
+    
 #if VC_CACHE_STATISTICS
     c->vc.total = count;
     c->vc.dump_stats(mode);
@@ -1448,7 +1474,7 @@
             return;
         }
     }
-    ((target == GL_ARRAY_BUFFER) ? 
+    ((target == GL_ARRAY_BUFFER) ?
             c->arrays.array_buffer : c->arrays.element_array_buffer) = bo;
 }
 
@@ -1467,7 +1493,7 @@
         ogles_error(c, GL_INVALID_ENUM);
         return;
     }
-    buffer_t const* bo = ((target == GL_ARRAY_BUFFER) ? 
+    buffer_t const* bo = ((target == GL_ARRAY_BUFFER) ?
             c->arrays.array_buffer : c->arrays.element_array_buffer);
 
     if (bo == 0) {
@@ -1497,7 +1523,7 @@
         ogles_error(c, GL_INVALID_VALUE);
         return;
     }
-    buffer_t const* bo = ((target == GL_ARRAY_BUFFER) ? 
+    buffer_t const* bo = ((target == GL_ARRAY_BUFFER) ?
             c->arrays.array_buffer : c->arrays.element_array_buffer);
 
     if (bo == 0) {
@@ -1545,7 +1571,7 @@
                 }
             }
         }
-    }    
+    }
     c->bufferObjectManager->deleteBuffers(n, buffers);
     c->bufferObjectManager->recycleTokens(n, buffers);
 }
diff --git a/opengl/libagl/copybit.cpp b/opengl/libagl/copybit.cpp
new file mode 100644
index 0000000..3c5bcdf3
--- /dev/null
+++ b/opengl/libagl/copybit.cpp
@@ -0,0 +1,458 @@
+/*
+**
+** Copyright 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.
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+
+#include "context.h"
+#include "fp.h"
+#include "state.h"
+#include "matrix.h"
+#include "vertex.h"
+#include "light.h"
+#include "primitives.h"
+#include "texture.h"
+#include "BufferObjectManager.h"
+#include "TextureObjectManager.h"
+
+#include <hardware/gralloc.h>
+#include <hardware/copybit.h>
+#include <private/ui/android_natives_priv.h>
+
+
+#define DEBUG_COPYBIT true
+
+// ----------------------------------------------------------------------------
+
+namespace android {
+
+static void textureToCopyBitImage(
+        const GGLSurface* surface, buffer_handle_t buffer, copybit_image_t* img) 
+{
+    img->w      = surface->stride;
+    img->h      = surface->height;
+    img->format = surface->format;
+    img->base   = surface->data;
+    img->handle = (native_handle_t *)buffer;
+}
+
+struct clipRectRegion : public copybit_region_t {
+    clipRectRegion(ogles_context_t* c) 
+    {
+        scissor_t const* scissor = &c->rasterizer.state.scissor;
+        r.l = scissor->left;
+        r.t = scissor->top;
+        r.r = scissor->right;
+        r.b = scissor->bottom;
+        next = iterate; 
+    }
+private:
+    static int iterate(copybit_region_t const * self, copybit_rect_t* rect) {
+        *rect = static_cast<clipRectRegion const*>(self)->r;
+        const_cast<copybit_region_t *>(self)->next = iterate_done;
+        return 1;
+    }
+    static int iterate_done(copybit_region_t const *, copybit_rect_t*) {
+        return 0;
+    }
+    copybit_rect_t r;
+};
+
+static bool supportedCopybitsFormat(int format) {
+    switch (format) {
+    case COPYBIT_FORMAT_RGBA_8888:
+    case COPYBIT_FORMAT_RGB_565:
+    case COPYBIT_FORMAT_BGRA_8888:
+    case COPYBIT_FORMAT_RGBA_5551:
+    case COPYBIT_FORMAT_RGBA_4444:
+    case COPYBIT_FORMAT_YCbCr_422_SP:
+    case COPYBIT_FORMAT_YCbCr_420_SP:
+        return true;
+    default:
+        return false;
+    }
+}
+
+static bool hasAlpha(int format) {
+    switch (format) {
+    case COPYBIT_FORMAT_RGBA_8888:
+    case COPYBIT_FORMAT_BGRA_8888:
+    case COPYBIT_FORMAT_RGBA_5551:
+    case COPYBIT_FORMAT_RGBA_4444:
+        return true;
+    default:
+        return false;
+    }
+}
+
+static inline int fixedToByte(GGLfixed val) {
+    return (val - (val >> 8)) >> 8;
+}
+
+/**
+ * Performs a quick check of the rendering state. If this function returns
+ * false we cannot use the copybit driver.
+ */
+
+static bool checkContext(ogles_context_t* c) {
+
+	// By convention copybitQuickCheckContext() has already returned true.
+	// avoid checking the same information again.
+	
+    if (c->copybits.blitEngine == NULL) {
+        LOGD_IF(DEBUG_COPYBIT, "no copybit hal");
+        return false;
+    }
+
+    if (c->rasterizer.state.enables
+                    & (GGL_ENABLE_DEPTH_TEST|GGL_ENABLE_FOG)) {
+        LOGD_IF(DEBUG_COPYBIT, "depth test and/or fog");
+        return false;
+    }
+
+    // Note: The drawSurfaceBuffer is only set for destination
+    // surfaces types that are supported by the hardware and
+    // do not have an alpha channel. So we don't have to re-check that here.
+
+    static const int tmu = 0;
+    texture_unit_t& u(c->textures.tmu[tmu]);
+    EGLTextureObject* textureObject = u.texture;
+
+    if (!supportedCopybitsFormat(textureObject->surface.format)) {
+        LOGD_IF(DEBUG_COPYBIT, "texture format not supported");
+        return false;
+    }
+    return true;
+}
+
+
+static bool copybit(GLint x, GLint y,
+        GLint w, GLint h,
+        EGLTextureObject* textureObject,
+        const GLint* crop_rect,
+        int transform,
+        ogles_context_t* c)
+{
+    // We assume checkContext has already been called and has already
+    // returned true.
+
+    const GGLSurface& cbSurface = c->rasterizer.state.buffers.color.s;
+
+    y = cbSurface.height - (y + h);
+
+    const GLint Ucr = crop_rect[0];
+    const GLint Vcr = crop_rect[1];
+    const GLint Wcr = crop_rect[2];
+    const GLint Hcr = crop_rect[3];
+
+    GLint screen_w = w;
+    GLint screen_h = h;
+    int32_t dsdx = Wcr << 16;   // dsdx =  ((Wcr/screen_w)/Wt)*Wt
+    int32_t dtdy = Hcr << 16;   // dtdy = -((Hcr/screen_h)/Ht)*Ht
+    if (transform & COPYBIT_TRANSFORM_ROT_90) {
+        swap(screen_w, screen_h);
+    }
+    if (dsdx!=screen_w || dtdy!=screen_h) {
+        // in most cases the divide is not needed
+        dsdx /= screen_w;
+        dtdy /= screen_h;
+    }
+    dtdy = -dtdy; // see equation of dtdy above
+    if (dsdx < c->copybits.minScale || dsdx > c->copybits.maxScale
+            || dtdy < c->copybits.minScale || dtdy > c->copybits.maxScale) {
+        // The requested scale is out of the range the hardware
+        // can support.
+        LOGD_IF(DEBUG_COPYBIT,
+                "scale out of range dsdx=%08x (Wcr=%d / w=%d), "
+                "dtdy=%08x (Hcr=%d / h=%d), Ucr=%d, Vcr=%d", 
+                dsdx, Wcr, w, dtdy, Hcr, h, Ucr, Vcr);
+        return false;
+    }
+
+    // copybit doesn't say anything about filtering, so we can't
+    // discriminate. On msm7k, copybit will always filter.
+    // the code below handles min/mag filters, we keep it as a reference.
+    
+#ifdef MIN_MAG_FILTER
+    int32_t texelArea = gglMulx(dtdy, dsdx);
+    if (texelArea < FIXED_ONE && textureObject->mag_filter != GL_LINEAR) {
+        // Non-linear filtering on a texture enlargement.
+        LOGD_IF(DEBUG_COPYBIT, "mag filter is not GL_LINEAR");
+        return false;
+    }
+    if (texelArea > FIXED_ONE && textureObject->min_filter != GL_LINEAR) {
+        // Non-linear filtering on an texture shrink.
+        LOGD_IF(DEBUG_COPYBIT, "min filter is not GL_LINEAR");
+        return false;
+    }
+#endif
+    
+    const uint32_t enables = c->rasterizer.state.enables;
+    int planeAlpha = 255;
+    static const int tmu = 0;
+    texture_t& tev(c->rasterizer.state.texture[tmu]);
+    bool srcTextureHasAlpha = hasAlpha(textureObject->surface.format);
+    if (!srcTextureHasAlpha) {
+        planeAlpha = fixedToByte(c->currentColorClamped.a);
+    }
+
+    switch (tev.env) {
+    case GGL_REPLACE:
+        break;
+    case GGL_MODULATE:
+        if (! (c->currentColorClamped.r == FIXED_ONE &&
+               c->currentColorClamped.g == FIXED_ONE &&
+               c->currentColorClamped.b == FIXED_ONE)) {
+            LOGD_IF(DEBUG_COPYBIT, 
+                    "MODULATE and non white color (%08x, %08x, %08x)",
+                    c->currentColorClamped.r,
+                    c->currentColorClamped.g,
+                    c->currentColorClamped.b);
+            return false;
+        }
+        if (srcTextureHasAlpha && c->currentColorClamped.a < FIXED_ONE) {
+            LOGD_IF(DEBUG_COPYBIT, 
+                    "MODULATE and texture w/alpha and alpha=%08x)",
+                    c->currentColorClamped.a);
+            return false;
+        }
+        break;
+
+    default:
+        // Incompatible texture environment.
+        LOGD_IF(DEBUG_COPYBIT, "incompatible texture environment");
+        return false;
+    }
+
+    bool blending = false;
+    if ((enables & GGL_ENABLE_BLENDING)
+            && !(c->rasterizer.state.blend.src == GL_ONE
+                    && c->rasterizer.state.blend.dst == GL_ZERO)) {
+        // Blending is OK if it is
+        // the exact kind of blending that the copybits hardware supports.
+        // Note: The hardware only supports
+        // GL_SRC_ALPHA / GL_ONE_MINUS_SRC_ALPHA,
+        // But the surface flinger uses GL_ONE / GL_ONE_MINUS_SRC_ALPHA.
+        // We substitute GL_SRC_ALPHA / GL_ONE_MINUS_SRC_ALPHA in that case,
+        // because the performance is worth it, even if the results are
+        // not correct.
+        if (!((c->rasterizer.state.blend.src == GL_SRC_ALPHA
+                || c->rasterizer.state.blend.src == GL_ONE)
+                && c->rasterizer.state.blend.dst == GL_ONE_MINUS_SRC_ALPHA
+                && c->rasterizer.state.blend.alpha_separate == 0)) {
+            // Incompatible blend mode.
+            LOGD_IF(DEBUG_COPYBIT, "incompatible blend mode");
+            return false;
+        }
+        blending = true;
+    } else {
+        // No blending is OK if we are not using alpha.
+        if (srcTextureHasAlpha || planeAlpha != 255) {
+            // Incompatible alpha
+            LOGD_IF(DEBUG_COPYBIT, "incompatible alpha");
+            return false;
+        }
+    }
+
+    if (srcTextureHasAlpha && planeAlpha != 255) {
+        // Can't do two types of alpha at once.
+        LOGD_IF(DEBUG_COPYBIT, "src alpha and plane alpha");
+        return false;
+    }
+
+    // LOGW("calling copybits");
+
+    copybit_device_t* copybit = c->copybits.blitEngine;
+
+    copybit_image_t dst;
+    buffer_handle_t target_hnd = c->copybits.drawSurfaceBuffer;
+    textureToCopyBitImage(&cbSurface, target_hnd, &dst);
+    copybit_rect_t drect = {x, y, x+w, y+h};
+
+    copybit_image_t src;
+    buffer_handle_t source_hnd = textureObject->buffer->handle;
+    textureToCopyBitImage(&textureObject->surface, source_hnd, &src);
+    copybit_rect_t srect = { Ucr, Vcr + Hcr, Ucr + Wcr, Vcr };
+
+    copybit->set_parameter(copybit, COPYBIT_TRANSFORM, transform);
+    copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, planeAlpha);
+    copybit->set_parameter(copybit, COPYBIT_DITHER,
+            (enables & GGL_ENABLE_DITHER) ? COPYBIT_ENABLE : COPYBIT_DISABLE);
+
+    clipRectRegion it(c);
+    status_t err = copybit->stretch(copybit, &dst, &src, &drect, &srect, &it);
+    if (err != NO_ERROR) {
+        c->textures.tmu[0].texture->try_copybit = false;
+    }
+    return err == NO_ERROR ? true : false;
+}
+
+/*
+ * Try to draw a triangle fan with copybit, return false if we fail.
+ */
+bool drawTriangleFanWithCopybit_impl(ogles_context_t* c, GLint first, GLsizei count)
+{
+    if (!checkContext(c)) {
+        return false;
+    }
+
+    // FIXME: we should handle culling  here
+    c->arrays.compileElements(c, c->vc.vBuffer, 0, 4);
+
+    // we detect if we're dealing with a rectangle, by comparing the
+    // rectangles {v0,v2} and {v1,v3} which should be identical.
+    
+    // NOTE: we should check that the rectangle is window aligned, however
+    // if we do that, the optimization won't be taken in a lot of cases.
+    // Since this code is intended to be used with SurfaceFlinger only,
+    // so it's okay...
+    
+    const vec4_t& v0 = c->vc.vBuffer[0].window;
+    const vec4_t& v1 = c->vc.vBuffer[1].window;
+    const vec4_t& v2 = c->vc.vBuffer[2].window;
+    const vec4_t& v3 = c->vc.vBuffer[3].window;
+    int l = min(v0.x, v2.x);
+    int b = min(v0.y, v2.y);
+    int r = max(v0.x, v2.x);
+    int t = max(v0.y, v2.y);
+    if ((l != min(v1.x, v3.x)) || (b != min(v1.y, v3.y)) ||
+        (r != max(v1.x, v3.x)) || (t != max(v1.y, v3.y))) {
+        LOGD_IF(DEBUG_COPYBIT, "geometry not a rectangle");
+        return false;
+    }
+
+    // fetch and transform texture coordinates
+    // NOTE: maybe it would be better to have a "compileElementsAll" method
+    // that would ensure all vertex data are fetched and transformed
+    const transform_t& tr = c->transforms.texture[0].transform; 
+    for (size_t i=0 ; i<4 ; i++) {
+        const GLubyte* tp = c->arrays.texture[0].element(i);
+        vertex_t* const v = &c->vc.vBuffer[i];
+        c->arrays.texture[0].fetch(c, v->texture[0].v, tp);
+        // FIXME: we should bail if q!=1
+        c->arrays.tex_transform[0](&tr, &v->texture[0], &v->texture[0]);
+    }
+    
+    const vec4_t& t0 = c->vc.vBuffer[0].texture[0];
+    const vec4_t& t1 = c->vc.vBuffer[1].texture[0];
+    const vec4_t& t2 = c->vc.vBuffer[2].texture[0];
+    const vec4_t& t3 = c->vc.vBuffer[3].texture[0];
+    int txl = min(t0.x, t2.x);
+    int txb = min(t0.y, t2.y);
+    int txr = max(t0.x, t2.x);
+    int txt = max(t0.y, t2.y);
+    if ((txl != min(t1.x, t3.x)) || (txb != min(t1.y, t3.y)) ||
+        (txr != max(t1.x, t3.x)) || (txt != max(t1.y, t3.y))) {
+        LOGD_IF(DEBUG_COPYBIT, "texcoord not a rectangle");
+        return false;
+    }
+    if ((txl != 0) || (txb != 0) ||
+        (txr != FIXED_ONE) || (txt != FIXED_ONE)) {
+        // we could probably handle this case, if we wanted to
+        LOGD_IF(DEBUG_COPYBIT, "texture is cropped: %08x,%08x,%08x,%08x",
+                txl, txb, txr, txt);
+        return false;
+    }
+
+    // at this point, we know we are dealing with a rectangle, so we 
+    // only need to consider 3 vertices for computing the jacobians
+    
+    const int dx01 = v1.x - v0.x;
+    const int dx02 = v2.x - v0.x;
+    const int dy01 = v1.y - v0.y;
+    const int dy02 = v2.y - v0.y;
+    const int ds01 = t1.S - t0.S;
+    const int ds02 = t2.S - t0.S;
+    const int dt01 = t1.T - t0.T;
+    const int dt02 = t2.T - t0.T;
+    const int area = dx01*dy02 - dy01*dx02;
+    int dsdx, dsdy, dtdx, dtdy;
+    if (area >= 0) {
+        dsdx = ds01*dy02 - ds02*dy01;
+        dtdx = dt01*dy02 - dt02*dy01;
+        dsdy = ds02*dx01 - ds01*dx02;
+        dtdy = dt02*dx01 - dt01*dx02;
+    } else {
+        dsdx = ds02*dy01 - ds01*dy02;
+        dtdx = dt02*dy01 - dt01*dy02;
+        dsdy = ds01*dx02 - ds02*dx01;
+        dtdy = dt01*dx02 - dt02*dx01;
+    }
+
+    // here we rely on the fact that we know the transform is
+    // a rigid-body transform AND that it can only rotate in 90 degrees
+    // increments
+
+    int transform = 0;
+    if (dsdx == 0) {
+        // 90 deg rotation case
+        // [ 0    dtdx  ]
+        // [ dsdx    0  ]
+        transform |= COPYBIT_TRANSFORM_ROT_90;
+        // FIXME: not sure if FLIP_H and FLIP_V shouldn't be inverted
+        if (dtdx > 0)
+            transform |= COPYBIT_TRANSFORM_FLIP_H;
+        if (dsdy < 0)
+            transform |= COPYBIT_TRANSFORM_FLIP_V;
+    } else {
+        // [ dsdx    0  ]
+        // [ 0     dtdy ]
+        if (dsdx < 0)
+            transform |= COPYBIT_TRANSFORM_FLIP_H;
+        if (dtdy < 0)
+            transform |= COPYBIT_TRANSFORM_FLIP_V;
+    }
+
+    //LOGD("l=%d, b=%d, w=%d, h=%d, tr=%d", x, y, w, h, transform);
+    //LOGD("A=%f\tB=%f\nC=%f\tD=%f",
+    //      dsdx/65536.0, dtdx/65536.0, dsdy/65536.0, dtdy/65536.0);
+
+    int x = l >> 4;
+    int y = b >> 4;
+    int w = (r-l) >> 4;
+    int h = (t-b) >> 4;
+    texture_unit_t& u(c->textures.tmu[0]);
+    EGLTextureObject* textureObject = u.texture;
+    GLint tWidth = textureObject->surface.width;
+    GLint tHeight = textureObject->surface.height;
+    GLint crop_rect[4] = {0, tHeight, tWidth, -tHeight};
+    const GGLSurface& cbSurface = c->rasterizer.state.buffers.color.s;
+    y = cbSurface.height - (y + h);
+    return copybit(x, y, w, h, textureObject, crop_rect, transform, c);
+}
+
+/*
+ * Try to drawTexiOESWithCopybit, return false if we fail.
+ */
+
+bool drawTexiOESWithCopybit_impl(GLint x, GLint y, GLint z,
+        GLint w, GLint h, ogles_context_t* c)
+{
+    // quickly process empty rects
+    if ((w|h) <= 0) {
+        return true;
+    }
+    if (!checkContext(c)) {
+        return false;
+    }
+    texture_unit_t& u(c->textures.tmu[0]);
+    EGLTextureObject* textureObject = u.texture;
+    return copybit(x, y, w, h, textureObject, textureObject->crop_rect, 0, c);
+}
+
+} // namespace android
+
diff --git a/opengl/libagl/copybit.h b/opengl/libagl/copybit.h
new file mode 100644
index 0000000..b8b5afd
--- /dev/null
+++ b/opengl/libagl/copybit.h
@@ -0,0 +1,75 @@
+/*
+**
+** Copyright 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.
+*/
+
+#ifndef ANDROID_OPENGLES_COPYBIT_H
+#define ANDROID_OPENGLES_COPYBIT_H
+
+#include <stdlib.h>
+
+#include <GLES/gl.h>
+
+#include "TextureObjectManager.h"
+namespace android {
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+
+bool drawTexiOESWithCopybit_impl(GLint x, GLint y, GLint z,
+        GLint w, GLint h, ogles_context_t* c);
+
+bool drawTriangleFanWithCopybit_impl(ogles_context_t* c, GLint first,
+        GLsizei count);
+
+inline bool copybitQuickCheckContext(ogles_context_t* c) {
+        return  c->copybits.drawSurfaceBuffer != 0
+            && c->rasterizer.state.enabled_tmu == 1
+            && c->textures.tmu[0].texture->try_copybit;
+}
+
+/*
+ * Tries to draw a drawTexiOES using copybit hardware.
+ * Returns true if successful.
+ */
+inline bool drawTexiOESWithCopybit(GLint x, GLint y, GLint z,
+        GLint w, GLint h, ogles_context_t* c) {
+    if (!copybitQuickCheckContext(c)) {
+    	return false;
+   	}
+   	
+   	return drawTexiOESWithCopybit_impl(x, y, z, w, h, c);
+}
+
+/*
+ * Tries to draw a triangle fan using copybit hardware.
+ * Returns true if successful.
+ */
+inline bool drawTriangleFanWithCopybit(ogles_context_t* c, GLint first,
+        GLsizei count) {
+    /*
+     * We are looking for the glDrawArrays call made by SurfaceFlinger.
+     */
+
+    if ((count!=4) || first || !copybitQuickCheckContext(c))
+        return false;
+    
+    return drawTriangleFanWithCopybit_impl(c, first, count);
+}
+
+
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
+
+} // namespace android
+
+#endif // ANDROID_OPENGLES_COPYBIT_H
diff --git a/opengl/libagl/egl.cpp b/opengl/libagl/egl.cpp
index 4461567..7afcae7 100644
--- a/opengl/libagl/egl.cpp
+++ b/opengl/libagl/egl.cpp
@@ -15,8 +15,6 @@
 ** limitations under the License.
 */
 
-#define LOG_TAG "EGL"
-
 #include <assert.h>
 #include <errno.h>
 #include <stdlib.h>
@@ -41,6 +39,10 @@
 #include <pixelflinger/format.h>
 #include <pixelflinger/pixelflinger.h>
 
+#include <private/ui/android_natives_priv.h>
+
+#include <hardware/copybit.h>
+
 #include "context.h"
 #include "state.h"
 #include "texture.h"
@@ -89,9 +91,9 @@
 struct egl_display_t
 {
     egl_display_t() : type(0), initialized(0) { }
-    
+
     static egl_display_t& get_display(EGLDisplay dpy);
-    
+
     static EGLBoolean is_valid(EGLDisplay dpy) {
         return ((uintptr_t(dpy)-1U) >= NUM_DISPLAYS) ? EGL_FALSE : EGL_TRUE;
     }
@@ -140,18 +142,21 @@
                 egl_surface_t(EGLDisplay dpy, EGLConfig config, int32_t depthFormat);
     virtual     ~egl_surface_t();
     virtual     bool    isValid() const = 0;
-    
+
     virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl) = 0;
     virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl) = 0;
+    virtual     void        connect() {}
+    virtual     void        disconnect() {}
     virtual     EGLint      getWidth() const = 0;
     virtual     EGLint      getHeight() const = 0;
-    virtual     void*       getBits() const = 0;
 
     virtual     EGLint      getHorizontalResolution() const;
     virtual     EGLint      getVerticalResolution() const;
     virtual     EGLint      getRefreshRate() const;
     virtual     EGLint      getSwapBehavior() const;
     virtual     EGLBoolean  swapBuffers();
+    virtual     EGLBoolean  setSwapRectangle(EGLint l, EGLint t, EGLint w, EGLint h);
+    virtual     EGLClientBuffer getRenderBuffer() const;
 protected:
     GGLSurface              depth;
 };
@@ -185,42 +190,191 @@
 EGLint egl_surface_t::getSwapBehavior() const {
     return EGL_BUFFER_PRESERVED;
 }
+EGLBoolean egl_surface_t::setSwapRectangle(
+        EGLint l, EGLint t, EGLint w, EGLint h)
+{
+    return EGL_FALSE;
+}
+EGLClientBuffer egl_surface_t::getRenderBuffer() const {
+    return 0;
+}
 
 // ----------------------------------------------------------------------------
 
-struct egl_window_surface_t : public egl_surface_t
+struct egl_window_surface_v2_t : public egl_surface_t
 {
-    egl_window_surface_t(
+    egl_window_surface_v2_t(
             EGLDisplay dpy, EGLConfig config,
             int32_t depthFormat,
-            egl_native_window_t* window);
+            android_native_window_t* window);
 
-     ~egl_window_surface_t();
+     ~egl_window_surface_v2_t();
 
-    virtual     bool        isValid() const { return nativeWindow->magic == 0x600913; }    
+    virtual     bool        isValid() const { return nativeWindow->common.magic == ANDROID_NATIVE_WINDOW_MAGIC; }
     virtual     EGLBoolean  swapBuffers();
     virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl);
     virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl);
-    virtual     EGLint      getWidth() const    { return nativeWindow->width;  }
-    virtual     EGLint      getHeight() const   { return nativeWindow->height; }
-    virtual     void*       getBits() const;
+    virtual     void        connect();
+    virtual     void        disconnect();
+    virtual     EGLint      getWidth() const    { return buffer->width;  }
+    virtual     EGLint      getHeight() const   { return buffer->height; }
     virtual     EGLint      getHorizontalResolution() const;
     virtual     EGLint      getVerticalResolution() const;
     virtual     EGLint      getRefreshRate() const;
     virtual     EGLint      getSwapBehavior() const;
+    virtual     EGLBoolean  setSwapRectangle(EGLint l, EGLint t, EGLint w, EGLint h);
+    virtual     EGLClientBuffer  getRenderBuffer() const;
+    
 private:
-    egl_native_window_t*    nativeWindow;
+    status_t lock(android_native_buffer_t* buf, int usage, void** vaddr);
+    status_t unlock(android_native_buffer_t* buf);
+    android_native_window_t*   nativeWindow;
+    android_native_buffer_t*   buffer;
+    android_native_buffer_t*   previousBuffer;
+    gralloc_module_t const*    module;
+    copybit_device_t*          blitengine;
+    int width;
+    int height;
+    void* bits;
+    GGLFormat const* pixelFormatTable;
+    
+    struct Rect {
+        inline Rect() { };
+        inline Rect(int32_t w, int32_t h)
+            : left(0), top(0), right(w), bottom(h) { }
+        inline Rect(int32_t l, int32_t t, int32_t r, int32_t b)
+            : left(l), top(t), right(r), bottom(b) { }
+        Rect& andSelf(const Rect& r) {
+            left   = max(left, r.left);
+            top    = max(top, r.top);
+            right  = min(right, r.right);
+            bottom = min(bottom, r.bottom);
+            return *this;
+        }
+        bool isEmpty() const {
+            return (left>=right || top>=bottom);
+        }
+        void dump(char const* what) {
+            LOGD("%s { %5d, %5d, w=%5d, h=%5d }", 
+                    what, left, top, right-left, bottom-top);
+        }
+        
+        int32_t left;
+        int32_t top;
+        int32_t right;
+        int32_t bottom;
+    };
+
+    struct Region {
+        inline Region() : count(0) { }
+        typedef Rect const* const_iterator;
+        const_iterator begin() const { return storage; }
+        const_iterator end() const { return storage+count; }
+        static Region subtract(const Rect& lhs, const Rect& rhs) {
+            Region reg;
+            Rect* storage = reg.storage;
+            if (!lhs.isEmpty()) {
+                if (lhs.top < rhs.top) { // top rect
+                    storage->left   = lhs.left;
+                    storage->top    = lhs.top;
+                    storage->right  = lhs.right;
+                    storage->bottom = rhs.top;
+                    storage++;
+                }
+                const int32_t top = max(lhs.top, rhs.top);
+                const int32_t bot = min(lhs.bottom, rhs.bottom);
+                if (top < bot) {
+                    if (lhs.left < rhs.left) { // left-side rect
+                        storage->left   = lhs.left;
+                        storage->top    = top;
+                        storage->right  = rhs.left;
+                        storage->bottom = bot;
+                        storage++;
+                    }
+                    if (lhs.right > rhs.right) { // right-side rect
+                        storage->left   = rhs.right;
+                        storage->top    = top;
+                        storage->right  = lhs.right;
+                        storage->bottom = bot;
+                        storage++;
+                    }
+                }
+                if (lhs.bottom > rhs.bottom) { // bottom rect
+                    storage->left   = lhs.left;
+                    storage->top    = rhs.bottom;
+                    storage->right  = lhs.right;
+                    storage->bottom = lhs.bottom;
+                    storage++;
+                }
+                reg.count = storage - reg.storage;
+            }
+            return reg;
+        }
+        bool isEmpty() const {
+            return count<=0;
+        }
+    private:
+        Rect storage[4];
+        ssize_t count;
+    };
+    
+    struct region_iterator : public copybit_region_t {
+        region_iterator(const Region& region)
+            : b(region.begin()), e(region.end()) {
+            this->next = iterate;
+        }
+    private:
+        static int iterate(copybit_region_t const * self, copybit_rect_t* rect) {
+            region_iterator const* me = static_cast<region_iterator const*>(self);
+            if (me->b != me->e) {
+                *reinterpret_cast<Rect*>(rect) = *me->b++;
+                return 1;
+            }
+            return 0;
+        }
+        mutable Region::const_iterator b;
+        Region::const_iterator const e;
+    };
+
+    void copyBlt(
+            android_native_buffer_t* dst, void* dst_vaddr,
+            android_native_buffer_t* src, void const* src_vaddr,
+            const Region& clip);
+
+    Rect dirtyRegion;
+    Rect oldDirtyRegion;
 };
 
-egl_window_surface_t::egl_window_surface_t(EGLDisplay dpy,
+egl_window_surface_v2_t::egl_window_surface_v2_t(EGLDisplay dpy,
         EGLConfig config,
         int32_t depthFormat,
-        egl_native_window_t* window)
-    : egl_surface_t(dpy, config, depthFormat), nativeWindow(window)
+        android_native_window_t* window)
+    : egl_surface_t(dpy, config, depthFormat), 
+    nativeWindow(window), buffer(0), previousBuffer(0), module(0),
+    blitengine(0), bits(NULL)
 {
+    hw_module_t const* pModule;
+    hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &pModule);
+    module = reinterpret_cast<gralloc_module_t const*>(pModule);
+
+    if (hw_get_module(COPYBIT_HARDWARE_MODULE_ID, &pModule) == 0) {
+        copybit_open(pModule, &blitengine);
+    }
+
+    pixelFormatTable = gglGetPixelFormatTable();
+    
+    // keep a reference on the window
+    nativeWindow->common.incRef(&nativeWindow->common);
+
+    // dequeue a buffer
+    nativeWindow->dequeueBuffer(nativeWindow, &buffer);
+
+    // allocate a corresponding depth-buffer
+    width = buffer->width;
+    height = buffer->height;
     if (depthFormat) {
-        depth.width   = window->width;
-        depth.height  = window->height;
+        depth.width   = width;
+        depth.height  = height;
         depth.stride  = depth.width; // use the width here
         depth.data    = (GGLubyte*)malloc(depth.stride*depth.height*2);
         if (depth.data == 0) {
@@ -228,76 +382,292 @@
             return;
         }
     }
-    nativeWindow->incRef(nativeWindow);
-}
-egl_window_surface_t::~egl_window_surface_t() {
-    nativeWindow->decRef(nativeWindow);
+
+    // keep a reference on the buffer
+    buffer->common.incRef(&buffer->common);
 }
 
-EGLBoolean egl_window_surface_t::swapBuffers()
+egl_window_surface_v2_t::~egl_window_surface_v2_t() {
+    if (buffer) {
+        buffer->common.decRef(&buffer->common);
+    }
+    if (previousBuffer) {
+        previousBuffer->common.decRef(&previousBuffer->common); 
+    }
+    nativeWindow->common.decRef(&nativeWindow->common);
+    if (blitengine) {
+        copybit_close(blitengine);
+    }
+}
+
+void egl_window_surface_v2_t::connect() 
 {
-    uint32_t flags = nativeWindow->swapBuffers(nativeWindow);
-    if (flags & EGL_NATIVES_FLAG_SIZE_CHANGED) {
+    // Lock the buffer
+    nativeWindow->lockBuffer(nativeWindow, buffer);
+    // pin the buffer down
+    if (lock(buffer, GRALLOC_USAGE_SW_READ_OFTEN | 
+            GRALLOC_USAGE_SW_WRITE_OFTEN, &bits) != NO_ERROR) {
+        LOGE("connect() failed to lock buffer %p (%ux%u)",
+                buffer, buffer->width, buffer->height);
+        setError(EGL_BAD_ACCESS, EGL_NO_SURFACE);
+        // FIXME: we should make sure we're not accessing the buffer anymore
+    }
+}
+
+void egl_window_surface_v2_t::disconnect() 
+{
+    if (buffer && bits) {
+        bits = NULL;
+        unlock(buffer);
+    }
+}
+
+status_t egl_window_surface_v2_t::lock(
+        android_native_buffer_t* buf, int usage, void** vaddr)
+{
+    int err = module->lock(module, buf->handle, 
+            usage, 0, 0, buf->width, buf->height, vaddr);
+    return err;
+}
+
+status_t egl_window_surface_v2_t::unlock(android_native_buffer_t* buf)
+{
+    int err = module->unlock(module, buf->handle);
+    return err;
+}
+
+void egl_window_surface_v2_t::copyBlt(
+        android_native_buffer_t* dst, void* dst_vaddr,
+        android_native_buffer_t* src, void const* src_vaddr,
+        const Region& clip)
+{
+    // FIXME: use copybit if possible
+    // NOTE: dst and src must be the same format
+    
+    status_t err = NO_ERROR;
+    copybit_device_t* const copybit = blitengine;
+    if (copybit)  {
+        copybit_image_t simg;
+        simg.w = src->width;
+        simg.h = src->height;
+        simg.format = src->format;
+        simg.handle = const_cast<native_handle_t*>(src->handle);
+
+        copybit_image_t dimg;
+        dimg.w = dst->width;
+        dimg.h = dst->height;
+        dimg.format = dst->format;
+        dimg.handle = const_cast<native_handle_t*>(dst->handle);
+        
+        copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0);
+        copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 255);
+        copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_DISABLE);
+        region_iterator it(clip);
+        err = copybit->blit(copybit, &dimg, &simg, &it);
+        if (err != NO_ERROR) {
+            LOGE("copybit failed (%s)", strerror(err));
+        }
+    }
+
+    if (!copybit || err) {
+        Region::const_iterator cur = clip.begin();
+        Region::const_iterator end = clip.end();
+        
+        const size_t bpp = pixelFormatTable[src->format].size;
+        const size_t dbpr = dst->stride * bpp;
+        const size_t sbpr = src->stride * bpp;
+
+        uint8_t const * const src_bits = (uint8_t const *)src_vaddr;
+        uint8_t       * const dst_bits = (uint8_t       *)dst_vaddr;
+
+        while (cur != end) {
+            const Rect& r(*cur++);
+            ssize_t w = r.right - r.left;
+            ssize_t h = r.bottom - r.top;
+            if (w <= 0 || h<=0) continue;
+            size_t size = w * bpp;
+            uint8_t const * s = src_bits + (r.left + src->stride * r.top) * bpp;
+            uint8_t       * d = dst_bits + (r.left + dst->stride * r.top) * bpp;
+            if (dbpr==sbpr && size==sbpr) {
+                size *= h;
+                h = 1;
+            }
+            do {
+                memcpy(d, s, size);
+                d += dbpr;
+                s += sbpr;
+            } while (--h > 0);
+        }
+    }
+}
+
+EGLBoolean egl_window_surface_v2_t::swapBuffers()
+{
+    /*
+     * Handle eglSetSwapRectangleANDROID()
+     * We copyback from the front buffer 
+     */
+    if (!dirtyRegion.isEmpty()) {
+        dirtyRegion.andSelf(Rect(buffer->width, buffer->height));
+        if (previousBuffer) {
+            const Region copyBack(Region::subtract(oldDirtyRegion, dirtyRegion));
+            if (!copyBack.isEmpty()) {
+                void* prevBits;
+                if (lock(previousBuffer, 
+                        GRALLOC_USAGE_SW_READ_OFTEN, &prevBits) == NO_ERROR) {
+                    // copy from previousBuffer to buffer
+                    copyBlt(buffer, bits, previousBuffer, prevBits, copyBack);
+                    unlock(previousBuffer);
+                }
+            }
+        }
+        oldDirtyRegion = dirtyRegion;
+    }
+
+    if (previousBuffer) {
+        previousBuffer->common.decRef(&previousBuffer->common); 
+        previousBuffer = 0;
+    }
+    
+    unlock(buffer);
+    previousBuffer = buffer;
+    nativeWindow->queueBuffer(nativeWindow, buffer);
+    buffer = 0;
+
+    // dequeue a new buffer
+    nativeWindow->dequeueBuffer(nativeWindow, &buffer);
+    
+    // TODO: lockBuffer should rather be executed when the very first
+    // direct rendering occurs.
+    nativeWindow->lockBuffer(nativeWindow, buffer);
+    
+    // reallocate the depth-buffer if needed
+    if ((width != buffer->width) || (height != buffer->height)) {
         // TODO: we probably should reset the swap rect here
         // if the window size has changed
+        width = buffer->width;
+        height = buffer->height;
         if (depth.data) {
             free(depth.data);
-            depth.width   = nativeWindow->width;
-            depth.height  = nativeWindow->height;
-            depth.stride  = nativeWindow->stride;
+            depth.width   = width;
+            depth.height  = height;
+            depth.stride  = buffer->stride;
             depth.data    = (GGLubyte*)malloc(depth.stride*depth.height*2);
             if (depth.data == 0) {
-                setError(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+                setError(EGL_BAD_ALLOC, EGL_FALSE);
                 return EGL_FALSE;
             }
         }
     }
+    
+    // keep a reference on the buffer
+    buffer->common.incRef(&buffer->common);
+
+    // finally pin the buffer down
+    if (lock(buffer, GRALLOC_USAGE_SW_READ_OFTEN | 
+            GRALLOC_USAGE_SW_WRITE_OFTEN, &bits) != NO_ERROR) {
+        LOGE("eglSwapBuffers() failed to lock buffer %p (%ux%u)",
+                buffer, buffer->width, buffer->height);
+        setError(EGL_BAD_ACCESS, EGL_NO_SURFACE);
+        // FIXME: we should make sure we're not accessing the buffer anymore
+    }
+
     return EGL_TRUE;
 }
 
-EGLBoolean egl_window_surface_t::bindDrawSurface(ogles_context_t* gl)
+EGLBoolean egl_window_surface_v2_t::setSwapRectangle(
+        EGLint l, EGLint t, EGLint w, EGLint h)
+{
+    dirtyRegion = Rect(l, t, l+w, t+h);
+    return EGL_TRUE;
+}
+
+EGLClientBuffer egl_window_surface_v2_t::getRenderBuffer() const
+{
+    return buffer;
+}
+
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+
+static bool supportedCopybitsDestinationFormat(int format) {
+    // Hardware supported
+    switch (format) {
+    case HAL_PIXEL_FORMAT_RGB_565:
+    case HAL_PIXEL_FORMAT_RGBA_8888:
+    case HAL_PIXEL_FORMAT_RGBA_4444:
+    case HAL_PIXEL_FORMAT_RGBA_5551:
+    case HAL_PIXEL_FORMAT_BGRA_8888:
+        return true;
+    }
+    return false;
+}
+#endif
+
+EGLBoolean egl_window_surface_v2_t::bindDrawSurface(ogles_context_t* gl)
 {
     GGLSurface buffer;
     buffer.version = sizeof(GGLSurface);
-    buffer.width   = nativeWindow->width;
-    buffer.height  = nativeWindow->height;
-    buffer.stride  = nativeWindow->stride;
-    buffer.data    = (GGLubyte*)nativeWindow->base + nativeWindow->offset;
-    buffer.format  = nativeWindow->format;
+    buffer.width   = this->buffer->width;
+    buffer.height  = this->buffer->height;
+    buffer.stride  = this->buffer->stride;
+    buffer.data    = (GGLubyte*)bits;
+    buffer.format  = this->buffer->format;
     gl->rasterizer.procs.colorBuffer(gl, &buffer);
     if (depth.data != gl->rasterizer.state.buffers.depth.data)
         gl->rasterizer.procs.depthBuffer(gl, &depth);
+
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+    gl->copybits.drawSurfaceBuffer = 0;
+    if (gl->copybits.blitEngine != NULL) {
+        if (supportedCopybitsDestinationFormat(buffer.format)) {
+            buffer_handle_t handle = this->buffer->handle;
+            if (handle != NULL) {
+                gl->copybits.drawSurfaceBuffer = handle;
+            }
+        }
+    }
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
+
     return EGL_TRUE;
 }
-EGLBoolean egl_window_surface_t::bindReadSurface(ogles_context_t* gl)
+EGLBoolean egl_window_surface_v2_t::bindReadSurface(ogles_context_t* gl)
 {
     GGLSurface buffer;
     buffer.version = sizeof(GGLSurface);
-    buffer.width   = nativeWindow->width;
-    buffer.height  = nativeWindow->height;
-    buffer.stride  = nativeWindow->stride;
-    buffer.data    = (GGLubyte*)nativeWindow->base + nativeWindow->offset;
-    buffer.format  = nativeWindow->format;
+    buffer.width   = this->buffer->width;
+    buffer.height  = this->buffer->height;
+    buffer.stride  = this->buffer->stride;
+    buffer.data    = (GGLubyte*)bits; // FIXME: hopefully is is LOCKED!!!
+    buffer.format  = this->buffer->format;
     gl->rasterizer.procs.readBuffer(gl, &buffer);
     return EGL_TRUE;
 }
-void* egl_window_surface_t::getBits() const {
-    return (GGLubyte*)nativeWindow->base + nativeWindow->offset;
-}
-EGLint egl_window_surface_t::getHorizontalResolution() const {
+EGLint egl_window_surface_v2_t::getHorizontalResolution() const {
     return (nativeWindow->xdpi * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
 }
-EGLint egl_window_surface_t::getVerticalResolution() const {
+EGLint egl_window_surface_v2_t::getVerticalResolution() const {
     return (nativeWindow->ydpi * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
 }
-EGLint egl_window_surface_t::getRefreshRate() const {
-    return (nativeWindow->fps * EGL_DISPLAY_SCALING);
+EGLint egl_window_surface_v2_t::getRefreshRate() const {
+    return (60 * EGL_DISPLAY_SCALING); // FIXME
 }
-EGLint egl_window_surface_t::getSwapBehavior() const {
-    uint32_t flags = nativeWindow->flags;
-    if (flags & EGL_NATIVES_FLAG_DESTROY_BACKBUFFER)
-        return EGL_BUFFER_DESTROYED;
-    return EGL_BUFFER_PRESERVED;
+EGLint egl_window_surface_v2_t::getSwapBehavior() const 
+{
+    /*
+     * EGL_BUFFER_PRESERVED means that eglSwapBuffers() completely preserves
+     * the content of the swapped buffer.
+     * 
+     * EGL_BUFFER_DESTROYED means that the content of the buffer is lost.
+     * 
+     * However when ANDROID_swap_retcangle is supported, EGL_BUFFER_DESTROYED
+     * only applies to the area specified by eglSetSwapRectangleANDROID(), that
+     * is, everything outside of this area is preserved.
+     * 
+     * This implementation of EGL assumes the later case.
+     * 
+     */
+
+    return EGL_BUFFER_DESTROYED;
 }
 
 // ----------------------------------------------------------------------------
@@ -311,12 +681,11 @@
 
     virtual ~egl_pixmap_surface_t() { }
 
-    virtual     bool        isValid() const { return nativePixmap.version == sizeof(egl_native_pixmap_t); }    
+    virtual     bool        isValid() const { return nativePixmap.version == sizeof(egl_native_pixmap_t); }
     virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl);
     virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl);
     virtual     EGLint      getWidth() const    { return nativePixmap.width;  }
     virtual     EGLint      getHeight() const   { return nativePixmap.height; }
-    virtual     void*       getBits() const     { return nativePixmap.data; }
 private:
     egl_native_pixmap_t     nativePixmap;
 };
@@ -347,7 +716,7 @@
     buffer.stride  = nativePixmap.stride;
     buffer.data    = nativePixmap.data;
     buffer.format  = nativePixmap.format;
-    
+
     gl->rasterizer.procs.colorBuffer(gl, &buffer);
     if (depth.data != gl->rasterizer.state.buffers.depth.data)
         gl->rasterizer.procs.depthBuffer(gl, &depth);
@@ -376,12 +745,11 @@
 
     virtual ~egl_pbuffer_surface_t();
 
-    virtual     bool        isValid() const { return pbuffer.data != 0; }    
+    virtual     bool        isValid() const { return pbuffer.data != 0; }
     virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl);
     virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl);
     virtual     EGLint      getWidth() const    { return pbuffer.width;  }
     virtual     EGLint      getHeight() const   { return pbuffer.height; }
-    virtual     void*       getBits() const     { return pbuffer.data; }
 private:
     GGLSurface  pbuffer;
 };
@@ -407,7 +775,7 @@
     pbuffer.stride  = w;
     pbuffer.data    = (GGLubyte*)malloc(size);
     pbuffer.format  = f;
-    
+
     if (depthFormat) {
         depth.width   = pbuffer.width;
         depth.height  = pbuffer.height;
@@ -468,7 +836,13 @@
 static char const * const gVendorString     = "Google Inc.";
 static char const * const gVersionString    = "1.2 Android Driver";
 static char const * const gClientApiString  = "OpenGL ES";
-static char const * const gExtensionsString = "";
+static char const * const gExtensionsString =
+        "EGL_KHR_image_base "
+        // "KHR_image_pixmap "
+        "EGL_ANDROID_image_native_buffer "
+        "EGL_ANDROID_swap_rectangle "
+        "EGL_ANDROID_get_render_buffer "
+        ;
 
 // ----------------------------------------------------------------------------
 
@@ -496,6 +870,10 @@
             (__eglMustCastToProperFunctionPointerType)&glDrawTexxvOES },
     { "glQueryMatrixxOES",
             (__eglMustCastToProperFunctionPointerType)&glQueryMatrixxOES },
+    { "glEGLImageTargetTexture2DOES",
+            (__eglMustCastToProperFunctionPointerType)&glEGLImageTargetTexture2DOES },
+    { "glEGLImageTargetRenderbufferStorageOES",
+            (__eglMustCastToProperFunctionPointerType)&glEGLImageTargetRenderbufferStorageOES },
     { "glClipPlanef",
             (__eglMustCastToProperFunctionPointerType)&glClipPlanef },
     { "glClipPlanex",
@@ -510,9 +888,17 @@
             (__eglMustCastToProperFunctionPointerType)&glDeleteBuffers },
     { "glGenBuffers",
             (__eglMustCastToProperFunctionPointerType)&glGenBuffers },
+    { "eglCreateImageKHR",  
+            (__eglMustCastToProperFunctionPointerType)&eglCreateImageKHR }, 
+    { "eglDestroyImageKHR", 
+            (__eglMustCastToProperFunctionPointerType)&eglDestroyImageKHR }, 
+    { "eglSetSwapRectangleANDROID", 
+            (__eglMustCastToProperFunctionPointerType)&eglSetSwapRectangleANDROID }, 
+    { "eglGetRenderBufferANDROID", 
+            (__eglMustCastToProperFunctionPointerType)&eglGetRenderBufferANDROID }, 
 };
 
-/* 
+/*
  * In the lists below, attributes names MUST be sorted.
  * Additionally, all configs must be sorted according to
  * the EGL specification.
@@ -523,7 +909,7 @@
         { EGL_CONFIG_CAVEAT,              EGL_SLOW_CONFIG                   },
         { EGL_LEVEL,                      0                                 },
         { EGL_MAX_PBUFFER_HEIGHT,         GGL_MAX_VIEWPORT_DIMS             },
-        { EGL_MAX_PBUFFER_PIXELS,         
+        { EGL_MAX_PBUFFER_PIXELS,
                 GGL_MAX_VIEWPORT_DIMS*GGL_MAX_VIEWPORT_DIMS                 },
         { EGL_MAX_PBUFFER_WIDTH,          GGL_MAX_VIEWPORT_DIMS             },
         { EGL_NATIVE_RENDERABLE,          EGL_TRUE                          },
@@ -660,9 +1046,9 @@
 {
    while (first <= last) {
        int mid = (first + last) / 2;
-       if (key > sortedArray[mid].key) { 
+       if (key > sortedArray[mid].key) {
            first = mid + 1;
-       } else if (key < sortedArray[mid].key) { 
+       } else if (key < sortedArray[mid].key) {
            last = mid - 1;
        } else {
            return mid;
@@ -674,13 +1060,13 @@
 static int isAttributeMatching(int i, EGLint attr, EGLint val)
 {
     // look for the attribute in all of our configs
-    config_pair_t const* configFound = gConfigs[i].array; 
+    config_pair_t const* configFound = gConfigs[i].array;
     int index = binarySearch<config_pair_t>(
             gConfigs[i].array,
             0, gConfigs[i].size-1,
             attr);
     if (index < 0) {
-        configFound = config_base_attribute_list; 
+        configFound = config_base_attribute_list;
         index = binarySearch<config_pair_t>(
                 config_base_attribute_list,
                 0, NELEM(config_base_attribute_list)-1,
@@ -794,28 +1180,28 @@
     int32_t depthFormat;
     int32_t pixelFormat;
     switch(configID) {
-    case 0: 
-        pixelFormat = GGL_PIXEL_FORMAT_RGB_565; 
+    case 0:
+        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
         depthFormat = 0;
         break;
     case 1:
-        pixelFormat = GGL_PIXEL_FORMAT_RGB_565; 
+        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
         depthFormat = GGL_PIXEL_FORMAT_Z_16;
         break;
     case 2:
-        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888; 
+        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
         depthFormat = 0;
         break;
     case 3:
-        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888; 
+        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
         depthFormat = GGL_PIXEL_FORMAT_Z_16;
         break;
     case 4:
-        pixelFormat = GGL_PIXEL_FORMAT_A_8; 
+        pixelFormat = GGL_PIXEL_FORMAT_A_8;
         depthFormat = 0;
         break;
     case 5:
-        pixelFormat = GGL_PIXEL_FORMAT_A_8; 
+        pixelFormat = GGL_PIXEL_FORMAT_A_8;
         depthFormat = GGL_PIXEL_FORMAT_Z_16;
         break;
     default:
@@ -828,9 +1214,9 @@
     //if (EGLint(info.format) != pixelFormat)
     //    return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
 
-    egl_surface_t* surface =
-        new egl_window_surface_t(dpy, config, depthFormat,
-                static_cast<egl_native_window_t*>(window));
+    egl_surface_t* surface;
+    surface = new egl_window_surface_v2_t(dpy, config, depthFormat,
+            static_cast<android_native_window_t*>(window));
 
     if (!surface->isValid()) {
         // there was a problem in the ctor, the error
@@ -863,28 +1249,28 @@
     int32_t depthFormat;
     int32_t pixelFormat;
     switch(configID) {
-    case 0: 
-        pixelFormat = GGL_PIXEL_FORMAT_RGB_565; 
+    case 0:
+        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
         depthFormat = 0;
         break;
     case 1:
-        pixelFormat = GGL_PIXEL_FORMAT_RGB_565; 
+        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
         depthFormat = GGL_PIXEL_FORMAT_Z_16;
         break;
     case 2:
-        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888; 
+        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
         depthFormat = 0;
         break;
     case 3:
-        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888; 
+        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
         depthFormat = GGL_PIXEL_FORMAT_Z_16;
         break;
     case 4:
-        pixelFormat = GGL_PIXEL_FORMAT_A_8; 
+        pixelFormat = GGL_PIXEL_FORMAT_A_8;
         depthFormat = 0;
         break;
     case 5:
-        pixelFormat = GGL_PIXEL_FORMAT_A_8; 
+        pixelFormat = GGL_PIXEL_FORMAT_A_8;
         depthFormat = GGL_PIXEL_FORMAT_Z_16;
         break;
     default:
@@ -916,10 +1302,10 @@
     EGLint surfaceType;
     if (getConfigAttrib(dpy, config, EGL_SURFACE_TYPE, &surfaceType) == EGL_FALSE)
         return EGL_FALSE;
-    
+
     if (!(surfaceType & EGL_PBUFFER_BIT))
         return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
-        
+
     EGLint configID;
     if (getConfigAttrib(dpy, config, EGL_CONFIG_ID, &configID) == EGL_FALSE)
         return EGL_FALSE;
@@ -927,28 +1313,28 @@
     int32_t depthFormat;
     int32_t pixelFormat;
     switch(configID) {
-    case 0: 
-        pixelFormat = GGL_PIXEL_FORMAT_RGB_565; 
+    case 0:
+        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
         depthFormat = 0;
         break;
     case 1:
-        pixelFormat = GGL_PIXEL_FORMAT_RGB_565; 
+        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
         depthFormat = GGL_PIXEL_FORMAT_Z_16;
         break;
     case 2:
-        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888; 
+        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
         depthFormat = 0;
         break;
     case 3:
-        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888; 
+        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
         depthFormat = GGL_PIXEL_FORMAT_Z_16;
         break;
     case 4:
-        pixelFormat = GGL_PIXEL_FORMAT_A_8; 
+        pixelFormat = GGL_PIXEL_FORMAT_A_8;
         depthFormat = 0;
         break;
     case 5:
-        pixelFormat = GGL_PIXEL_FORMAT_A_8; 
+        pixelFormat = GGL_PIXEL_FORMAT_A_8;
         depthFormat = GGL_PIXEL_FORMAT_Z_16;
         break;
     default:
@@ -1001,7 +1387,7 @@
         egl_display_t& d = egl_display_t::get_display(dpy);
         d.type = display;
         return dpy;
-    }    
+    }
     return EGL_NO_DISPLAY;
 }
 
@@ -1009,10 +1395,10 @@
 {
     if (egl_display_t::is_valid(dpy) == EGL_FALSE)
         return setError(EGL_BAD_DISPLAY, EGL_FALSE);
-    
+
     EGLBoolean res = EGL_TRUE;
     egl_display_t& d = egl_display_t::get_display(dpy);
-    
+
     if (android_atomic_inc(&d.initialized) == 0) {
         // initialize stuff here if needed
         //pthread_mutex_lock(&gInitMutex);
@@ -1080,7 +1466,7 @@
         *num_config = 0;
         return EGL_TRUE;
     }
-    
+
     int numAttributes = 0;
     int numConfigs =  NELEM(gConfigs);
     uint32_t possibleMatch = (1<<numConfigs)-1;
@@ -1161,7 +1547,7 @@
 {
     return createWindowSurface(dpy, config, window, attrib_list);
 }
-    
+
 EGLSurface eglCreatePixmapSurface(  EGLDisplay dpy, EGLConfig config,
                                     NativePixmapType pixmap,
                                     const EGLint *attrib_list)
@@ -1174,7 +1560,7 @@
 {
     return createPbufferSurface(dpy, config, attrib_list);
 }
-                                    
+
 EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface eglSurface)
 {
     if (egl_display_t::is_valid(dpy) == EGL_FALSE)
@@ -1185,6 +1571,11 @@
             return setError(EGL_BAD_SURFACE, EGL_FALSE);
         if (surface->dpy != dpy)
             return setError(EGL_BAD_DISPLAY, EGL_FALSE);
+        if (surface->ctx) {
+            // FIXME: this surface is current check what the spec says
+            surface->disconnect();
+            surface->ctx = 0;
+        }
         delete surface;
     }
     return EGL_TRUE;
@@ -1244,7 +1635,7 @@
             *value = (wr * EGL_DISPLAY_SCALING) / hr;
         } break;
         case EGL_SWAP_BEHAVIOR:
-            *value = surface->getSwapBehavior(); 
+            *value = surface->getSwapBehavior();
             break;
         default:
             ret = setError(EGL_BAD_ATTRIBUTE, EGL_FALSE);
@@ -1294,7 +1685,7 @@
     }
 
     EGLContext current_ctx = EGL_NO_CONTEXT;
-    
+
     if ((read == EGL_NO_SURFACE && draw == EGL_NO_SURFACE) && (ctx != EGL_NO_CONTEXT))
         return setError(EGL_BAD_MATCH, EGL_FALSE);
 
@@ -1310,21 +1701,28 @@
         egl_surface_t* r = (egl_surface_t*)read;
         if ((d && d->ctx && d->ctx != ctx) ||
             (r && r->ctx && r->ctx != ctx)) {
-            // once of the surface is bound to a context in another thread
+            // one of the surface is bound to a context in another thread
             return setError(EGL_BAD_ACCESS, EGL_FALSE);
         }
     }
 
-    // TODO: call connect / disconnect on the surface
-
     ogles_context_t* gl = (ogles_context_t*)ctx;
     if (makeCurrent(gl) == 0) {
         if (ctx) {
             egl_context_t* c = egl_context_t::context(ctx);
             egl_surface_t* d = (egl_surface_t*)draw;
             egl_surface_t* r = (egl_surface_t*)read;
-            c->read = read;
+            
+            if (c->draw) {
+                reinterpret_cast<egl_surface_t*>(c->draw)->disconnect();
+            }
+            if (c->read) {
+                // FIXME: unlock/disconnect the read surface too 
+            }
+            
             c->draw = draw;
+            c->read = read;
+
             if (c->flags & egl_context_t::NEVER_CURRENT) {
                 c->flags &= ~egl_context_t::NEVER_CURRENT;
                 GLint w = 0;
@@ -1338,10 +1736,12 @@
                 ogles_scissor(gl, 0, 0, w, h);
             }
             if (d) {
+                d->connect();
                 d->ctx = ctx;
                 d->bindDrawSurface(gl);
             }
             if (r) {
+                // FIXME: lock/connect the read surface too 
                 r->ctx = ctx;
                 r->bindReadSurface(gl);
             }
@@ -1352,8 +1752,16 @@
                 egl_context_t* c = egl_context_t::context(current_ctx);
                 egl_surface_t* d = (egl_surface_t*)c->draw;
                 egl_surface_t* r = (egl_surface_t*)c->read;
-                if (d) d->ctx = EGL_NO_CONTEXT;
-                if (r) r->ctx = EGL_NO_CONTEXT;
+                if (d) {
+                    c->draw = 0;
+                    d->ctx = EGL_NO_CONTEXT;
+                    d->disconnect();
+                }
+                if (r) {
+                    c->read = 0;
+                    r->ctx = EGL_NO_CONTEXT;
+                    // FIXME: unlock/disconnect the read surface too 
+                }
             }
         }
         return EGL_TRUE;
@@ -1425,7 +1833,7 @@
 {
     if (egl_display_t::is_valid(dpy) == EGL_FALSE)
         return setError(EGL_BAD_DISPLAY, EGL_FALSE);
-    
+
     egl_surface_t* d = static_cast<egl_surface_t*>(draw);
     if (d->dpy != dpy)
         return setError(EGL_BAD_DISPLAY, EGL_FALSE);
@@ -1558,7 +1966,7 @@
 }
 
 // ----------------------------------------------------------------------------
-// Android extensions
+// EGL_EGLEXT_VERSION 3
 // ----------------------------------------------------------------------------
 
 void (*eglGetProcAddress (const char *procname))()
@@ -1571,3 +1979,93 @@
     }
     return NULL;
 }
+
+EGLBoolean eglLockSurfaceKHR(EGLDisplay dpy, EGLSurface surface,
+        const EGLint *attrib_list)
+{
+    EGLBoolean result = EGL_FALSE;
+    return result;
+}
+
+EGLBoolean eglUnlockSurfaceKHR(EGLDisplay dpy, EGLSurface surface)
+{
+    EGLBoolean result = EGL_FALSE;
+    return result;
+}
+
+EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target,
+        EGLClientBuffer buffer, const EGLint *attrib_list)
+{
+    if (egl_display_t::is_valid(dpy) == EGL_FALSE) {
+        return setError(EGL_BAD_DISPLAY, EGL_NO_IMAGE_KHR);
+    }
+    if (ctx != EGL_NO_CONTEXT) {
+        return setError(EGL_BAD_CONTEXT, EGL_NO_IMAGE_KHR);
+    }
+    if (target != EGL_NATIVE_BUFFER_ANDROID) {
+        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
+    }
+
+    android_native_buffer_t* native_buffer = (android_native_buffer_t*)buffer;
+
+    if (native_buffer->common.magic != ANDROID_NATIVE_BUFFER_MAGIC)
+        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
+
+    if (native_buffer->common.version != sizeof(android_native_buffer_t))
+        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
+    
+    native_buffer->common.incRef(&native_buffer->common);
+    return (EGLImageKHR)native_buffer;
+}
+
+EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR img)
+{
+    if (egl_display_t::is_valid(dpy) == EGL_FALSE) {
+        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
+    }
+
+    android_native_buffer_t* native_buffer = (android_native_buffer_t*)img;
+
+    if (native_buffer->common.magic != ANDROID_NATIVE_BUFFER_MAGIC)
+        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
+
+    if (native_buffer->common.version != sizeof(android_native_buffer_t))
+        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
+
+    native_buffer->common.decRef(&native_buffer->common);
+
+    return EGL_TRUE;
+}
+
+// ----------------------------------------------------------------------------
+// ANDROID extensions
+// ----------------------------------------------------------------------------
+
+EGLBoolean eglSetSwapRectangleANDROID(EGLDisplay dpy, EGLSurface draw,
+        EGLint left, EGLint top, EGLint width, EGLint height)
+{
+    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
+        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
+
+    egl_surface_t* d = static_cast<egl_surface_t*>(draw);
+    if (d->dpy != dpy)
+        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
+
+    // post the surface
+    d->setSwapRectangle(left, top, width, height);
+
+    return EGL_TRUE;
+}
+
+EGLClientBuffer eglGetRenderBufferANDROID(EGLDisplay dpy, EGLSurface draw)
+{
+    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
+        return setError(EGL_BAD_DISPLAY, (EGLClientBuffer)0);
+
+    egl_surface_t* d = static_cast<egl_surface_t*>(draw);
+    if (d->dpy != dpy)
+        return setError(EGL_BAD_DISPLAY, (EGLClientBuffer)0);
+
+    // post the surface
+    return d->getRenderBuffer();
+}
diff --git a/opengl/libagl/primitives.cpp b/opengl/libagl/primitives.cpp
index f164c02..769ec40 100644
--- a/opengl/libagl/primitives.cpp
+++ b/opengl/libagl/primitives.cpp
@@ -369,7 +369,7 @@
         int32_t c0, int32_t c1, int32_t c2) const
 {
     int64_t it64[3];
-    iterators0032(it, c0, c1, c2);
+    iterators0032(it64, c0, c1, c2);
     it[0] = it64[0];
     it[1] = it64[1];
     it[2] = it64[2];
diff --git a/opengl/libagl/state.cpp b/opengl/libagl/state.cpp
index 5cbabea..a59b3b0 100644
--- a/opengl/libagl/state.cpp
+++ b/opengl/libagl/state.cpp
@@ -2,16 +2,16 @@
 **
 ** Copyright 2006, 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 
+** 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 
+**     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 
+** 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.
 */
 
@@ -28,12 +28,16 @@
 #include "BufferObjectManager.h"
 #include "TextureObjectManager.h"
 
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+#include <hardware/copybit.h>
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
+
 namespace android {
 
 // ----------------------------------------------------------------------------
 
 static char const * const gVendorString     = "Android";
-static char const * const gRendererString   = "Android PixelFlinger 1.0";
+static char const * const gRendererString   = "Android PixelFlinger 1.1";
 static char const * const gVersionString    = "OpenGL ES-CM 1.0";
 static char const * const gExtensionsString =
     "GL_OES_byte_coordinates "              // OK
@@ -46,9 +50,9 @@
     "GL_OES_query_matrix "                  // OK
     //        "GL_OES_point_size_array "              // TODO
     //        "GL_OES_point_sprite "                  // TODO
+    "GL_OES_EGL_image "                     // OK
     "GL_ARB_texture_compression "           // OK
     "GL_ARB_texture_non_power_of_two "      // OK
-    "GL_ANDROID_direct_texture "            // OK
     "GL_ANDROID_user_clip_plane "           // OK
     "GL_ANDROID_vertex_buffer_object "      // OK
     "GL_ANDROID_generate_mipmap "           // OK
@@ -62,13 +66,13 @@
 ogles_context_t *ogles_init(size_t extra)
 {
     void* const base = malloc(extra + sizeof(ogles_context_t) + 32);
-	if (!base) return 0;
+    if (!base) return 0;
 
     ogles_context_t *c =
             (ogles_context_t *)((ptrdiff_t(base) + extra + 31) & ~0x1FL);
     memset(c, 0, sizeof(ogles_context_t));
     ggl_init_context(&(c->rasterizer));
-    
+
     // XXX: this should be passed as an argument
     sp<EGLSurfaceManager> smgr(new EGLSurfaceManager());
     c->surfaceManager = smgr.get();
@@ -87,13 +91,42 @@
     c->rasterizer.base = base;
     c->point.size = TRI_ONE;
     c->line.width = TRI_ONE;
-            
+
     // in OpenGL, writing to the depth buffer is enabled by default.
     c->rasterizer.procs.depthMask(c, 1);
-    
+
     // OpenGL enables dithering by default
     c->rasterizer.procs.enable(c, GL_DITHER);
 
+    c->copybits.blitEngine = NULL;
+    c->copybits.minScale = 0;
+    c->copybits.maxScale = 0;
+    c->copybits.drawSurfaceBuffer = 0;
+
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+    hw_module_t const* module;
+    if (hw_get_module(COPYBIT_HARDWARE_MODULE_ID, &module) == 0) {
+        struct copybit_device_t* copyBits;
+        if (copybit_open(module, &copyBits) == 0) {
+            c->copybits.blitEngine = copyBits;
+            {
+                int minLim = copyBits->get(copyBits,
+                        COPYBIT_MINIFICATION_LIMIT);
+                if (minLim != -EINVAL && minLim > 0) {
+                    c->copybits.minScale = (1 << 16) / minLim;
+                }
+            }
+            {
+                int magLim = copyBits->get(copyBits,
+                        COPYBIT_MAGNIFICATION_LIMIT);
+                if (magLim != -EINVAL && magLim > 0) {
+                    c->copybits.maxScale = min(32*1024-1, magLim) << 16;
+                }
+            }
+        }
+    }
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
+
     return c;
 }
 
@@ -107,7 +140,12 @@
     c->surfaceManager->decStrong(c);
     c->bufferObjectManager->decStrong(c);
     ggl_uninit_context(&(c->rasterizer));
-	free(c->rasterizer.base);
+    free(c->rasterizer.base);
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+    if (c->copybits.blitEngine != NULL) {
+        copybit_close((struct copybit_device_t*) c->copybits.blitEngine);
+    }
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
 }
 
 void _ogles_error(ogles_context_t* c, GLenum error)
@@ -188,7 +226,7 @@
         // these need to fall through into the rasterizer
         c->rasterizer.procs.enableDisable(c, cap, enabled);
         break;
-        
+
     case GL_MULTISAMPLE:
     case GL_SAMPLE_ALPHA_TO_COVERAGE:
     case GL_SAMPLE_ALPHA_TO_ONE:
@@ -281,7 +319,7 @@
     case GL_LINE_SMOOTH_HINT:
         break;
     case GL_POINT_SMOOTH_HINT:
-        c->rasterizer.procs.enableDisable(c, 
+        c->rasterizer.procs.enableDisable(c,
                 GGL_POINT_SMOOTH_NICE, mode==GL_NICEST);
         break;
     case GL_PERSPECTIVE_CORRECTION_HINT:
@@ -323,7 +361,7 @@
         c->error = 0;
         return ret;
     }
-    
+
     if (c->rasterizer.error) {
         const GLenum ret(c->rasterizer.error);
         c->rasterizer.error = 0;
@@ -362,25 +400,25 @@
         int index = c->rasterizer.state.buffers.color.format;
         GGLFormat const * formats = gglGetPixelFormatTable();
         params[0] = formats[index].ah - formats[index].al;
-        break; 
+        break;
         }
     case GL_RED_BITS: {
         int index = c->rasterizer.state.buffers.color.format;
         GGLFormat const * formats = gglGetPixelFormatTable();
         params[0] = formats[index].rh - formats[index].rl;
-        break; 
+        break;
         }
     case GL_GREEN_BITS: {
         int index = c->rasterizer.state.buffers.color.format;
         GGLFormat const * formats = gglGetPixelFormatTable();
         params[0] = formats[index].gh - formats[index].gl;
-        break; 
+        break;
         }
     case GL_BLUE_BITS: {
         int index = c->rasterizer.state.buffers.color.format;
         GGLFormat const * formats = gglGetPixelFormatTable();
         params[0] = formats[index].bh - formats[index].bl;
-        break; 
+        break;
         }
     case GL_COMPRESSED_TEXTURE_FORMATS:
         params[ 0] = GL_PALETTE4_RGB8_OES;
diff --git a/opengl/libagl/texture.cpp b/opengl/libagl/texture.cpp
index 14a910c..4d3c2f4 100644
--- a/opengl/libagl/texture.cpp
+++ b/opengl/libagl/texture.cpp
@@ -2,16 +2,16 @@
 **
 ** Copyright 2006, 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 
+** 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 
+**     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 
+** 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.
 */
 
@@ -23,6 +23,12 @@
 #include "texture.h"
 #include "TextureObjectManager.h"
 
+#include <private/ui/android_natives_priv.h>
+
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+#include "copybit.h"
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
+
 namespace android {
 
 // ----------------------------------------------------------------------------
@@ -48,7 +54,7 @@
     // each context has a default named (0) texture (not shared)
     c->textures.defaultTexture = new EGLTextureObject();
     c->textures.defaultTexture->incStrong(c);
-    
+
     // bind the default texture to each texture unit
     for (int i=0; i<GGL_TEXTURE_UNIT_COUNT ; i++) {
         bindTextureTmu(c, i, 0, c->textures.defaultTexture);
@@ -96,7 +102,7 @@
     }
 }
 
-void ogles_validate_texture_impl(ogles_context_t* c)
+void ogles_validate_texture(ogles_context_t* c)
 {
     for (int i=0 ; i<GGL_TEXTURE_UNIT_COUNT ; i++) {
         if (c->rasterizer.state.texture[i].enable)
@@ -110,6 +116,66 @@
     c->textures.tmu[tmu].dirty = flags;
 }
 
+/*
+ * If the active textures are EGLImage, they need to be locked before
+ * they can be used. 
+ * 
+ * FIXME: code below is far from being optimal
+ * 
+ */
+
+void ogles_lock_textures(ogles_context_t* c)
+{
+    for (int i=0 ; i<GGL_TEXTURE_UNIT_COUNT ; i++) {
+        if (c->rasterizer.state.texture[i].enable) {
+            texture_unit_t& u(c->textures.tmu[i]);
+            android_native_buffer_t* native_buffer = u.texture->buffer;
+            if (native_buffer) {
+                c->rasterizer.procs.activeTexture(c, i);
+                hw_module_t const* pModule;
+                if (hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &pModule))
+                    continue;
+
+                gralloc_module_t const* module =
+                    reinterpret_cast<gralloc_module_t const*>(pModule);
+
+                void* vaddr;
+                int err = module->lock(module, native_buffer->handle,
+                        GRALLOC_USAGE_SW_READ_OFTEN,
+                        0, 0, native_buffer->width, native_buffer->height,
+                        &vaddr);
+
+                u.texture->setImageBits(vaddr);
+                c->rasterizer.procs.bindTexture(c, &(u.texture->surface));
+            }
+        }
+    }
+}
+
+void ogles_unlock_textures(ogles_context_t* c)
+{
+    for (int i=0 ; i<GGL_TEXTURE_UNIT_COUNT ; i++) {
+        if (c->rasterizer.state.texture[i].enable) {
+            texture_unit_t& u(c->textures.tmu[i]);
+            android_native_buffer_t* native_buffer = u.texture->buffer;
+            if (native_buffer) {
+                c->rasterizer.procs.activeTexture(c, i);
+                hw_module_t const* pModule;
+                if (hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &pModule))
+                    continue;
+
+                gralloc_module_t const* module =
+                    reinterpret_cast<gralloc_module_t const*>(pModule);
+
+                module->unlock(module, native_buffer->handle);
+                u.texture->setImageBits(NULL);
+                c->rasterizer.procs.bindTexture(c, &(u.texture->surface));
+            }
+        }
+    }
+    c->rasterizer.procs.activeTexture(c, c->textures.active);
+}
+
 // ----------------------------------------------------------------------------
 #if 0
 #pragma mark -
@@ -255,7 +321,7 @@
         u.texture->decStrong(c);
 
     if (name == 0) {
-        // 0 is our local texture object, not shared with anyone. 
+        // 0 is our local texture object, not shared with anyone.
         // But it affects all bound TMUs immediately.
         // (we need to invalidate all units bound to this texture object)
         tex = c->textures.defaultTexture;
@@ -273,7 +339,7 @@
     u.texture = tex.get();
     u.texture->incStrong(c);
     u.name = name;
-    invalidate_texture(c, active);    
+    invalidate_texture(c, active);
     return tex;
 }
 
@@ -282,7 +348,7 @@
 {
     if (tex.get() == c->textures.tmu[tmu].texture)
         return;
-    
+
     // free the reference to the previously bound object
     texture_unit_t& u(c->textures.tmu[tmu]);
     if (u.texture)
@@ -310,7 +376,7 @@
     if (formatIdx == 0) { // we don't know what to do with this
         return GL_INVALID_OPERATION;
     }
-    
+
     // figure out the size we need as well as the stride
     const GGLFormat& pixelFormat(c->rasterizer.formats[formatIdx]);
     const int32_t align = c->textures.unpackAlignment-1;
@@ -530,8 +596,8 @@
         ogles_error(c, GL_INVALID_ENUM);
         return;
     }
-    
-    EGLTextureObject* textureObject = c->textures.tmu[c->textures.active].texture;    
+
+    EGLTextureObject* textureObject = c->textures.tmu[c->textures.active].texture;
     switch (pname) {
     case GL_TEXTURE_WRAP_S:
         if ((param == GL_REPEAT) ||
@@ -581,13 +647,12 @@
 }
 
 
-static void drawTexxOES(GLfixed x, GLfixed y, GLfixed z, GLfixed w, GLfixed h,
+
+static void drawTexxOESImp(GLfixed x, GLfixed y, GLfixed z, GLfixed w, GLfixed h,
         ogles_context_t* c)
 {
-    // quickly reject empty rects
-    if ((w|h) <= 0)
-        return;                
-
+    ogles_lock_textures(c);
+    
     const GGLSurface& cbSurface = c->rasterizer.state.buffers.color.s;
     y = gglIntToFixed(cbSurface.height) - (y + h);
     w >>= FIXED_BITS;
@@ -610,7 +675,7 @@
                 GGL_TEXTURE_2D, GGL_TEXTURE_WRAP_T, GGL_CLAMP);
         u.dirty = 0xFF; // XXX: should be more subtle
 
-        EGLTextureObject* textureObject = u.texture;  
+        EGLTextureObject* textureObject = u.texture;
         const GLint Ucr = textureObject->crop_rect[0] << 16;
         const GLint Vcr = textureObject->crop_rect[1] << 16;
         const GLint Wcr = textureObject->crop_rect[2] << 16;
@@ -641,11 +706,30 @@
     c->rasterizer.procs.disable(c, GGL_W_LERP);
     c->rasterizer.procs.disable(c, GGL_AA);
     c->rasterizer.procs.shadeModel(c, GL_FLAT);
-    c->rasterizer.procs.recti(c, 
+    c->rasterizer.procs.recti(c,
             gglFixedToIntRound(x),
             gglFixedToIntRound(y),
             gglFixedToIntRound(x)+w,
             gglFixedToIntRound(y)+h);
+
+    ogles_unlock_textures(c);
+}
+
+static void drawTexxOES(GLfixed x, GLfixed y, GLfixed z, GLfixed w, GLfixed h,
+        ogles_context_t* c)
+{
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+    if (drawTexiOESWithCopybit(gglFixedToIntRound(x),
+            gglFixedToIntRound(y), gglFixedToIntRound(z),
+            gglFixedToIntRound(w), gglFixedToIntRound(h), c)) {
+        return;
+    }
+#else
+    // quickly reject empty rects
+    if ((w|h) <= 0)
+        return;
+#endif
+    drawTexxOESImp(x, y, z, w, h, c);
 }
 
 static void drawTexiOES(GLint x, GLint y, GLint z, GLint w, GLint h, ogles_context_t* c)
@@ -656,14 +740,21 @@
     // which is a lot faster.
 
     if (ggl_likely(c->rasterizer.state.enabled_tmu == 1)) {
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+        if (drawTexiOESWithCopybit(x, y, z, w, h, c)) {
+            return;
+        }
+#endif
         const int tmu = 0;
         texture_unit_t& u(c->textures.tmu[tmu]);
-        EGLTextureObject* textureObject = u.texture;  
+        EGLTextureObject* textureObject = u.texture;
         const GLint Wcr = textureObject->crop_rect[2];
         const GLint Hcr = textureObject->crop_rect[3];
 
         if ((w == Wcr) && (h == -Hcr)) {
+#ifndef LIBAGL_USE_GRALLOC_COPYBITS
             if ((w|h) <= 0) return; // quickly reject empty rects
+#endif
 
             if (u.dirty) {
                 c->rasterizer.procs.activeTexture(c, tmu);
@@ -679,14 +770,14 @@
                     GGL_TEXTURE_GEN_MODE, GGL_ONE_TO_ONE);
             u.dirty = 0xFF; // XXX: should be more subtle
             c->rasterizer.procs.activeTexture(c, c->textures.active);
-            
+
             const GGLSurface& cbSurface = c->rasterizer.state.buffers.color.s;
             y = cbSurface.height - (y + h);
             const GLint Ucr = textureObject->crop_rect[0];
             const GLint Vcr = textureObject->crop_rect[1];
             const GLint s0  = Ucr - x;
             const GLint t0  = (Vcr + Hcr) - y;
-            
+
             const GLuint tw = textureObject->surface.width;
             const GLuint th = textureObject->surface.height;
             if ((uint32_t(s0+x+w) > tw) || (uint32_t(t0+y+h) > th)) {
@@ -694,7 +785,9 @@
                 // in this case, so we just use the slow case, which
                 // at least won't crash
                 goto slow_case;
-            } 
+            }
+
+            ogles_lock_textures(c);
 
             c->rasterizer.procs.texCoord2i(c, s0, t0);
             const uint32_t enables = c->rasterizer.state.enables;
@@ -706,12 +799,15 @@
             c->rasterizer.procs.disable(c, GGL_AA);
             c->rasterizer.procs.shadeModel(c, GL_FLAT);
             c->rasterizer.procs.recti(c, x, y, x+w, y+h);
+            
+            ogles_unlock_textures(c);
+
             return;
         }
     }
 
 slow_case:
-    drawTexxOES(
+    drawTexxOESImp(
             gglIntToFixed(x), gglIntToFixed(y), gglIntToFixed(z),
             gglIntToFixed(w), gglIntToFixed(h),
             c);
@@ -749,7 +845,7 @@
     }
 
     // Bind or create a texture
-    sp<EGLTextureObject> tex;    
+    sp<EGLTextureObject> tex;
     if (texture == 0) {
         // 0 is our local texture object
         tex = c->textures.defaultTexture;
@@ -837,7 +933,7 @@
     if ((pname != GL_PACK_ALIGNMENT) && (pname != GL_UNPACK_ALIGNMENT)) {
         ogles_error(c, GL_INVALID_ENUM);
         return;
-    }    
+    }
     if ((param<=0 || param>8) || (param & (param-1))) {
         ogles_error(c, GL_INVALID_VALUE);
         return;
@@ -952,7 +1048,7 @@
     }
 
     // "uncompress" the texture since pixelflinger doesn't support
-    // any compressed texture format natively. 
+    // any compressed texture format natively.
     GLenum format;
     GLenum type;
     switch (internalformat) {
@@ -1016,7 +1112,7 @@
         GLenum format, GLenum type, const GLvoid *pixels)
 {
     ogles_context_t* c = ogles_context_t::get();
-    if (target != GL_TEXTURE_2D && target != GL_DIRECT_TEXTURE_2D_QUALCOMM) {
+    if (target != GL_TEXTURE_2D) {
         ogles_error(c, GL_INVALID_ENUM);
         return;
     }
@@ -1024,7 +1120,7 @@
         ogles_error(c, GL_INVALID_VALUE);
         return;
     }
-    if (format != internalformat) {
+    if (format != (GLenum)internalformat) {
         ogles_error(c, GL_INVALID_OPERATION);
         return;
     }
@@ -1034,16 +1130,10 @@
 
     int32_t size = 0;
     GGLSurface* surface = 0;
-    if (target != GL_DIRECT_TEXTURE_2D_QUALCOMM) {
-        int error = createTextureSurface(c, &surface, &size,
-                level, format, type, width, height);
-        if (error) {
-            ogles_error(c, error);
-            return;
-        }
-    } else if (pixels == 0 || level != 0) {
-        // pixel can't be null for direct texture
-        ogles_error(c, GL_INVALID_OPERATION);
+    int error = createTextureSurface(c, &surface, &size,
+            level, format, type, width, height);
+    if (error) {
+        ogles_error(c, error);
         return;
     }
 
@@ -1064,18 +1154,12 @@
         userSurface.compressedFormat = 0;
         userSurface.data = (GLubyte*)pixels;
 
-        if (target != GL_DIRECT_TEXTURE_2D_QUALCOMM) {
-            int err = copyPixels(c, *surface, 0, 0, userSurface, 0, 0, width, height); 
-            if (err) {
-                ogles_error(c, err);
-                return;
-            }
-            generateMipmap(c, level);
-        } else {
-            // bind it to the texture unit
-            sp<EGLTextureObject> tex = getAndBindActiveTextureObject(c);
-            tex->setSurface(&userSurface);
+        int err = copyPixels(c, *surface, 0, 0, userSurface, 0, 0, width, height);
+        if (err) {
+            ogles_error(c, err);
+            return;
         }
+        generateMipmap(c, level);
     }
 }
 
@@ -1150,7 +1234,7 @@
 
     int err = copyPixels(c,
             surface, xoffset, yoffset,
-            userSurface, 0, 0, width, height); 
+            userSurface, 0, 0, width, height);
     if (err) {
         ogles_error(c, err);
         return;
@@ -1203,7 +1287,7 @@
     case GL_LUMINANCE_ALPHA:
     case GL_LUMINANCE:
         type = GL_UNSIGNED_BYTE;
-        break;    
+        break;
     }
 
     // figure out the format to use for the new texture
@@ -1213,7 +1297,7 @@
     case GGL_PIXEL_FORMAT_RGBA_5551:
     case GGL_PIXEL_FORMAT_RGBA_4444:
         format = internalformat;
-        break;    
+        break;
     case GGL_PIXEL_FORMAT_RGBX_8888:
     case GGL_PIXEL_FORMAT_RGB_888:
     case GGL_PIXEL_FORMAT_RGB_565:
@@ -1222,7 +1306,7 @@
         case GL_LUMINANCE:
         case GL_RGB:
             format = internalformat;
-            break;    
+            break;
         }
         break;
     }
@@ -1242,7 +1326,7 @@
         ogles_error(c, error);
         return;
     }
-    
+
     // The bottom row is stored first in textures
     GGLSurface txSurface(*surface);
     txSurface.stride = -txSurface.stride;
@@ -1252,7 +1336,7 @@
 
     int err = copyPixels(c,
             txSurface, 0, 0,
-            cbSurface, x, y, cbSurface.width, cbSurface.height);  
+            cbSurface, x, y, cbSurface.width, cbSurface.height);
     if (err) {
         ogles_error(c, err);
     }
@@ -1302,7 +1386,7 @@
 
     int err = copyPixels(c,
             surface, xoffset, yoffset,
-            cbSurface, x, y, width, height);  
+            cbSurface, x, y, width, height);
     if (err) {
         ogles_error(c, err);
         return;
@@ -1372,7 +1456,7 @@
         return;
     }
 
-    ggl->colorBuffer(ggl, &userSurface);  // destination is user buffer 
+    ggl->colorBuffer(ggl, &userSurface);  // destination is user buffer
     ggl->bindTexture(ggl, &readSurface);  // source is read-buffer
     ggl->texCoord2i(ggl, x, readSurface.height - (y + height));
     ggl->recti(ggl, 0, 0, width, height);
@@ -1426,3 +1510,43 @@
     ogles_context_t* c = ogles_context_t::get();
     drawTexxOES(x, y, z, w, h, c);
 }
+
+// ----------------------------------------------------------------------------
+#if 0
+#pragma mark -
+#pragma mark EGL Image Extension
+#endif
+
+void glEGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image)
+{
+    ogles_context_t* c = ogles_context_t::get();
+    if (target != GL_TEXTURE_2D) {
+        ogles_error(c, GL_INVALID_ENUM);
+        return;
+    }
+
+    android_native_buffer_t* native_buffer = (android_native_buffer_t*)image;
+    if (native_buffer->common.magic != ANDROID_NATIVE_BUFFER_MAGIC) {
+        ogles_error(c, GL_INVALID_VALUE);
+        return;
+    }
+    if (native_buffer->common.version != sizeof(android_native_buffer_t)) {
+        ogles_error(c, GL_INVALID_VALUE);
+        return;
+    }
+
+    // bind it to the texture unit
+    sp<EGLTextureObject> tex = getAndBindActiveTextureObject(c);
+    tex->setImage(native_buffer);
+
+#ifdef LIBAGL_USE_GRALLOC_COPYBITS
+    tex->try_copybit = false;
+    if (c->copybits.blitEngine != NULL) {
+        tex->try_copybit = true;
+    }
+#endif // LIBAGL_USE_GRALLOC_COPYBITS
+}
+
+void glEGLImageTargetRenderbufferStorageOES(GLenum target, GLeglImageOES image)
+{
+}
diff --git a/opengl/libagl/texture.h b/opengl/libagl/texture.h
index 5c57948..98f7550 100644
--- a/opengl/libagl/texture.h
+++ b/opengl/libagl/texture.h
@@ -32,13 +32,9 @@
 
 void ogles_init_texture(ogles_context_t* c);
 void ogles_uninit_texture(ogles_context_t* c);
-void ogles_validate_texture_impl(ogles_context_t* c);
-
-inline void ogles_validate_texture(ogles_context_t* c) {
-    if (c->rasterizer.state.enables & GGL_ENABLE_TMUS)
-        ogles_validate_texture_impl(c);
-}
-
+void ogles_validate_texture(ogles_context_t* c);
+void ogles_lock_textures(ogles_context_t* c);
+void ogles_unlock_textures(ogles_context_t* c);
 
 }; // namespace android
 
diff --git a/opengl/libs/Android.mk b/opengl/libs/Android.mk
index 23304d5..e1fd48b 100644
--- a/opengl/libs/Android.mk
+++ b/opengl/libs/Android.mk
@@ -1,17 +1,18 @@
 LOCAL_PATH:= $(call my-dir)
 
-#
+###############################################################################
 # Build META EGL library
 #
 
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= 	\
-	EGL/egl.cpp 		\
-	EGL/gpu.cpp			\
+	EGL/egl.cpp 	\
+	EGL/hooks.cpp 	\
+	EGL/Loader.cpp 	\
 #
 
-LOCAL_SHARED_LIBRARIES += libcutils libutils libui
+LOCAL_SHARED_LIBRARIES += libcutils libutils
 LOCAL_LDLIBS := -lpthread -ldl
 LOCAL_MODULE:= libEGL
 
@@ -19,24 +20,42 @@
 ifeq ($(TARGET_SIMULATOR),true)
 else
     LOCAL_SHARED_LIBRARIES += libdl
-    # we need to access the Bionic private header <bionic_tls.h>
-    LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../bionic/libc/private
+    # we need to access the private Bionic header <bionic_tls.h>
+    LOCAL_C_INCLUDES += bionic/libc/private
 endif
 
+LOCAL_CFLAGS += -DLOG_TAG=\"libEGL\"
+LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
 LOCAL_CFLAGS += -fvisibility=hidden
 
 include $(BUILD_SHARED_LIBRARY)
+installed_libEGL := $(LOCAL_INSTALLED_MODULE)
 
 
+# OpenGL drivers config file
+ifneq ($(BOARD_EGL_CFG),)
 
-#
-# Build the wrapper OpenGL ES library
+include $(CLEAR_VARS)
+LOCAL_MODULE := egl.cfg
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_CLASS := ETC
+LOCAL_MODULE_PATH := $(TARGET_OUT)/lib/egl
+LOCAL_SRC_FILES := ../../../../$(BOARD_EGL_CFG)
+include $(BUILD_PREBUILT)
+
+# make sure we depend on egl.cfg, so it gets installed
+$(installed_libEGL): | egl.cfg
+
+endif
+
+###############################################################################
+# Build the wrapper OpenGL ES 1.x library
 #
 
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:= 	\
-	GLES_CM/gl.cpp.arm 		\
+LOCAL_SRC_FILES:= 		\
+	GLES_CM/gl.cpp.arm 	\
 #
 
 LOCAL_SHARED_LIBRARIES += libcutils libEGL
@@ -47,10 +66,41 @@
 ifeq ($(TARGET_SIMULATOR),true)
 else
     LOCAL_SHARED_LIBRARIES += libdl
-    # we need to access the Bionic private header <bionic_tls.h>
-    LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../bionic/libc/private
+    # we need to access the private Bionic header <bionic_tls.h>
+    LOCAL_C_INCLUDES += bionic/libc/private
 endif
 
+LOCAL_CFLAGS += -DLOG_TAG=\"libGLESv1\"
+LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+LOCAL_CFLAGS += -fvisibility=hidden
+
+include $(BUILD_SHARED_LIBRARY)
+
+
+###############################################################################
+# Build the wrapper OpenGL ES 2.x library
+#
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= 		\
+	GLES2/gl2.cpp.arm 	\
+#
+
+LOCAL_SHARED_LIBRARIES += libcutils libEGL
+LOCAL_LDLIBS := -lpthread -ldl
+LOCAL_MODULE:= libGLESv2
+
+# needed on sim build because of weird logging issues
+ifeq ($(TARGET_SIMULATOR),true)
+else
+    LOCAL_SHARED_LIBRARIES += libdl
+    # we need to access the private Bionic header <bionic_tls.h>
+    LOCAL_C_INCLUDES += bionic/libc/private
+endif
+
+LOCAL_CFLAGS += -DLOG_TAG=\"libGLESv2\"
+LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
 LOCAL_CFLAGS += -fvisibility=hidden
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/opengl/libs/EGL/Loader.cpp b/opengl/libs/EGL/Loader.cpp
new file mode 100644
index 0000000..7f3f114
--- /dev/null
+++ b/opengl/libs/EGL/Loader.cpp
@@ -0,0 +1,276 @@
+/* 
+ ** Copyright 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.
+ */
+
+#include <ctype.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <dlfcn.h>
+#include <limits.h>
+
+#include <cutils/log.h>
+
+#include <EGL/egl.h>
+
+#include "hooks.h"
+#include "egl_impl.h"
+
+#include "Loader.h"
+
+// ----------------------------------------------------------------------------
+namespace android {
+// ----------------------------------------------------------------------------
+
+
+/*
+ * EGL drivers are called
+ * 
+ * /system/lib/egl/lib{[EGL|GLESv1_CM|GLESv2] | GLES}_$TAG.so 
+ * 
+ */
+
+ANDROID_SINGLETON_STATIC_INSTANCE( Loader )
+
+// ----------------------------------------------------------------------------
+
+Loader::driver_t::driver_t(void* gles) 
+{
+    dso[0] = gles;
+    for (size_t i=1 ; i<NELEM(dso) ; i++)
+        dso[i] = 0;
+}
+
+Loader::driver_t::~driver_t() 
+{
+    for (size_t i=0 ; i<NELEM(dso) ; i++) {
+        if (dso[i]) {
+            dlclose(dso[i]);
+            dso[i] = 0;
+        }
+    }
+}
+
+status_t Loader::driver_t::set(void* hnd, int32_t api)
+{
+    switch (api) {
+        case EGL:
+            dso[0] = hnd;
+            break;
+        case GLESv1_CM:
+            dso[1] = hnd;
+            break;
+        case GLESv2:
+            dso[2] = hnd;
+            break;
+        default:
+            return BAD_INDEX;
+    }
+    return NO_ERROR;
+}
+
+// ----------------------------------------------------------------------------
+
+Loader::entry_t::entry_t(int dpy, int impl, const char* tag)
+    : dpy(dpy), impl(impl), tag(tag) {
+}
+
+// ----------------------------------------------------------------------------
+
+Loader::Loader()
+{
+    char line[256];
+    char tag[256];
+    FILE* cfg = fopen("/system/lib/egl/egl.cfg", "r");
+    if (cfg == NULL) {
+        // default config
+        LOGD("egl.cfg not found, using default config");
+        gConfig.add( entry_t(0, 0, "android") );
+    } else {
+        while (fgets(line, 256, cfg)) {
+            int dpy;
+            int impl;
+            if (sscanf(line, "%u %u %s", &dpy, &impl, tag) == 3) {
+                //LOGD(">>> %u %u %s", dpy, impl, tag);
+                gConfig.add( entry_t(dpy, impl, tag) );
+            }
+        }
+        fclose(cfg);
+    }
+}
+
+Loader::~Loader()
+{
+}
+
+const char* Loader::getTag(int dpy, int impl)
+{
+    const Vector<entry_t>& cfgs(gConfig);    
+    const size_t c = cfgs.size();
+    for (size_t i=0 ; i<c ; i++) {
+        if (dpy == cfgs[i].dpy)
+            if (impl == cfgs[i].impl)
+                return cfgs[i].tag.string();
+    }
+    return 0;
+}
+
+void* Loader::open(EGLNativeDisplayType display, int impl, gl_hooks_t* hooks)
+{
+    /*
+     * TODO: if we don't find display/0, then use 0/0
+     * (0/0 should always work)
+     */
+    
+    void* dso;
+    char path[PATH_MAX];
+    int index = int(display);
+    driver_t* hnd = 0;
+    const char* const format = "/system/lib/egl/lib%s_%s.so";
+    
+    char const* tag = getTag(index, impl);
+    if (tag) {
+        snprintf(path, PATH_MAX, format, "GLES", tag);
+        dso = load_driver(path, hooks, EGL | GLESv1_CM | GLESv2);
+        if (dso) {
+            hnd = new driver_t(dso);
+        } else {
+            // Always load EGL first
+            snprintf(path, PATH_MAX, "lib%s_%s.so", "EGL", tag);
+            dso = load_driver(path, hooks, EGL);
+            if (dso) {
+                hnd = new driver_t(dso);
+
+                // TODO: make this more automated
+                snprintf(path, PATH_MAX, format, "GLESv1_CM", tag);
+                hnd->set( load_driver(path, hooks, GLESv1_CM), GLESv1_CM );
+
+                snprintf(path, PATH_MAX, format, "GLESv2", tag);
+                hnd->set( load_driver(path, hooks, GLESv2), GLESv2 );
+            }
+        }
+    }
+
+    LOG_FATAL_IF(!index && !impl && !hnd, 
+            "couldn't find the default OpenGL ES implementation "
+            "for default display");
+    
+    return (void*)hnd;
+}
+
+status_t Loader::close(void* driver)
+{
+    driver_t* hnd = (driver_t*)driver;
+    delete hnd;
+    return NO_ERROR;
+}
+
+void Loader::init_api(void* dso, 
+        char const * const * api, 
+        __eglMustCastToProperFunctionPointerType* curr, 
+        getProcAddressType getProcAddress) 
+{
+    char scrap[256];
+    while (*api) {
+        char const * name = *api;
+        __eglMustCastToProperFunctionPointerType f = 
+            (__eglMustCastToProperFunctionPointerType)dlsym(dso, name);
+        if (f == NULL) {
+            // couldn't find the entry-point, use eglGetProcAddress()
+            f = getProcAddress(name);
+        }
+        if (f == NULL) {
+            // Try without the OES postfix
+            ssize_t index = ssize_t(strlen(name)) - 3;
+            if ((index>0 && (index<255)) && (!strcmp(name+index, "OES"))) {
+                strncpy(scrap, name, index);
+                scrap[index] = 0;
+                f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap);
+                //LOGD_IF(f, "found <%s> instead", scrap);
+            }
+        }
+        if (f == NULL) {
+            // Try with the OES postfix
+            ssize_t index = ssize_t(strlen(name)) - 3;
+            if ((index>0 && (index<252)) && (strcmp(name+index, "OES"))) {
+                strncpy(scrap, name, index);
+                scrap[index] = 0;
+                strcat(scrap, "OES");
+                f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap);
+                //LOGD_IF(f, "found <%s> instead", scrap);
+            }
+        }
+        if (f == NULL) {
+            //LOGD("%s", name);
+            f = (__eglMustCastToProperFunctionPointerType)gl_unimplemented;
+        }
+        *curr++ = f;
+        api++;
+    }
+}
+
+void *Loader::load_driver(const char* driver, gl_hooks_t* hooks, uint32_t mask)
+{
+    //LOGD("%s", driver);
+    void* dso = dlopen(driver, RTLD_NOW | RTLD_LOCAL);
+    LOGE_IF(!dso, "%s", dlerror());
+    if (dso == 0)
+        return 0;
+
+    if (mask & EGL) {
+        getProcAddress = (getProcAddressType)dlsym(dso, "eglGetProcAddress");
+
+        LOGE_IF(!getProcAddress, 
+                "can't find eglGetProcAddress() in %s", driver);        
+
+        gl_hooks_t::egl_t* egl = &hooks->egl;
+        __eglMustCastToProperFunctionPointerType* curr =
+            (__eglMustCastToProperFunctionPointerType*)egl;
+        char const * const * api = egl_names;
+        while (*api) {
+            char const * name = *api;
+            __eglMustCastToProperFunctionPointerType f = 
+                (__eglMustCastToProperFunctionPointerType)dlsym(dso, name);
+            if (f == NULL) {
+                // couldn't find the entry-point, use eglGetProcAddress()
+                f = getProcAddress(name);
+                if (f == NULL) {
+                    f = (__eglMustCastToProperFunctionPointerType)0;
+                }
+            }
+            *curr++ = f;
+            api++;
+        }
+    }
+    
+    if (mask & GLESv1_CM) {
+        init_api(dso, gl_names,  
+                (__eglMustCastToProperFunctionPointerType*)&hooks->gl, 
+                getProcAddress);
+    }
+
+    if (mask & GLESv2) {
+      init_api(dso, gl2_names, 
+            (__eglMustCastToProperFunctionPointerType*)&hooks->gl2, 
+            getProcAddress);
+    }
+    
+    return dso;
+}
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+// ----------------------------------------------------------------------------
diff --git a/opengl/libs/EGL/Loader.h b/opengl/libs/EGL/Loader.h
new file mode 100644
index 0000000..69f6dd5
--- /dev/null
+++ b/opengl/libs/EGL/Loader.h
@@ -0,0 +1,90 @@
+/* 
+ ** Copyright 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.
+ */
+
+#ifndef ANDROID_EGL_LOADER_H
+#define ANDROID_EGL_LOADER_H
+
+#include <ctype.h>
+#include <string.h>
+#include <errno.h>
+
+#include <utils/Errors.h>
+#include <utils/Singleton.h>
+#include <utils/String8.h>
+#include <utils/Vector.h>
+
+#include <EGL/egl.h>
+
+// ----------------------------------------------------------------------------
+namespace android {
+// ----------------------------------------------------------------------------
+
+struct gl_hooks_t;
+
+class Loader : public Singleton<Loader>
+{
+    friend class Singleton<Loader>;
+
+    typedef __eglMustCastToProperFunctionPointerType (*getProcAddressType)(
+            const char*);
+   
+    enum {
+        EGL         = 0x01,
+        GLESv1_CM   = 0x02,
+        GLESv2      = 0x04
+    };
+    struct driver_t {
+        driver_t(void* gles);
+        ~driver_t();
+        status_t set(void* hnd, int32_t api);
+        void* dso[3];
+    };
+    
+    struct entry_t {
+        entry_t() { }
+        entry_t(int dpy, int impl, const char* tag);
+        int dpy;
+        int impl;
+        String8 tag;
+    };
+
+    Vector<entry_t> gConfig;    
+    getProcAddressType getProcAddress;
+    
+    const char* getTag(int dpy, int impl);
+
+public:
+    ~Loader();
+    
+    void* open(EGLNativeDisplayType display, int impl, gl_hooks_t* hooks);
+    status_t close(void* driver);
+    
+private:
+    Loader();
+    void *load_driver(const char* driver, gl_hooks_t* hooks, uint32_t mask);
+
+    static __attribute__((noinline))
+    void init_api(void* dso, 
+            char const * const * api, 
+            __eglMustCastToProperFunctionPointerType* curr, 
+            getProcAddressType getProcAddress); 
+};
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+// ----------------------------------------------------------------------------
+
+#endif /* ANDROID_EGL_LOADER_H */
diff --git a/opengl/libs/EGL/egl.cpp b/opengl/libs/EGL/egl.cpp
index c6e0f50..c2003dd 100644
--- a/opengl/libs/EGL/egl.cpp
+++ b/opengl/libs/EGL/egl.cpp
@@ -14,9 +14,8 @@
  ** limitations under the License.
  */
 
-#define LOG_TAG "libEGL"
-
 #include <ctype.h>
+#include <stdlib.h>
 #include <string.h>
 #include <errno.h>
 #include <dlfcn.h>
@@ -37,11 +36,9 @@
 #include <cutils/properties.h>
 #include <cutils/memory.h>
 
-#include <utils/RefBase.h>
-
 #include "hooks.h"
 #include "egl_impl.h"
-
+#include "Loader.h"
 
 #define MAKE_CONFIG(_impl, _index)  ((EGLConfig)(((_impl)<<24) | (_index)))
 #define setError(_e, _r) setErrorEtc(__FUNCTION__, __LINE__, _e, _r)
@@ -55,7 +52,16 @@
 static char const * const gVendorString     = "Android";
 static char const * const gVersionString    = "1.31 Android META-EGL";
 static char const * const gClientApiString  = "OpenGL ES";
-static char const * const gExtensionString  = "";
+static char const * const gExtensionString  = 
+        "EGL_KHR_image "
+        "EGL_KHR_image_base "
+        "EGL_KHR_image_pixmap "
+        "EGL_ANDROID_image_native_buffer "
+        "EGL_ANDROID_swap_rectangle "
+        "EGL_ANDROID_get_render_buffer "
+        ;
+
+// ----------------------------------------------------------------------------
 
 template <int MAGIC>
 struct egl_object_t
@@ -87,21 +93,15 @@
 struct egl_surface_t : public egl_object_t<'_srf'>
 {
     egl_surface_t(EGLDisplay dpy, EGLSurface surface,
-            NativeWindowType window, int impl, egl_connection_t const* cnx) 
-    : dpy(dpy), surface(surface), window(window), impl(impl), cnx(cnx)
+            int impl, egl_connection_t const* cnx) 
+    : dpy(dpy), surface(surface), impl(impl), cnx(cnx)
     {
         // NOTE: window must be incRef'ed and connected already
     }
     ~egl_surface_t() {
-        if (window) {
-            if (window->disconnect)
-                window->disconnect(window);
-            window->decRef(window);
-        }
     }
     EGLDisplay                  dpy;
     EGLSurface                  surface;
-    NativeWindowType            window;
     int                         impl;
     egl_connection_t const*     cnx;
 };
@@ -121,6 +121,18 @@
     egl_connection_t const*     cnx;
 };
 
+struct egl_image_t : public egl_object_t<'_img'>
+{
+    egl_image_t(EGLDisplay dpy, EGLContext context)
+        : dpy(dpy), context(context)
+    {
+        memset(images, 0, sizeof(images));
+    }
+    EGLDisplay dpy;
+    EGLConfig context;
+    EGLImageKHR images[IMPL_NUM_DRIVERS_IMPLEMENTATIONS];
+};
+
 struct tls_t
 {
     tls_t() : error(EGL_SUCCESS), ctx(0) { }
@@ -128,32 +140,6 @@
     EGLContext  ctx;
 };
 
-static void gl_unimplemented() {
-    LOGE("called unimplemented OpenGL ES API");
-}
-
-// ----------------------------------------------------------------------------
-// GL / EGL hooks
-// ----------------------------------------------------------------------------
-
-#undef GL_ENTRY
-#undef EGL_ENTRY
-#define GL_ENTRY(_r, _api, ...) #_api,
-#define EGL_ENTRY(_r, _api, ...) #_api,
-
-static char const * const gl_names[] = {
-    #include "gl_entries.in"
-    #include "glext_entries.in"
-    NULL
-};
-
-static char const * const egl_names[] = {
-    #include "egl_entries.in"
-    NULL
-};
-
-#undef GL_ENTRY
-#undef EGL_ENTRY
 
 // ----------------------------------------------------------------------------
 
@@ -262,110 +248,8 @@
     return tls->ctx;
 }
 
-
 /*****************************************************************************/
 
-class ISurfaceComposer;
-const sp<ISurfaceComposer>& getSurfaceFlinger();
-request_gpu_t* gpu_acquire(void* user);
-int gpu_release(void*, request_gpu_t* gpu);
-
-static __attribute__((noinline))
-void *load_driver(const char* driver, gl_hooks_t* hooks)
-{
-    //LOGD("%s", driver);
-    char scrap[256];
-    void* dso = dlopen(driver, RTLD_NOW | RTLD_LOCAL);
-    LOGE_IF(!dso,
-            "couldn't load <%s> library (%s)",
-            driver, dlerror());
-
-    if (dso) {
-        // first find the symbol for eglGetProcAddress
-        
-        typedef __eglMustCastToProperFunctionPointerType (*getProcAddressType)(
-                const char*);
-        
-        getProcAddressType getProcAddress = 
-            (getProcAddressType)dlsym(dso, "eglGetProcAddress");
-        
-        LOGE_IF(!getProcAddress, 
-                "can't find eglGetProcAddress() in %s", driver);        
-        
-        __eglMustCastToProperFunctionPointerType* curr;
-        char const * const * api;
-
-        gl_hooks_t::egl_t* egl = &hooks->egl;
-        curr = (__eglMustCastToProperFunctionPointerType*)egl;
-        api = egl_names;
-        while (*api) {
-            char const * name = *api;
-            __eglMustCastToProperFunctionPointerType f = 
-                (__eglMustCastToProperFunctionPointerType)dlsym(dso, name);
-            if (f == NULL) {
-                // couldn't find the entry-point, use eglGetProcAddress()
-                f = getProcAddress(name);
-                if (f == NULL) {
-                    f = (__eglMustCastToProperFunctionPointerType)0;
-                }
-            }
-            *curr++ = f;
-            api++;
-        }
-
-        gl_hooks_t::gl_t* gl = &hooks->gl;
-        curr = (__eglMustCastToProperFunctionPointerType*)gl;
-        api = gl_names;
-        while (*api) {
-            char const * name = *api;
-            __eglMustCastToProperFunctionPointerType f = 
-                (__eglMustCastToProperFunctionPointerType)dlsym(dso, name);
-            if (f == NULL) {
-                // couldn't find the entry-point, use eglGetProcAddress()
-                f = getProcAddress(name);
-            }
-            if (f == NULL) {
-                // Try without the OES postfix
-                ssize_t index = ssize_t(strlen(name)) - 3;
-                if ((index>0 && (index<255)) && (!strcmp(name+index, "OES"))) {
-                    strncpy(scrap, name, index);
-                    scrap[index] = 0;
-                    f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap);
-                    //LOGD_IF(f, "found <%s> instead", scrap);
-                }
-            }
-            if (f == NULL) {
-                // Try with the OES postfix
-                ssize_t index = ssize_t(strlen(name)) - 3;
-                if ((index>0 && (index<252)) && (strcmp(name+index, "OES"))) {
-                    strncpy(scrap, name, index);
-                    scrap[index] = 0;
-                    strcat(scrap, "OES");
-                    f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap);
-                    //LOGD_IF(f, "found <%s> instead", scrap);
-                }
-            }
-            if (f == NULL) {
-                //LOGD("%s", name);
-                f = (__eglMustCastToProperFunctionPointerType)gl_unimplemented;
-            }
-            *curr++ = f;
-            api++;
-        }
-
-        // hook this driver up with surfaceflinger if needed
-        register_gpu_t register_gpu = 
-            (register_gpu_t)dlsym(dso, "oem_register_gpu");
-
-        if (register_gpu != NULL) {
-            if (getSurfaceFlinger() != 0) {
-                register_gpu(dso, gpu_acquire, gpu_release);
-            }
-        }
-    }
-    return dso;
-}
-
 template<typename T>
 static __attribute__((noinline))
 int binarySearch(
@@ -412,6 +296,18 @@
 };
 
 static const extention_map_t gExtentionMap[] = {
+    { "eglLockSurfaceKHR",  
+            (__eglMustCastToProperFunctionPointerType)&eglLockSurfaceKHR }, 
+    { "eglUnlockSurfaceKHR", 
+            (__eglMustCastToProperFunctionPointerType)&eglUnlockSurfaceKHR }, 
+    { "eglCreateImageKHR",  
+            (__eglMustCastToProperFunctionPointerType)&eglCreateImageKHR }, 
+    { "eglDestroyImageKHR", 
+            (__eglMustCastToProperFunctionPointerType)&eglDestroyImageKHR }, 
+    { "eglSetSwapRectangleANDROID", 
+            (__eglMustCastToProperFunctionPointerType)&eglSetSwapRectangleANDROID }, 
+    { "eglGetRenderBufferANDROID", 
+            (__eglMustCastToProperFunctionPointerType)&eglGetRenderBufferANDROID }, 
 };
 
 static extention_map_t gGLExtentionMap[MAX_NUMBER_OF_GL_EXTENSIONS];
@@ -429,6 +325,12 @@
 
 // ----------------------------------------------------------------------------
 
+/*
+ * To "loose" the GPU, use something like
+ *    gEGLImpl[IMPL_HARDWARE].hooks = &gHooks[IMPL_CONTEXT_LOST];
+ * 
+ */
+
 static int gl_context_lost() {
     setGlThreadSpecific(&gHooks[IMPL_CONTEXT_LOST]);
     return 0;
@@ -491,6 +393,11 @@
     return egl_to_native_cast<egl_context_t>(context);
 }
 
+static inline
+egl_image_t* get_image(EGLImageKHR image) {
+    return egl_to_native_cast<egl_image_t>(image);
+}
+
 static egl_connection_t* validate_display_config(
         EGLDisplay dpy, EGLConfig config,
         egl_display_t const*& dp, int& impl, int& index)
@@ -540,6 +447,24 @@
 }
 
 
+EGLImageKHR egl_get_image_for_current_context(EGLImageKHR image)
+{
+    EGLContext context = getContext();
+    if (context == EGL_NO_CONTEXT || image == EGL_NO_IMAGE_KHR)
+        return EGL_NO_IMAGE_KHR;
+    
+    egl_context_t const * const c = get_context(context);
+    if (!c->isValid())
+        return EGL_NO_IMAGE_KHR;
+
+    egl_image_t const * const i = get_image(image);
+    if (!i->isValid())
+        return EGL_NO_IMAGE_KHR;
+
+    return i->images[c->impl];
+}
+
+
 EGLDisplay egl_init_displays(NativeDisplayType display)
 {
     if (sEarlyInitState) {
@@ -554,12 +479,15 @@
     EGLDisplay dpy = EGLDisplay(uintptr_t(display) + 1LU);
     egl_display_t* d = &gDisplay[index];
 
+    // get our driver loader
+    Loader& loader(Loader::getInstance());    
+    
     // dynamically load all our EGL implementations for that display
     // and call into the real eglGetGisplay()
     egl_connection_t* cnx = &gEGLImpl[IMPL_SOFTWARE];
     if (cnx->dso == 0) {
         cnx->hooks = &gHooks[IMPL_SOFTWARE];
-        cnx->dso = load_driver("libagl.so", cnx->hooks);
+        cnx->dso = loader.open(display, 0, cnx->hooks);
     }
     if (cnx->dso && d->dpys[IMPL_SOFTWARE]==EGL_NO_DISPLAY) {
         d->dpys[IMPL_SOFTWARE] = cnx->hooks->egl.eglGetDisplay(display);
@@ -573,7 +501,7 @@
         property_get("debug.egl.hw", value, "1");
         if (atoi(value) != 0) {
             cnx->hooks = &gHooks[IMPL_HARDWARE];
-            cnx->dso = load_driver("libhgl.so", cnx->hooks);
+            cnx->dso = loader.open(display, 1, cnx->hooks);
         } else {
             LOGD("3D hardware acceleration is disabled");
         }
@@ -605,7 +533,8 @@
         if (d->dpys[IMPL_HARDWARE] == EGL_NO_DISPLAY) {
             LOGE("h/w accelerated eglGetDisplay() failed (%s)",
                     egl_strerror(cnx->hooks->egl.eglGetError()));
-            dlclose((void*)cnx->dso);
+            
+            loader.close(cnx->dso);
             cnx->dso = 0;
             // in case of failure, we want to make sure we don't try again
             // as it's expensive.
@@ -717,6 +646,8 @@
     if (android_atomic_dec(&dp->refs) != 1)
         return EGL_TRUE;
         
+    Loader& loader(Loader::getInstance());    
+
     EGLBoolean res = EGL_FALSE;
     for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
         egl_connection_t* const cnx = &gEGLImpl[i];
@@ -732,7 +663,8 @@
             free((void*)dp->queryString[i].extensions);
             dp->numConfigs[i] = 0;
             dp->dpys[i] = EGL_NO_DISPLAY;
-            dlclose((void*)cnx->dso);
+
+            loader.close(cnx->dso);
             cnx->dso = 0;
             res = EGL_TRUE;
         }
@@ -909,26 +841,12 @@
     int i=0, index=0;
     egl_connection_t* cnx = validate_display_config(dpy, config, dp, i, index);
     if (cnx) {
-        // window must be connected upon calling underlying
-        // eglCreateWindowSurface
-        if (window) {
-            window->incRef(window);
-            if (window->connect)
-                window->connect(window);
-        }
-
         EGLSurface surface = cnx->hooks->egl.eglCreateWindowSurface(
                 dp->dpys[i], dp->configs[i][index], window, attrib_list);       
         if (surface != EGL_NO_SURFACE) {
-            egl_surface_t* s = new egl_surface_t(dpy, surface, window, i, cnx);
+            egl_surface_t* s = new egl_surface_t(dpy, surface, i, cnx);
             return s;
         }
-        
-        // something went wrong, disconnect and free window
-        // (will disconnect() automatically)
-        if (window) {
-            window->decRef(window);
-        }        
     }
     return EGL_NO_SURFACE;
 }
@@ -944,7 +862,7 @@
         EGLSurface surface = cnx->hooks->egl.eglCreatePixmapSurface(
                 dp->dpys[i], dp->configs[i][index], pixmap, attrib_list);
         if (surface != EGL_NO_SURFACE) {
-            egl_surface_t* s = new egl_surface_t(dpy, surface, NULL, i, cnx);
+            egl_surface_t* s = new egl_surface_t(dpy, surface, i, cnx);
             return s;
         }
     }
@@ -961,7 +879,7 @@
         EGLSurface surface = cnx->hooks->egl.eglCreatePbufferSurface(
                 dp->dpys[i], dp->configs[i][index], attrib_list);
         if (surface != EGL_NO_SURFACE) {
-            egl_surface_t* s = new egl_surface_t(dpy, surface, NULL, i, cnx);
+            egl_surface_t* s = new egl_surface_t(dpy, surface, i, cnx);
             return s;
         }
     }
@@ -1430,3 +1348,156 @@
     }
     return setError(EGL_BAD_CONFIG, EGL_NO_SURFACE);
 }
+
+// ----------------------------------------------------------------------------
+// EGL_EGLEXT_VERSION 3
+// ----------------------------------------------------------------------------
+
+EGLBoolean eglLockSurfaceKHR(EGLDisplay dpy, EGLSurface surface,
+        const EGLint *attrib_list)
+{
+    EGLBoolean result = EGL_FALSE;
+    if (!validate_display_surface(dpy, surface))
+        return result;
+
+    egl_display_t const * const dp = get_display(dpy);
+    egl_surface_t const * const s = get_surface(surface);
+
+    if (s->cnx->hooks->egl.eglLockSurfaceKHR) {
+        result = s->cnx->hooks->egl.eglLockSurfaceKHR(
+                dp->dpys[s->impl], s->surface, attrib_list);
+    }
+    return result;
+}
+
+EGLBoolean eglUnlockSurfaceKHR(EGLDisplay dpy, EGLSurface surface)
+{
+    EGLBoolean result = EGL_FALSE;
+    if (!validate_display_surface(dpy, surface))
+        return result;
+
+    egl_display_t const * const dp = get_display(dpy);
+    egl_surface_t const * const s = get_surface(surface);
+
+    if (s->cnx->hooks->egl.eglUnlockSurfaceKHR) {
+        result = s->cnx->hooks->egl.eglUnlockSurfaceKHR(
+                dp->dpys[s->impl], s->surface);
+    }
+    return result;
+}
+
+EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target,
+        EGLClientBuffer buffer, const EGLint *attrib_list)
+{
+    if (ctx != EGL_NO_CONTEXT) {
+        if (!validate_display_context(dpy, ctx))
+            return EGL_NO_IMAGE_KHR;
+        egl_display_t const * const dp = get_display(dpy);
+        egl_context_t * const c = get_context(ctx);
+        // since we have an EGLContext, we know which implementation to use
+        EGLImageKHR image = c->cnx->hooks->egl.eglCreateImageKHR(
+                dp->dpys[c->impl], c->context, target, buffer, attrib_list);
+        if (image == EGL_NO_IMAGE_KHR)
+            return image;
+            
+        egl_image_t* result = new egl_image_t(dpy, ctx);
+        result->images[c->impl] = image;
+        return (EGLImageKHR)result;
+    } else {
+        // EGL_NO_CONTEXT is a valid parameter
+        egl_display_t const * const dp = get_display(dpy);
+        if (dp == 0) {
+            return setError(EGL_BAD_DISPLAY, EGL_NO_IMAGE_KHR);
+        }
+        // since we don't have a way to know which implementation to call,
+        // we're calling all of them
+
+        EGLImageKHR implImages[IMPL_NUM_DRIVERS_IMPLEMENTATIONS];
+        bool success = false;
+        for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
+            egl_connection_t* const cnx = &gEGLImpl[i];
+            implImages[i] = EGL_NO_IMAGE_KHR;
+            if (cnx->dso) {
+                if (cnx->hooks->egl.eglCreateImageKHR) {
+                    implImages[i] = cnx->hooks->egl.eglCreateImageKHR(
+                            dp->dpys[i], ctx, target, buffer, attrib_list);
+                    if (implImages[i] != EGL_NO_IMAGE_KHR) {
+                        success = true;
+                    }
+                }
+            }
+        }
+        if (!success)
+            return EGL_NO_IMAGE_KHR;
+        
+        egl_image_t* result = new egl_image_t(dpy, ctx);
+        memcpy(result->images, implImages, sizeof(implImages));
+        return (EGLImageKHR)result;
+    }
+}
+
+EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR img)
+{
+     egl_display_t const * const dp = get_display(dpy);
+     if (dp == 0) {
+         return setError(EGL_BAD_DISPLAY, EGL_FALSE);
+     }
+
+     egl_image_t* image = get_image(img);
+     if (!image->isValid()) {
+         return setError(EGL_BAD_PARAMETER, EGL_FALSE);
+     }
+
+     bool success = false;
+     for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
+         egl_connection_t* const cnx = &gEGLImpl[i];
+         if (image->images[i] != EGL_NO_IMAGE_KHR) {
+             if (cnx->dso) {
+                 if (cnx->hooks->egl.eglCreateImageKHR) {
+                     if (cnx->hooks->egl.eglDestroyImageKHR(
+                             dp->dpys[i], image->images[i])) {
+                         success = true;
+                     }
+                 }
+             }
+         }
+     }
+     if (!success)
+         return EGL_FALSE;
+
+     delete image;
+
+     return EGL_FALSE;
+}
+
+
+// ----------------------------------------------------------------------------
+// ANDROID extensions
+// ----------------------------------------------------------------------------
+
+EGLBoolean eglSetSwapRectangleANDROID(EGLDisplay dpy, EGLSurface draw,
+        EGLint left, EGLint top, EGLint width, EGLint height)
+{
+    if (!validate_display_surface(dpy, draw))
+        return EGL_FALSE;    
+    egl_display_t const * const dp = get_display(dpy);
+    egl_surface_t const * const s = get_surface(draw);
+    if (s->cnx->hooks->egl.eglSetSwapRectangleANDROID) {
+        return s->cnx->hooks->egl.eglSetSwapRectangleANDROID(dp->dpys[s->impl],
+                s->surface, left, top, width, height);
+    }
+    return EGL_FALSE;
+}
+
+EGLClientBuffer eglGetRenderBufferANDROID(EGLDisplay dpy, EGLSurface draw)
+{
+    if (!validate_display_surface(dpy, draw))
+        return 0;    
+    egl_display_t const * const dp = get_display(dpy);
+    egl_surface_t const * const s = get_surface(draw);
+    if (s->cnx->hooks->egl.eglGetRenderBufferANDROID) {
+        return s->cnx->hooks->egl.eglGetRenderBufferANDROID(dp->dpys[s->impl],
+                s->surface);
+    }
+    return 0;
+}
diff --git a/opengl/libs/egl_entries.in b/opengl/libs/EGL/egl_entries.in
similarity index 92%
rename from opengl/libs/egl_entries.in
rename to opengl/libs/EGL/egl_entries.in
index 3b4551b..5d89287 100644
--- a/opengl/libs/egl_entries.in
+++ b/opengl/libs/EGL/egl_entries.in
@@ -50,3 +50,8 @@
 EGL_ENTRY(EGLBoolean,  eglUnlockSurfaceKHR, EGLDisplay, EGLSurface)
 EGL_ENTRY(EGLImageKHR, eglCreateImageKHR,   EGLDisplay, EGLContext, EGLenum, EGLClientBuffer, const EGLint *)
 EGL_ENTRY(EGLBoolean,  eglDestroyImageKHR,  EGLDisplay, EGLImageKHR)
+
+/* ANDROID extensions */
+
+EGL_ENTRY(EGLBoolean, eglSetSwapRectangleANDROID, EGLDisplay, EGLSurface, EGLint, EGLint, EGLint, EGLint)
+EGL_ENTRY(EGLClientBuffer, eglGetRenderBufferANDROID, EGLDisplay, EGLSurface)
diff --git a/opengl/libs/EGL/gpu.cpp b/opengl/libs/EGL/gpu.cpp
deleted file mode 100644
index 4c902c8..0000000
--- a/opengl/libs/EGL/gpu.cpp
+++ /dev/null
@@ -1,217 +0,0 @@
-/* 
- ** Copyright 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.
- */
-
-#define LOG_TAG "EGL"
-
-#include <ctype.h>
-#include <string.h>
-#include <errno.h>
-
-#include <sys/ioctl.h>
-
-#if HAVE_ANDROID_OS
-#include <linux/android_pmem.h>
-#endif
-
-#include <cutils/log.h>
-#include <cutils/properties.h>
-
-#include <utils/IMemory.h>
-#include <utils/threads.h>
-#include <utils/IServiceManager.h>
-#include <utils/IPCThreadState.h>
-#include <utils/Parcel.h>
-
-#include <ui/EGLDisplaySurface.h>
-#include <ui/ISurfaceComposer.h>
-
-#include "hooks.h"
-#include "egl_impl.h"
-
-// ----------------------------------------------------------------------------
-namespace android {
-// ----------------------------------------------------------------------------
-
-/*
- * we provide our own allocators for the GPU regions, these
- * allocators go through surfaceflinger 
- */
-
-static Mutex                            gRegionsLock;
-static request_gpu_t                    gRegions;
-static sp<ISurfaceComposer>             gSurfaceManager;
-GL_API ISurfaceComposer*                GLES_localSurfaceManager = 0;
-
-extern egl_connection_t gEGLImpl[2];
-
-const sp<ISurfaceComposer>& getSurfaceFlinger()
-{
-    Mutex::Autolock _l(gRegionsLock);
-
-    /*
-     * There is a little bit of voodoo magic here. We want to access
-     * surfaceflinger for allocating GPU regions, however, when we are
-     * running as part of surfaceflinger, we want to bypass the
-     * service manager because surfaceflinger might not be registered yet.
-     * SurfaceFlinger will populate "GLES_localSurfaceManager" with its
-     * own address, so we can just use that.
-     */
-    if (gSurfaceManager == 0) {
-        if (GLES_localSurfaceManager) {
-            // we're running in SurfaceFlinger's context
-            gSurfaceManager =  GLES_localSurfaceManager;
-        } else {
-            // we're a remote process or not part of surfaceflinger,
-            // go through the service manager
-            sp<IServiceManager> sm = defaultServiceManager();
-            if (sm != NULL) {
-                sp<IBinder> binder = sm->getService(String16("SurfaceFlinger"));
-                gSurfaceManager = interface_cast<ISurfaceComposer>(binder);
-            }
-        }
-    }
-    return gSurfaceManager;
-}
-
-class GPURevokeRequester : public BnGPUCallback
-{
-public:
-    virtual void gpuLost() {
-        LOGD("CONTEXT_LOST: Releasing GPU upon request from SurfaceFlinger.");
-        gEGLImpl[IMPL_HARDWARE].hooks = &gHooks[IMPL_CONTEXT_LOST];
-    }
-};
-
-static sp<GPURevokeRequester> gRevokerCallback;
-
-
-request_gpu_t* gpu_acquire(void* user)
-{
-    sp<ISurfaceComposer> server( getSurfaceFlinger() );
-
-    Mutex::Autolock _l(gRegionsLock);
-    if (server == NULL) {
-        return 0;
-    }
-    
-    ISurfaceComposer::gpu_info_t info;
-    
-    if (gRevokerCallback == 0)
-        gRevokerCallback = new GPURevokeRequester();
-
-    status_t err = server->requestGPU(gRevokerCallback, &info);
-    if (err != NO_ERROR) {
-        LOGD("requestGPU returned %d", err);
-        return 0;
-    }
-
-    if (info.regs == 0) {
-        LOGD("requestGPU() failed");
-        return 0;
-    }
-
-    bool failed = false;
-    request_gpu_t* gpu = &gRegions;
-    memset(gpu, 0, sizeof(*gpu));
-    
-    if (info.regs != 0) {
-        sp<IMemoryHeap> heap(info.regs->getMemory());
-        if (heap != 0) {
-            int fd = heap->heapID();
-            gpu->regs.fd = fd;
-            gpu->regs.base = info.regs->pointer(); 
-            gpu->regs.size = info.regs->size(); 
-            gpu->regs.user = info.regs.get();
-#if HAVE_ANDROID_OS
-            struct pmem_region region;
-            if (ioctl(fd, PMEM_GET_PHYS, &region) >= 0)
-                gpu->regs.phys = (void*)region.offset;
-#endif
-            info.regs->incStrong(gpu);
-        } else {
-            LOGE("GPU register handle %p is invalid!", info.regs.get());
-            failed = true;
-        }
-    }
-
-    for (size_t i=0 ; i<info.count && !failed ; i++) {
-        sp<IMemory>& region(info.regions[i].region);
-        if (region != 0) {
-            sp<IMemoryHeap> heap(region->getMemory());
-            if (heap != 0) {
-                const int fd = heap->heapID();
-                gpu->gpu[i].fd = fd;
-                gpu->gpu[i].base = region->pointer(); 
-                gpu->gpu[i].size = region->size(); 
-                gpu->gpu[i].user = region.get();
-                gpu->gpu[i].offset = info.regions[i].reserved;
-#if HAVE_ANDROID_OS
-                struct pmem_region reg;
-                if (ioctl(fd, PMEM_GET_PHYS, &reg) >= 0)
-                    gpu->gpu[i].phys = (void*)reg.offset;
-#endif
-                region->incStrong(gpu);
-            } else {
-                LOGE("GPU region handle [%d, %p] is invalid!", i, region.get());
-                failed = true;
-            }
-        }
-    }
-    
-    if (failed) {
-        // something went wrong, clean up everything!
-        if (gpu->regs.user) {
-            static_cast<IMemory*>(gpu->regs.user)->decStrong(gpu);
-            for (size_t i=0 ; i<info.count ; i++) {
-                if (gpu->gpu[i].user) {
-                    static_cast<IMemory*>(gpu->gpu[i].user)->decStrong(gpu);
-                }
-            }
-        }
-    }
-    
-    gpu->count = info.count;
-    return gpu;
-}
-
-int gpu_release(void*, request_gpu_t* gpu)
-{
-    sp<IMemory> regs;
-
-    { // scope for lock
-        Mutex::Autolock _l(gRegionsLock);
-        regs = static_cast<IMemory*>(gpu->regs.user);   
-        gpu->regs.user = 0;
-        if (regs != 0) regs->decStrong(gpu);
-        
-        for (int i=0 ; i<gpu->count ; i++) {
-            sp<IMemory> r(static_cast<IMemory*>(gpu->gpu[i].user));
-            gpu->gpu[i].user = 0;
-            if (r != 0) r->decStrong(gpu);
-        }
-    }
-    
-    // there is a special transaction to relinquish the GPU
-    // (it will happen automatically anyway if we don't do this)
-    Parcel data, reply;
-    // NOTE: this transaction does not require an interface token
-    regs->asBinder()->transact(1000, data, &reply);
-    return 1;
-}
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-// ----------------------------------------------------------------------------
diff --git a/opengl/libs/EGL/hooks.cpp b/opengl/libs/EGL/hooks.cpp
new file mode 100644
index 0000000..2246366
--- /dev/null
+++ b/opengl/libs/EGL/hooks.cpp
@@ -0,0 +1,67 @@
+/* 
+ ** Copyright 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.
+ */
+
+#include <ctype.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include <cutils/log.h>
+
+#include "hooks.h"
+
+// ----------------------------------------------------------------------------
+namespace android {
+// ----------------------------------------------------------------------------
+
+void gl_unimplemented() {
+    LOGE("called unimplemented OpenGL ES API");
+}
+
+
+// ----------------------------------------------------------------------------
+// GL / EGL hooks
+// ----------------------------------------------------------------------------
+
+#undef GL_ENTRY
+#undef EGL_ENTRY
+#define GL_ENTRY(_r, _api, ...) #_api,
+#define EGL_ENTRY(_r, _api, ...) #_api,
+
+char const * const gl_names[] = {
+    #include "GLES_CM/gl_entries.in"
+    #include "GLES_CM/glext_entries.in"
+    NULL
+};
+
+char const * const gl2_names[] = {
+    #include "GLES2/gl2_entries.in"
+    #include "GLES2/gl2ext_entries.in"
+    NULL
+};
+
+char const * const egl_names[] = {
+    #include "egl_entries.in"
+    NULL
+};
+
+#undef GL_ENTRY
+#undef EGL_ENTRY
+
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+// ----------------------------------------------------------------------------
+
diff --git a/opengl/libs/GLES2/gl2.cpp b/opengl/libs/GLES2/gl2.cpp
new file mode 100644
index 0000000..e5358c3
--- /dev/null
+++ b/opengl/libs/GLES2/gl2.cpp
@@ -0,0 +1,111 @@
+/* 
+ ** Copyright 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.
+ */
+
+#include <ctype.h>
+#include <string.h>
+#include <errno.h>
+
+#include <sys/ioctl.h>
+
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+#include <cutils/log.h>
+#include <cutils/properties.h>
+
+#include "hooks.h"
+#include "egl_impl.h"
+
+using namespace android;
+
+// ----------------------------------------------------------------------------
+// Actual GL entry-points
+// ----------------------------------------------------------------------------
+
+#undef API_ENTRY
+#undef CALL_GL_API
+#undef CALL_GL_API_RETURN
+
+#if USE_FAST_TLS_KEY
+
+    #define API_ENTRY(_api) __attribute__((naked)) _api
+
+    #define CALL_GL_API(_api, ...)                              \
+         asm volatile(                                          \
+            "mov   r12, #0xFFFF0FFF   \n"                       \
+            "ldr   r12, [r12, #-15]   \n"                       \
+            "ldr   r12, [r12, %[tls]] \n"                       \
+            "cmp   r12, #0            \n"                       \
+            "ldrne pc,  [r12, %[api]] \n"                       \
+            "bx    lr                 \n"                       \
+            :                                                   \
+            : [tls] "J"(TLS_SLOT_OPENGL_API*4),                 \
+              [api] "J"(__builtin_offsetof(gl_hooks_t, gl2._api))    \
+            :                                                   \
+            );
+    
+    #define CALL_GL_API_RETURN(_api, ...) \
+        CALL_GL_API(_api, __VA_ARGS__) \
+        return 0; // placate gcc's warnings. never reached.
+
+#else
+
+    #define API_ENTRY(_api) _api
+
+    #define CALL_GL_API(_api, ...)                                       \
+        gl_hooks_t::gl2_t const * const _c = &getGlThreadSpecific()->gl2; \
+        _c->_api(__VA_ARGS__)
+    
+    #define CALL_GL_API_RETURN(_api, ...)                                \
+        gl_hooks_t::gl2_t const * const _c = &getGlThreadSpecific()->gl2; \
+        return _c->_api(__VA_ARGS__)
+
+#endif
+
+
+extern "C" {
+#include "gl2_api.in"
+#include "gl2ext_api.in"
+}
+
+#undef API_ENTRY
+#undef CALL_GL_API
+#undef CALL_GL_API_RETURN
+
+
+/*
+ * These GL calls are special because they need to EGL to retrieve some
+ * informations before they can execute.
+ */
+
+extern "C" void __glEGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image);
+extern "C" void __glEGLImageTargetRenderbufferStorageOES(GLenum target, GLeglImageOES image);
+
+
+void glEGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image)
+{
+    GLeglImageOES implImage = 
+        (GLeglImageOES)egl_get_image_for_current_context((EGLImageKHR)image);
+    __glEGLImageTargetTexture2DOES(target, implImage);
+}
+
+void glEGLImageTargetRenderbufferStorageOES(GLenum target, GLeglImageOES image)
+{
+    GLeglImageOES implImage = 
+        (GLeglImageOES)egl_get_image_for_current_context((EGLImageKHR)image);
+    __glEGLImageTargetRenderbufferStorageOES(target, image);
+}
+
diff --git a/opengl/libs/GLES2/gl2_api.in b/opengl/libs/GLES2/gl2_api.in
new file mode 100644
index 0000000..9c2e69a
--- /dev/null
+++ b/opengl/libs/GLES2/gl2_api.in
@@ -0,0 +1,426 @@
+void API_ENTRY(glActiveTexture)(GLenum texture) {
+    CALL_GL_API(glActiveTexture, texture);
+}
+void API_ENTRY(glAttachShader)(GLuint program, GLuint shader) {
+    CALL_GL_API(glAttachShader, program, shader);
+}
+void API_ENTRY(glBindAttribLocation)(GLuint program, GLuint index, const char* name) {
+    CALL_GL_API(glBindAttribLocation, program, index, name);
+}
+void API_ENTRY(glBindBuffer)(GLenum target, GLuint buffer) {
+    CALL_GL_API(glBindBuffer, target, buffer);
+}
+void API_ENTRY(glBindFramebuffer)(GLenum target, GLuint framebuffer) {
+    CALL_GL_API(glBindFramebuffer, target, framebuffer);
+}
+void API_ENTRY(glBindRenderbuffer)(GLenum target, GLuint renderbuffer) {
+    CALL_GL_API(glBindRenderbuffer, target, renderbuffer);
+}
+void API_ENTRY(glBindTexture)(GLenum target, GLuint texture) {
+    CALL_GL_API(glBindTexture, target, texture);
+}
+void API_ENTRY(glBlendColor)(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) {
+    CALL_GL_API(glBlendColor, red, green, blue, alpha);
+}
+void API_ENTRY(glBlendEquation)( GLenum mode ) {
+    CALL_GL_API(glBlendEquation, mode);
+}
+void API_ENTRY(glBlendEquationSeparate)(GLenum modeRGB, GLenum modeAlpha) {
+    CALL_GL_API(glBlendEquationSeparate, modeRGB, modeAlpha);
+}
+void API_ENTRY(glBlendFunc)(GLenum sfactor, GLenum dfactor) {
+    CALL_GL_API(glBlendFunc, sfactor, dfactor);
+}
+void API_ENTRY(glBlendFuncSeparate)(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) {
+    CALL_GL_API(glBlendFuncSeparate, srcRGB, dstRGB, srcAlpha, dstAlpha);
+}
+void API_ENTRY(glBufferData)(GLenum target, GLsizeiptr size, const void* data, GLenum usage) {
+    CALL_GL_API(glBufferData, target, size, data, usage);
+}
+void API_ENTRY(glBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, const void* data) {
+    CALL_GL_API(glBufferSubData, target, offset, size, data);
+}
+GLenum API_ENTRY(glCheckFramebufferStatus)(GLenum target) {
+    CALL_GL_API_RETURN(glCheckFramebufferStatus, target);
+}
+void API_ENTRY(glClear)(GLbitfield mask) {
+    CALL_GL_API(glClear, mask);
+}
+void API_ENTRY(glClearColor)(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) {
+    CALL_GL_API(glClearColor, red, green, blue, alpha);
+}
+void API_ENTRY(glClearDepthf)(GLclampf depth) {
+    CALL_GL_API(glClearDepthf, depth);
+}
+void API_ENTRY(glClearStencil)(GLint s) {
+    CALL_GL_API(glClearStencil, s);
+}
+void API_ENTRY(glColorMask)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) {
+    CALL_GL_API(glColorMask, red, green, blue, alpha);
+}
+void API_ENTRY(glCompileShader)(GLuint shader) {
+    CALL_GL_API(glCompileShader, shader);
+}
+void API_ENTRY(glCompressedTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data) {
+    CALL_GL_API(glCompressedTexImage2D, target, level, internalformat, width, height, border, imageSize, data);
+}
+void API_ENTRY(glCompressedTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data) {
+    CALL_GL_API(glCompressedTexSubImage2D, target, level, xoffset, yoffset, width, height, format, imageSize, data);
+}
+void API_ENTRY(glCopyTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) {
+    CALL_GL_API(glCopyTexImage2D, target, level, internalformat, x, y, width, height, border);
+}
+void API_ENTRY(glCopyTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) {
+    CALL_GL_API(glCopyTexSubImage2D, target, level, xoffset, yoffset, x, y, width, height);
+}
+GLuint API_ENTRY(glCreateProgram)(void) {
+    CALL_GL_API_RETURN(glCreateProgram);
+}
+GLuint API_ENTRY(glCreateShader)(GLenum type) {
+    CALL_GL_API_RETURN(glCreateShader, type);
+}
+void API_ENTRY(glCullFace)(GLenum mode) {
+    CALL_GL_API(glCullFace, mode);
+}
+void API_ENTRY(glDeleteBuffers)(GLsizei n, const GLuint* buffers) {
+    CALL_GL_API(glDeleteBuffers, n, buffers);
+}
+void API_ENTRY(glDeleteFramebuffers)(GLsizei n, const GLuint* framebuffers) {
+    CALL_GL_API(glDeleteFramebuffers, n, framebuffers);
+}
+void API_ENTRY(glDeleteProgram)(GLuint program) {
+    CALL_GL_API(glDeleteProgram, program);
+}
+void API_ENTRY(glDeleteRenderbuffers)(GLsizei n, const GLuint* renderbuffers) {
+    CALL_GL_API(glDeleteRenderbuffers, n, renderbuffers);
+}
+void API_ENTRY(glDeleteShader)(GLuint shader) {
+    CALL_GL_API(glDeleteShader, shader);
+}
+void API_ENTRY(glDeleteTextures)(GLsizei n, const GLuint* textures) {
+    CALL_GL_API(glDeleteTextures, n, textures);
+}
+void API_ENTRY(glDepthFunc)(GLenum func) {
+    CALL_GL_API(glDepthFunc, func);
+}
+void API_ENTRY(glDepthMask)(GLboolean flag) {
+    CALL_GL_API(glDepthMask, flag);
+}
+void API_ENTRY(glDepthRangef)(GLclampf zNear, GLclampf zFar) {
+    CALL_GL_API(glDepthRangef, zNear, zFar);
+}
+void API_ENTRY(glDetachShader)(GLuint program, GLuint shader) {
+    CALL_GL_API(glDetachShader, program, shader);
+}
+void API_ENTRY(glDisable)(GLenum cap) {
+    CALL_GL_API(glDisable, cap);
+}
+void API_ENTRY(glDisableVertexAttribArray)(GLuint index) {
+    CALL_GL_API(glDisableVertexAttribArray, index);
+}
+void API_ENTRY(glDrawArrays)(GLenum mode, GLint first, GLsizei count) {
+    CALL_GL_API(glDrawArrays, mode, first, count);
+}
+void API_ENTRY(glDrawElements)(GLenum mode, GLsizei count, GLenum type, const void* indices) {
+    CALL_GL_API(glDrawElements, mode, count, type, indices);
+}
+void API_ENTRY(glEnable)(GLenum cap) {
+    CALL_GL_API(glEnable, cap);
+}
+void API_ENTRY(glEnableVertexAttribArray)(GLuint index) {
+    CALL_GL_API(glEnableVertexAttribArray, index);
+}
+void API_ENTRY(glFinish)(void) {
+    CALL_GL_API(glFinish);
+}
+void API_ENTRY(glFlush)(void) {
+    CALL_GL_API(glFlush);
+}
+void API_ENTRY(glFramebufferRenderbuffer)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) {
+    CALL_GL_API(glFramebufferRenderbuffer, target, attachment, renderbuffertarget, renderbuffer);
+}
+void API_ENTRY(glFramebufferTexture2D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) {
+    CALL_GL_API(glFramebufferTexture2D, target, attachment, textarget, texture, level);
+}
+void API_ENTRY(glFrontFace)(GLenum mode) {
+    CALL_GL_API(glFrontFace, mode);
+}
+void API_ENTRY(glGenBuffers)(GLsizei n, GLuint* buffers) {
+    CALL_GL_API(glGenBuffers, n, buffers);
+}
+void API_ENTRY(glGenerateMipmap)(GLenum target) {
+    CALL_GL_API(glGenerateMipmap, target);
+}
+void API_ENTRY(glGenFramebuffers)(GLsizei n, GLuint* framebuffers) {
+    CALL_GL_API(glGenFramebuffers, n, framebuffers);
+}
+void API_ENTRY(glGenRenderbuffers)(GLsizei n, GLuint* renderbuffers) {
+    CALL_GL_API(glGenRenderbuffers, n, renderbuffers);
+}
+void API_ENTRY(glGenTextures)(GLsizei n, GLuint* textures) {
+    CALL_GL_API(glGenTextures, n, textures);
+}
+void API_ENTRY(glGetActiveAttrib)(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name) {
+    CALL_GL_API(glGetActiveAttrib, program, index, bufsize, length, size, type, name);
+}
+void API_ENTRY(glGetActiveUniform)(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name) {
+    CALL_GL_API(glGetActiveUniform, program, index, bufsize, length, size, type, name);
+}
+void API_ENTRY(glGetAttachedShaders)(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders) {
+    CALL_GL_API(glGetAttachedShaders, program, maxcount, count, shaders);
+}
+int API_ENTRY(glGetAttribLocation)(GLuint program, const char* name) {
+    CALL_GL_API_RETURN(glGetAttribLocation, program, name);
+}
+void API_ENTRY(glGetBooleanv)(GLenum pname, GLboolean* params) {
+    CALL_GL_API(glGetBooleanv, pname, params);
+}
+void API_ENTRY(glGetBufferParameteriv)(GLenum target, GLenum pname, GLint* params) {
+    CALL_GL_API(glGetBufferParameteriv, target, pname, params);
+}
+GLenum API_ENTRY(glGetError)(void) {
+    CALL_GL_API_RETURN(glGetError);
+}
+void API_ENTRY(glGetFloatv)(GLenum pname, GLfloat* params) {
+    CALL_GL_API(glGetFloatv, pname, params);
+}
+void API_ENTRY(glGetFramebufferAttachmentParameteriv)(GLenum target, GLenum attachment, GLenum pname, GLint* params) {
+    CALL_GL_API(glGetFramebufferAttachmentParameteriv, target, attachment, pname, params);
+}
+void API_ENTRY(glGetIntegerv)(GLenum pname, GLint* params) {
+    CALL_GL_API(glGetIntegerv, pname, params);
+}
+void API_ENTRY(glGetProgramiv)(GLuint program, GLenum pname, GLint* params) {
+    CALL_GL_API(glGetProgramiv, program, pname, params);
+}
+void API_ENTRY(glGetProgramInfoLog)(GLuint program, GLsizei bufsize, GLsizei* length, char* infolog) {
+    CALL_GL_API(glGetProgramInfoLog, program, bufsize, length, infolog);
+}
+void API_ENTRY(glGetRenderbufferParameteriv)(GLenum target, GLenum pname, GLint* params) {
+    CALL_GL_API(glGetRenderbufferParameteriv, target, pname, params);
+}
+void API_ENTRY(glGetShaderiv)(GLuint shader, GLenum pname, GLint* params) {
+    CALL_GL_API(glGetShaderiv, shader, pname, params);
+}
+void API_ENTRY(glGetShaderInfoLog)(GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog) {
+    CALL_GL_API(glGetShaderInfoLog, shader, bufsize, length, infolog);
+}
+void API_ENTRY(glGetShaderPrecisionFormat)(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision) {
+    CALL_GL_API(glGetShaderPrecisionFormat, shadertype, precisiontype, range, precision);
+}
+void API_ENTRY(glGetShaderSource)(GLuint shader, GLsizei bufsize, GLsizei* length, char* source) {
+    CALL_GL_API(glGetShaderSource, shader, bufsize, length, source);
+}
+const GLubyte* API_ENTRY(glGetString)(GLenum name) {
+    CALL_GL_API_RETURN(glGetString, name);
+}
+void API_ENTRY(glGetTexParameterfv)(GLenum target, GLenum pname, GLfloat* params) {
+    CALL_GL_API(glGetTexParameterfv, target, pname, params);
+}
+void API_ENTRY(glGetTexParameteriv)(GLenum target, GLenum pname, GLint* params) {
+    CALL_GL_API(glGetTexParameteriv, target, pname, params);
+}
+void API_ENTRY(glGetUniformfv)(GLuint program, GLint location, GLfloat* params) {
+    CALL_GL_API(glGetUniformfv, program, location, params);
+}
+void API_ENTRY(glGetUniformiv)(GLuint program, GLint location, GLint* params) {
+    CALL_GL_API(glGetUniformiv, program, location, params);
+}
+int API_ENTRY(glGetUniformLocation)(GLuint program, const char* name) {
+    CALL_GL_API_RETURN(glGetUniformLocation, program, name);
+}
+void API_ENTRY(glGetVertexAttribfv)(GLuint index, GLenum pname, GLfloat* params) {
+    CALL_GL_API(glGetVertexAttribfv, index, pname, params);
+}
+void API_ENTRY(glGetVertexAttribiv)(GLuint index, GLenum pname, GLint* params) {
+    CALL_GL_API(glGetVertexAttribiv, index, pname, params);
+}
+void API_ENTRY(glGetVertexAttribPointerv)(GLuint index, GLenum pname, void** pointer) {
+    CALL_GL_API(glGetVertexAttribPointerv, index, pname, pointer);
+}
+void API_ENTRY(glHint)(GLenum target, GLenum mode) {
+    CALL_GL_API(glHint, target, mode);
+}
+GLboolean API_ENTRY(glIsBuffer)(GLuint buffer) {
+    CALL_GL_API_RETURN(glIsBuffer, buffer);
+}
+GLboolean API_ENTRY(glIsEnabled)(GLenum cap) {
+    CALL_GL_API_RETURN(glIsEnabled, cap);
+}
+GLboolean API_ENTRY(glIsFramebuffer)(GLuint framebuffer) {
+    CALL_GL_API_RETURN(glIsFramebuffer, framebuffer);
+}
+GLboolean API_ENTRY(glIsProgram)(GLuint program) {
+    CALL_GL_API_RETURN(glIsProgram, program);
+}
+GLboolean API_ENTRY(glIsRenderbuffer)(GLuint renderbuffer) {
+    CALL_GL_API_RETURN(glIsRenderbuffer, renderbuffer);
+}
+GLboolean API_ENTRY(glIsShader)(GLuint shader) {
+    CALL_GL_API_RETURN(glIsShader, shader);
+}
+GLboolean API_ENTRY(glIsTexture)(GLuint texture) {
+    CALL_GL_API_RETURN(glIsTexture, texture);
+}
+void API_ENTRY(glLineWidth)(GLfloat width) {
+    CALL_GL_API(glLineWidth, width);
+}
+void API_ENTRY(glLinkProgram)(GLuint program) {
+    CALL_GL_API(glLinkProgram, program);
+}
+void API_ENTRY(glPixelStorei)(GLenum pname, GLint param) {
+    CALL_GL_API(glPixelStorei, pname, param);
+}
+void API_ENTRY(glPolygonOffset)(GLfloat factor, GLfloat units) {
+    CALL_GL_API(glPolygonOffset, factor, units);
+}
+void API_ENTRY(glReadPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) {
+    CALL_GL_API(glReadPixels, x, y, width, height, format, type, pixels);
+}
+void API_ENTRY(glReleaseShaderCompiler)(void) {
+    CALL_GL_API(glReleaseShaderCompiler);
+}
+void API_ENTRY(glRenderbufferStorage)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height) {
+    CALL_GL_API(glRenderbufferStorage, target, internalformat, width, height);
+}
+void API_ENTRY(glSampleCoverage)(GLclampf value, GLboolean invert) {
+    CALL_GL_API(glSampleCoverage, value, invert);
+}
+void API_ENTRY(glScissor)(GLint x, GLint y, GLsizei width, GLsizei height) {
+    CALL_GL_API(glScissor, x, y, width, height);
+}
+void API_ENTRY(glShaderBinary)(GLsizei n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLsizei length) {
+    CALL_GL_API(glShaderBinary, n, shaders, binaryformat, binary, length);
+}
+void API_ENTRY(glShaderSource)(GLuint shader, GLsizei count, const char** string, const GLint* length) {
+    CALL_GL_API(glShaderSource, shader, count, string, length);
+}
+void API_ENTRY(glStencilFunc)(GLenum func, GLint ref, GLuint mask) {
+    CALL_GL_API(glStencilFunc, func, ref, mask);
+}
+void API_ENTRY(glStencilFuncSeparate)(GLenum face, GLenum func, GLint ref, GLuint mask) {
+    CALL_GL_API(glStencilFuncSeparate, face, func, ref, mask);
+}
+void API_ENTRY(glStencilMask)(GLuint mask) {
+    CALL_GL_API(glStencilMask, mask);
+}
+void API_ENTRY(glStencilMaskSeparate)(GLenum face, GLuint mask) {
+    CALL_GL_API(glStencilMaskSeparate, face, mask);
+}
+void API_ENTRY(glStencilOp)(GLenum fail, GLenum zfail, GLenum zpass) {
+    CALL_GL_API(glStencilOp, fail, zfail, zpass);
+}
+void API_ENTRY(glStencilOpSeparate)(GLenum face, GLenum fail, GLenum zfail, GLenum zpass) {
+    CALL_GL_API(glStencilOpSeparate, face, fail, zfail, zpass);
+}
+void API_ENTRY(glTexImage2D)(GLenum target, GLint level, GLint internalformat,  GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels) {
+    CALL_GL_API(glTexImage2D, target, level, internalformat, width, height, border, format, type, pixels);
+}
+void API_ENTRY(glTexParameterf)(GLenum target, GLenum pname, GLfloat param) {
+    CALL_GL_API(glTexParameterf, target, pname, param);
+}
+void API_ENTRY(glTexParameterfv)(GLenum target, GLenum pname, const GLfloat* params) {
+    CALL_GL_API(glTexParameterfv, target, pname, params);
+}
+void API_ENTRY(glTexParameteri)(GLenum target, GLenum pname, GLint param) {
+    CALL_GL_API(glTexParameteri, target, pname, param);
+}
+void API_ENTRY(glTexParameteriv)(GLenum target, GLenum pname, const GLint* params) {
+    CALL_GL_API(glTexParameteriv, target, pname, params);
+}
+void API_ENTRY(glTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels) {
+    CALL_GL_API(glTexSubImage2D, target, level, xoffset, yoffset, width, height, format, type, pixels);
+}
+void API_ENTRY(glUniform1f)(GLint location, GLfloat x) {
+    CALL_GL_API(glUniform1f, location, x);
+}
+void API_ENTRY(glUniform1fv)(GLint location, GLsizei count, const GLfloat* v) {
+    CALL_GL_API(glUniform1fv, location, count, v);
+}
+void API_ENTRY(glUniform1i)(GLint location, GLint x) {
+    CALL_GL_API(glUniform1i, location, x);
+}
+void API_ENTRY(glUniform1iv)(GLint location, GLsizei count, const GLint* v) {
+    CALL_GL_API(glUniform1iv, location, count, v);
+}
+void API_ENTRY(glUniform2f)(GLint location, GLfloat x, GLfloat y) {
+    CALL_GL_API(glUniform2f, location, x, y);
+}
+void API_ENTRY(glUniform2fv)(GLint location, GLsizei count, const GLfloat* v) {
+    CALL_GL_API(glUniform2fv, location, count, v);
+}
+void API_ENTRY(glUniform2i)(GLint location, GLint x, GLint y) {
+    CALL_GL_API(glUniform2i, location, x, y);
+}
+void API_ENTRY(glUniform2iv)(GLint location, GLsizei count, const GLint* v) {
+    CALL_GL_API(glUniform2iv, location, count, v);
+}
+void API_ENTRY(glUniform3f)(GLint location, GLfloat x, GLfloat y, GLfloat z) {
+    CALL_GL_API(glUniform3f, location, x, y, z);
+}
+void API_ENTRY(glUniform3fv)(GLint location, GLsizei count, const GLfloat* v) {
+    CALL_GL_API(glUniform3fv, location, count, v);
+}
+void API_ENTRY(glUniform3i)(GLint location, GLint x, GLint y, GLint z) {
+    CALL_GL_API(glUniform3i, location, x, y, z);
+}
+void API_ENTRY(glUniform3iv)(GLint location, GLsizei count, const GLint* v) {
+    CALL_GL_API(glUniform3iv, location, count, v);
+}
+void API_ENTRY(glUniform4f)(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w) {
+    CALL_GL_API(glUniform4f, location, x, y, z, w);
+}
+void API_ENTRY(glUniform4fv)(GLint location, GLsizei count, const GLfloat* v) {
+    CALL_GL_API(glUniform4fv, location, count, v);
+}
+void API_ENTRY(glUniform4i)(GLint location, GLint x, GLint y, GLint z, GLint w) {
+    CALL_GL_API(glUniform4i, location, x, y, z, w);
+}
+void API_ENTRY(glUniform4iv)(GLint location, GLsizei count, const GLint* v) {
+    CALL_GL_API(glUniform4iv, location, count, v);
+}
+void API_ENTRY(glUniformMatrix2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
+    CALL_GL_API(glUniformMatrix2fv, location, count, transpose, value);
+}
+void API_ENTRY(glUniformMatrix3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
+    CALL_GL_API(glUniformMatrix3fv, location, count, transpose, value);
+}
+void API_ENTRY(glUniformMatrix4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) {
+    CALL_GL_API(glUniformMatrix4fv, location, count, transpose, value);
+}
+void API_ENTRY(glUseProgram)(GLuint program) {
+    CALL_GL_API(glUseProgram, program);
+}
+void API_ENTRY(glValidateProgram)(GLuint program) {
+    CALL_GL_API(glValidateProgram, program);
+}
+void API_ENTRY(glVertexAttrib1f)(GLuint indx, GLfloat x) {
+    CALL_GL_API(glVertexAttrib1f, indx, x);
+}
+void API_ENTRY(glVertexAttrib1fv)(GLuint indx, const GLfloat* values) {
+    CALL_GL_API(glVertexAttrib1fv, indx, values);
+}
+void API_ENTRY(glVertexAttrib2f)(GLuint indx, GLfloat x, GLfloat y) {
+    CALL_GL_API(glVertexAttrib2f, indx, x, y);
+}
+void API_ENTRY(glVertexAttrib2fv)(GLuint indx, const GLfloat* values) {
+    CALL_GL_API(glVertexAttrib2fv, indx, values);
+}
+void API_ENTRY(glVertexAttrib3f)(GLuint indx, GLfloat x, GLfloat y, GLfloat z) {
+    CALL_GL_API(glVertexAttrib3f, indx, x, y, z);
+}
+void API_ENTRY(glVertexAttrib3fv)(GLuint indx, const GLfloat* values) {
+    CALL_GL_API(glVertexAttrib3fv, indx, values);
+}
+void API_ENTRY(glVertexAttrib4f)(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w) {
+    CALL_GL_API(glVertexAttrib4f, indx, x, y, z, w);
+}
+void API_ENTRY(glVertexAttrib4fv)(GLuint indx, const GLfloat* values) {
+    CALL_GL_API(glVertexAttrib4fv, indx, values);
+}
+void API_ENTRY(glVertexAttribPointer)(GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr) {
+    CALL_GL_API(glVertexAttribPointer, indx, size, type, normalized, stride, ptr);
+}
+void API_ENTRY(glViewport)(GLint x, GLint y, GLsizei width, GLsizei height) {
+    CALL_GL_API(glViewport, x, y, width, height);
+}
diff --git a/opengl/libs/GLES2/gl2_entries.in b/opengl/libs/GLES2/gl2_entries.in
new file mode 100644
index 0000000..6a41b94
--- /dev/null
+++ b/opengl/libs/GLES2/gl2_entries.in
@@ -0,0 +1,142 @@
+GL_ENTRY(void, glActiveTexture, GLenum texture)
+GL_ENTRY(void, glAttachShader, GLuint program, GLuint shader)
+GL_ENTRY(void, glBindAttribLocation, GLuint program, GLuint index, const char* name)
+GL_ENTRY(void, glBindBuffer, GLenum target, GLuint buffer)
+GL_ENTRY(void, glBindFramebuffer, GLenum target, GLuint framebuffer)
+GL_ENTRY(void, glBindRenderbuffer, GLenum target, GLuint renderbuffer)
+GL_ENTRY(void, glBindTexture, GLenum target, GLuint texture)
+GL_ENTRY(void, glBlendColor, GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+GL_ENTRY(void, glBlendEquation,  GLenum mode )
+GL_ENTRY(void, glBlendEquationSeparate, GLenum modeRGB, GLenum modeAlpha)
+GL_ENTRY(void, glBlendFunc, GLenum sfactor, GLenum dfactor)
+GL_ENTRY(void, glBlendFuncSeparate, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
+GL_ENTRY(void, glBufferData, GLenum target, GLsizeiptr size, const void* data, GLenum usage)
+GL_ENTRY(void, glBufferSubData, GLenum target, GLintptr offset, GLsizeiptr size, const void* data)
+GL_ENTRY(GLenum, glCheckFramebufferStatus, GLenum target)
+GL_ENTRY(void, glClear, GLbitfield mask)
+GL_ENTRY(void, glClearColor, GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+GL_ENTRY(void, glClearDepthf, GLclampf depth)
+GL_ENTRY(void, glClearStencil, GLint s)
+GL_ENTRY(void, glColorMask, GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
+GL_ENTRY(void, glCompileShader, GLuint shader)
+GL_ENTRY(void, glCompressedTexImage2D, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data)
+GL_ENTRY(void, glCompressedTexSubImage2D, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data)
+GL_ENTRY(void, glCopyTexImage2D, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
+GL_ENTRY(void, glCopyTexSubImage2D, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+GL_ENTRY(GLuint, glCreateProgram, void)
+GL_ENTRY(GLuint, glCreateShader, GLenum type)
+GL_ENTRY(void, glCullFace, GLenum mode)
+GL_ENTRY(void, glDeleteBuffers, GLsizei n, const GLuint* buffers)
+GL_ENTRY(void, glDeleteFramebuffers, GLsizei n, const GLuint* framebuffers)
+GL_ENTRY(void, glDeleteProgram, GLuint program)
+GL_ENTRY(void, glDeleteRenderbuffers, GLsizei n, const GLuint* renderbuffers)
+GL_ENTRY(void, glDeleteShader, GLuint shader)
+GL_ENTRY(void, glDeleteTextures, GLsizei n, const GLuint* textures)
+GL_ENTRY(void, glDepthFunc, GLenum func)
+GL_ENTRY(void, glDepthMask, GLboolean flag)
+GL_ENTRY(void, glDepthRangef, GLclampf zNear, GLclampf zFar)
+GL_ENTRY(void, glDetachShader, GLuint program, GLuint shader)
+GL_ENTRY(void, glDisable, GLenum cap)
+GL_ENTRY(void, glDisableVertexAttribArray, GLuint index)
+GL_ENTRY(void, glDrawArrays, GLenum mode, GLint first, GLsizei count)
+GL_ENTRY(void, glDrawElements, GLenum mode, GLsizei count, GLenum type, const void* indices)
+GL_ENTRY(void, glEnable, GLenum cap)
+GL_ENTRY(void, glEnableVertexAttribArray, GLuint index)
+GL_ENTRY(void, glFinish, void)
+GL_ENTRY(void, glFlush, void)
+GL_ENTRY(void, glFramebufferRenderbuffer, GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
+GL_ENTRY(void, glFramebufferTexture2D, GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
+GL_ENTRY(void, glFrontFace, GLenum mode)
+GL_ENTRY(void, glGenBuffers, GLsizei n, GLuint* buffers)
+GL_ENTRY(void, glGenerateMipmap, GLenum target)
+GL_ENTRY(void, glGenFramebuffers, GLsizei n, GLuint* framebuffers)
+GL_ENTRY(void, glGenRenderbuffers, GLsizei n, GLuint* renderbuffers)
+GL_ENTRY(void, glGenTextures, GLsizei n, GLuint* textures)
+GL_ENTRY(void, glGetActiveAttrib, GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
+GL_ENTRY(void, glGetActiveUniform, GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
+GL_ENTRY(void, glGetAttachedShaders, GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders)
+GL_ENTRY(int, glGetAttribLocation, GLuint program, const char* name)
+GL_ENTRY(void, glGetBooleanv, GLenum pname, GLboolean* params)
+GL_ENTRY(void, glGetBufferParameteriv, GLenum target, GLenum pname, GLint* params)
+GL_ENTRY(GLenum, glGetError, void)
+GL_ENTRY(void, glGetFloatv, GLenum pname, GLfloat* params)
+GL_ENTRY(void, glGetFramebufferAttachmentParameteriv, GLenum target, GLenum attachment, GLenum pname, GLint* params)
+GL_ENTRY(void, glGetIntegerv, GLenum pname, GLint* params)
+GL_ENTRY(void, glGetProgramiv, GLuint program, GLenum pname, GLint* params)
+GL_ENTRY(void, glGetProgramInfoLog, GLuint program, GLsizei bufsize, GLsizei* length, char* infolog)
+GL_ENTRY(void, glGetRenderbufferParameteriv, GLenum target, GLenum pname, GLint* params)
+GL_ENTRY(void, glGetShaderiv, GLuint shader, GLenum pname, GLint* params)
+GL_ENTRY(void, glGetShaderInfoLog, GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog)
+GL_ENTRY(void, glGetShaderPrecisionFormat, GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision)
+GL_ENTRY(void, glGetShaderSource, GLuint shader, GLsizei bufsize, GLsizei* length, char* source)
+GL_ENTRY(const GLubyte*, glGetString, GLenum name)
+GL_ENTRY(void, glGetTexParameterfv, GLenum target, GLenum pname, GLfloat* params)
+GL_ENTRY(void, glGetTexParameteriv, GLenum target, GLenum pname, GLint* params)
+GL_ENTRY(void, glGetUniformfv, GLuint program, GLint location, GLfloat* params)
+GL_ENTRY(void, glGetUniformiv, GLuint program, GLint location, GLint* params)
+GL_ENTRY(int, glGetUniformLocation, GLuint program, const char* name)
+GL_ENTRY(void, glGetVertexAttribfv, GLuint index, GLenum pname, GLfloat* params)
+GL_ENTRY(void, glGetVertexAttribiv, GLuint index, GLenum pname, GLint* params)
+GL_ENTRY(void, glGetVertexAttribPointerv, GLuint index, GLenum pname, void** pointer)
+GL_ENTRY(void, glHint, GLenum target, GLenum mode)
+GL_ENTRY(GLboolean, glIsBuffer, GLuint buffer)
+GL_ENTRY(GLboolean, glIsEnabled, GLenum cap)
+GL_ENTRY(GLboolean, glIsFramebuffer, GLuint framebuffer)
+GL_ENTRY(GLboolean, glIsProgram, GLuint program)
+GL_ENTRY(GLboolean, glIsRenderbuffer, GLuint renderbuffer)
+GL_ENTRY(GLboolean, glIsShader, GLuint shader)
+GL_ENTRY(GLboolean, glIsTexture, GLuint texture)
+GL_ENTRY(void, glLineWidth, GLfloat width)
+GL_ENTRY(void, glLinkProgram, GLuint program)
+GL_ENTRY(void, glPixelStorei, GLenum pname, GLint param)
+GL_ENTRY(void, glPolygonOffset, GLfloat factor, GLfloat units)
+GL_ENTRY(void, glReadPixels, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels)
+GL_ENTRY(void, glReleaseShaderCompiler, void)
+GL_ENTRY(void, glRenderbufferStorage, GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
+GL_ENTRY(void, glSampleCoverage, GLclampf value, GLboolean invert)
+GL_ENTRY(void, glScissor, GLint x, GLint y, GLsizei width, GLsizei height)
+GL_ENTRY(void, glShaderBinary, GLsizei n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLsizei length)
+GL_ENTRY(void, glShaderSource, GLuint shader, GLsizei count, const char** string, const GLint* length)
+GL_ENTRY(void, glStencilFunc, GLenum func, GLint ref, GLuint mask)
+GL_ENTRY(void, glStencilFuncSeparate, GLenum face, GLenum func, GLint ref, GLuint mask)
+GL_ENTRY(void, glStencilMask, GLuint mask)
+GL_ENTRY(void, glStencilMaskSeparate, GLenum face, GLuint mask)
+GL_ENTRY(void, glStencilOp, GLenum fail, GLenum zfail, GLenum zpass)
+GL_ENTRY(void, glStencilOpSeparate, GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
+GL_ENTRY(void, glTexImage2D, GLenum target, GLint level, GLint internalformat,  GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels)
+GL_ENTRY(void, glTexParameterf, GLenum target, GLenum pname, GLfloat param)
+GL_ENTRY(void, glTexParameterfv, GLenum target, GLenum pname, const GLfloat* params)
+GL_ENTRY(void, glTexParameteri, GLenum target, GLenum pname, GLint param)
+GL_ENTRY(void, glTexParameteriv, GLenum target, GLenum pname, const GLint* params)
+GL_ENTRY(void, glTexSubImage2D, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels)
+GL_ENTRY(void, glUniform1f, GLint location, GLfloat x)
+GL_ENTRY(void, glUniform1fv, GLint location, GLsizei count, const GLfloat* v)
+GL_ENTRY(void, glUniform1i, GLint location, GLint x)
+GL_ENTRY(void, glUniform1iv, GLint location, GLsizei count, const GLint* v)
+GL_ENTRY(void, glUniform2f, GLint location, GLfloat x, GLfloat y)
+GL_ENTRY(void, glUniform2fv, GLint location, GLsizei count, const GLfloat* v)
+GL_ENTRY(void, glUniform2i, GLint location, GLint x, GLint y)
+GL_ENTRY(void, glUniform2iv, GLint location, GLsizei count, const GLint* v)
+GL_ENTRY(void, glUniform3f, GLint location, GLfloat x, GLfloat y, GLfloat z)
+GL_ENTRY(void, glUniform3fv, GLint location, GLsizei count, const GLfloat* v)
+GL_ENTRY(void, glUniform3i, GLint location, GLint x, GLint y, GLint z)
+GL_ENTRY(void, glUniform3iv, GLint location, GLsizei count, const GLint* v)
+GL_ENTRY(void, glUniform4f, GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+GL_ENTRY(void, glUniform4fv, GLint location, GLsizei count, const GLfloat* v)
+GL_ENTRY(void, glUniform4i, GLint location, GLint x, GLint y, GLint z, GLint w)
+GL_ENTRY(void, glUniform4iv, GLint location, GLsizei count, const GLint* v)
+GL_ENTRY(void, glUniformMatrix2fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+GL_ENTRY(void, glUniformMatrix3fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+GL_ENTRY(void, glUniformMatrix4fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+GL_ENTRY(void, glUseProgram, GLuint program)
+GL_ENTRY(void, glValidateProgram, GLuint program)
+GL_ENTRY(void, glVertexAttrib1f, GLuint indx, GLfloat x)
+GL_ENTRY(void, glVertexAttrib1fv, GLuint indx, const GLfloat* values)
+GL_ENTRY(void, glVertexAttrib2f, GLuint indx, GLfloat x, GLfloat y)
+GL_ENTRY(void, glVertexAttrib2fv, GLuint indx, const GLfloat* values)
+GL_ENTRY(void, glVertexAttrib3f, GLuint indx, GLfloat x, GLfloat y, GLfloat z)
+GL_ENTRY(void, glVertexAttrib3fv, GLuint indx, const GLfloat* values)
+GL_ENTRY(void, glVertexAttrib4f, GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+GL_ENTRY(void, glVertexAttrib4fv, GLuint indx, const GLfloat* values)
+GL_ENTRY(void, glVertexAttribPointer, GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr)
+GL_ENTRY(void, glViewport, GLint x, GLint y, GLsizei width, GLsizei height)
diff --git a/opengl/libs/GLES2/gl2ext_api.in b/opengl/libs/GLES2/gl2ext_api.in
new file mode 100644
index 0000000..6eeecb3
--- /dev/null
+++ b/opengl/libs/GLES2/gl2ext_api.in
@@ -0,0 +1,105 @@
+void API_ENTRY(__glEGLImageTargetTexture2DOES)(GLenum target, GLeglImageOES image) {
+    CALL_GL_API(glEGLImageTargetTexture2DOES, target, image);
+}
+void API_ENTRY(__glEGLImageTargetRenderbufferStorageOES)(GLenum target, GLeglImageOES image) {
+    CALL_GL_API(glEGLImageTargetRenderbufferStorageOES, target, image);
+}
+void API_ENTRY(glGetProgramBinaryOES)(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary) {
+    CALL_GL_API(glGetProgramBinaryOES, program, bufSize, length, binaryFormat, binary);
+}
+void API_ENTRY(glProgramBinaryOES)(GLuint program, GLenum binaryFormat, const void *binary, GLint length) {
+    CALL_GL_API(glProgramBinaryOES, program, binaryFormat, binary, length);
+}
+void* API_ENTRY(glMapBufferOES)(GLenum target, GLenum access) {
+    CALL_GL_API_RETURN(glMapBufferOES, target, access);
+}
+GLboolean API_ENTRY(glUnmapBufferOES)(GLenum target) {
+    CALL_GL_API_RETURN(glUnmapBufferOES, target);
+}
+void API_ENTRY(glGetBufferPointervOES)(GLenum target, GLenum pname, void** params) {
+    CALL_GL_API(glGetBufferPointervOES, target, pname, params);
+}
+void API_ENTRY(glTexImage3DOES)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels) {
+    CALL_GL_API(glTexImage3DOES, target, level, internalformat, width, height, depth, border, format, type, pixels);
+}
+void API_ENTRY(glTexSubImage3DOES)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* pixels) {
+    CALL_GL_API(glTexSubImage3DOES, target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
+}
+void API_ENTRY(glCopyTexSubImage3DOES)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height) {
+    CALL_GL_API(glCopyTexSubImage3DOES, target, level, xoffset, yoffset, zoffset, x, y, width, height);
+}
+void API_ENTRY(glCompressedTexImage3DOES)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void* data) {
+    CALL_GL_API(glCompressedTexImage3DOES, target, level, internalformat, width, height, depth, border, imageSize, data);
+}
+void API_ENTRY(glCompressedTexSubImage3DOES)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void* data) {
+    CALL_GL_API(glCompressedTexSubImage3DOES, target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
+}
+void API_ENTRY(glFramebufferTexture3DOES)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset) {
+    CALL_GL_API(glFramebufferTexture3DOES, target, attachment, textarget, texture, level, zoffset);
+}
+void API_ENTRY(glGetPerfMonitorGroupsAMD)(GLint *numGroups, GLsizei groupsSize, GLuint *groups) {
+    CALL_GL_API(glGetPerfMonitorGroupsAMD, numGroups, groupsSize, groups);
+}
+void API_ENTRY(glGetPerfMonitorCountersAMD)(GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters) {
+    CALL_GL_API(glGetPerfMonitorCountersAMD, group, numCounters, maxActiveCounters, counterSize, counters);
+}
+void API_ENTRY(glGetPerfMonitorGroupStringAMD)(GLuint group, GLsizei bufSize, GLsizei *length, char *groupString) {
+    CALL_GL_API(glGetPerfMonitorGroupStringAMD, group, bufSize, length, groupString);
+}
+void API_ENTRY(glGetPerfMonitorCounterStringAMD)(GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, char *counterString) {
+    CALL_GL_API(glGetPerfMonitorCounterStringAMD, group, counter, bufSize, length, counterString);
+}
+void API_ENTRY(glGetPerfMonitorCounterInfoAMD)(GLuint group, GLuint counter, GLenum pname, void *data) {
+    CALL_GL_API(glGetPerfMonitorCounterInfoAMD, group, counter, pname, data);
+}
+void API_ENTRY(glGenPerfMonitorsAMD)(GLsizei n, GLuint *monitors) {
+    CALL_GL_API(glGenPerfMonitorsAMD, n, monitors);
+}
+void API_ENTRY(glDeletePerfMonitorsAMD)(GLsizei n, GLuint *monitors) {
+    CALL_GL_API(glDeletePerfMonitorsAMD, n, monitors);
+}
+void API_ENTRY(glSelectPerfMonitorCountersAMD)(GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *countersList) {
+    CALL_GL_API(glSelectPerfMonitorCountersAMD, monitor, enable, group, numCounters, countersList);
+}
+void API_ENTRY(glBeginPerfMonitorAMD)(GLuint monitor) {
+    CALL_GL_API(glBeginPerfMonitorAMD, monitor);
+}
+void API_ENTRY(glEndPerfMonitorAMD)(GLuint monitor) {
+    CALL_GL_API(glEndPerfMonitorAMD, monitor);
+}
+void API_ENTRY(glGetPerfMonitorCounterDataAMD)(GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten) {
+    CALL_GL_API(glGetPerfMonitorCounterDataAMD, monitor, pname, dataSize, data, bytesWritten);
+}
+void API_ENTRY(glDeleteFencesNV)(GLsizei n, const GLuint *fences) {
+    CALL_GL_API(glDeleteFencesNV, n, fences);
+}
+void API_ENTRY(glGenFencesNV)(GLsizei n, GLuint *fences) {
+    CALL_GL_API(glGenFencesNV, n, fences);
+}
+GLboolean API_ENTRY(glIsFenceNV)(GLuint fence) {
+    CALL_GL_API_RETURN(glIsFenceNV, fence);
+}
+GLboolean API_ENTRY(glTestFenceNV)(GLuint fence) {
+    CALL_GL_API_RETURN(glTestFenceNV, fence);
+}
+void API_ENTRY(glGetFenceivNV)(GLuint fence, GLenum pname, GLint *params) {
+    CALL_GL_API(glGetFenceivNV, fence, pname, params);
+}
+void API_ENTRY(glFinishFenceNV)(GLuint fence) {
+    CALL_GL_API(glFinishFenceNV, fence);
+}
+void API_ENTRY(glSetFenceNV)(GLuint fence, GLenum condition) {
+    CALL_GL_API(glSetFenceNV, fence, condition);
+}
+void API_ENTRY(glGetDriverControlsQCOM)(GLint *num, GLsizei size, GLuint *driverControls) {
+    CALL_GL_API(glGetDriverControlsQCOM, num, size, driverControls);
+}
+void API_ENTRY(glGetDriverControlStringQCOM)(GLuint driverControl, GLsizei bufSize, GLsizei *length, char *driverControlString) {
+    CALL_GL_API(glGetDriverControlStringQCOM, driverControl, bufSize, length, driverControlString);
+}
+void API_ENTRY(glEnableDriverControlQCOM)(GLuint driverControl) {
+    CALL_GL_API(glEnableDriverControlQCOM, driverControl);
+}
+void API_ENTRY(glDisableDriverControlQCOM)(GLuint driverControl) {
+    CALL_GL_API(glDisableDriverControlQCOM, driverControl);
+}
diff --git a/opengl/libs/GLES2/gl2ext_entries.in b/opengl/libs/GLES2/gl2ext_entries.in
new file mode 100644
index 0000000..e608f5d
--- /dev/null
+++ b/opengl/libs/GLES2/gl2ext_entries.in
@@ -0,0 +1,35 @@
+GL_ENTRY(void, glEGLImageTargetTexture2DOES, GLenum target, GLeglImageOES image)
+GL_ENTRY(void, glEGLImageTargetRenderbufferStorageOES, GLenum target, GLeglImageOES image)
+GL_ENTRY(void, glGetProgramBinaryOES, GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary)
+GL_ENTRY(void, glProgramBinaryOES, GLuint program, GLenum binaryFormat, const void *binary, GLint length)
+GL_ENTRY(void*, glMapBufferOES, GLenum target, GLenum access)
+GL_ENTRY(GLboolean, glUnmapBufferOES, GLenum target)
+GL_ENTRY(void, glGetBufferPointervOES, GLenum target, GLenum pname, void** params)
+GL_ENTRY(void, glTexImage3DOES, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels)
+GL_ENTRY(void, glTexSubImage3DOES, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* pixels)
+GL_ENTRY(void, glCopyTexSubImage3DOES, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+GL_ENTRY(void, glCompressedTexImage3DOES, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void* data)
+GL_ENTRY(void, glCompressedTexSubImage3DOES, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void* data)
+GL_ENTRY(void, glFramebufferTexture3DOES, GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset)
+GL_ENTRY(void, glGetPerfMonitorGroupsAMD, GLint *numGroups, GLsizei groupsSize, GLuint *groups)
+GL_ENTRY(void, glGetPerfMonitorCountersAMD, GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters)
+GL_ENTRY(void, glGetPerfMonitorGroupStringAMD, GLuint group, GLsizei bufSize, GLsizei *length, char *groupString)
+GL_ENTRY(void, glGetPerfMonitorCounterStringAMD, GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, char *counterString)
+GL_ENTRY(void, glGetPerfMonitorCounterInfoAMD, GLuint group, GLuint counter, GLenum pname, void *data)
+GL_ENTRY(void, glGenPerfMonitorsAMD, GLsizei n, GLuint *monitors)
+GL_ENTRY(void, glDeletePerfMonitorsAMD, GLsizei n, GLuint *monitors)
+GL_ENTRY(void, glSelectPerfMonitorCountersAMD, GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *countersList)
+GL_ENTRY(void, glBeginPerfMonitorAMD, GLuint monitor)
+GL_ENTRY(void, glEndPerfMonitorAMD, GLuint monitor)
+GL_ENTRY(void, glGetPerfMonitorCounterDataAMD, GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten)
+GL_ENTRY(void, glDeleteFencesNV, GLsizei n, const GLuint *fences)
+GL_ENTRY(void, glGenFencesNV, GLsizei n, GLuint *fences)
+GL_ENTRY(GLboolean, glIsFenceNV, GLuint fence)
+GL_ENTRY(GLboolean, glTestFenceNV, GLuint fence)
+GL_ENTRY(void, glGetFenceivNV, GLuint fence, GLenum pname, GLint *params)
+GL_ENTRY(void, glFinishFenceNV, GLuint fence)
+GL_ENTRY(void, glSetFenceNV, GLuint fence, GLenum condition)
+GL_ENTRY(void, glGetDriverControlsQCOM, GLint *num, GLsizei size, GLuint *driverControls)
+GL_ENTRY(void, glGetDriverControlStringQCOM, GLuint driverControl, GLsizei bufSize, GLsizei *length, char *driverControlString)
+GL_ENTRY(void, glEnableDriverControlQCOM, GLuint driverControl)
+GL_ENTRY(void, glDisableDriverControlQCOM, GLuint driverControl)
diff --git a/opengl/libs/GLES_CM/gl.cpp b/opengl/libs/GLES_CM/gl.cpp
index 384b59a..3204d9a 100644
--- a/opengl/libs/GLES_CM/gl.cpp
+++ b/opengl/libs/GLES_CM/gl.cpp
@@ -14,8 +14,6 @@
  ** limitations under the License.
  */
 
-#define LOG_TAG "GLES_CM"
-
 #include <ctype.h>
 #include <string.h>
 #include <errno.h>
@@ -121,16 +119,25 @@
 
 
 /*
- * These GL calls are special because they need to call into EGL to retrieve
- * some informations before they can execute.
+ * These GL calls are special because they need to EGL to retrieve some
+ * informations before they can execute.
  */
 
+extern "C" void __glEGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image);
+extern "C" void __glEGLImageTargetRenderbufferStorageOES(GLenum target, GLeglImageOES image);
+
 
 void glEGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image)
 {
+    GLeglImageOES implImage = 
+        (GLeglImageOES)egl_get_image_for_current_context((EGLImageKHR)image);
+    __glEGLImageTargetTexture2DOES(target, implImage);
 }
 
 void glEGLImageTargetRenderbufferStorageOES(GLenum target, GLeglImageOES image)
 {
+    GLeglImageOES implImage = 
+        (GLeglImageOES)egl_get_image_for_current_context((EGLImageKHR)image);
+    __glEGLImageTargetRenderbufferStorageOES(target, image);
 }
 
diff --git a/opengl/libs/gl_entries.in b/opengl/libs/GLES_CM/gl_entries.in
similarity index 100%
rename from opengl/libs/gl_entries.in
rename to opengl/libs/GLES_CM/gl_entries.in
diff --git a/opengl/libs/glext_entries.in b/opengl/libs/GLES_CM/glext_entries.in
similarity index 100%
rename from opengl/libs/glext_entries.in
rename to opengl/libs/GLES_CM/glext_entries.in
diff --git a/opengl/libs/egl_impl.h b/opengl/libs/egl_impl.h
index 312b176..c5f753d 100644
--- a/opengl/libs/egl_impl.h
+++ b/opengl/libs/egl_impl.h
@@ -31,13 +31,15 @@
 
 struct egl_connection_t
 {
-    void volatile *     dso;
+    void *              dso;
     gl_hooks_t *        hooks;
     EGLint              major;
     EGLint              minor;
     int                 unavailable;
 };
 
+EGLAPI EGLImageKHR egl_get_image_for_current_context(EGLImageKHR image);
+
 // ----------------------------------------------------------------------------
 }; // namespace android
 // ----------------------------------------------------------------------------
diff --git a/opengl/libs/gl_enums.in b/opengl/libs/gl_enums.in
deleted file mode 100644
index ffc2fad..0000000
--- a/opengl/libs/gl_enums.in
+++ /dev/null
@@ -1,261 +0,0 @@
-GLENUM(GL_POINTS, 0x0000)
-GLENUM(GL_LINES, 0x0001)
-GLENUM(GL_LINE_LOOP, 0x0002)
-GLENUM(GL_LINE_STRIP, 0x0003)
-GLENUM(GL_TRIANGLES, 0x0004)
-GLENUM(GL_TRIANGLE_STRIP, 0x0005)
-GLENUM(GL_TRIANGLE_FAN, 0x0006)
-GLENUM(GL_ADD, 0x0104)
-GLENUM(GL_NEVER, 0x0200)
-GLENUM(GL_LESS, 0x0201)
-GLENUM(GL_EQUAL, 0x0202)
-GLENUM(GL_LEQUAL, 0x0203)
-GLENUM(GL_GREATER, 0x0204)
-GLENUM(GL_NOTEQUAL, 0x0205)
-GLENUM(GL_GEQUAL, 0x0206)
-GLENUM(GL_ALWAYS, 0x0207)
-GLENUM(GL_SRC_COLOR, 0x0300)
-GLENUM(GL_ONE_MINUS_SRC_COLOR, 0x0301)
-GLENUM(GL_SRC_ALPHA, 0x0302)
-GLENUM(GL_ONE_MINUS_SRC_ALPHA, 0x0303)
-GLENUM(GL_DST_ALPHA, 0x0304)
-GLENUM(GL_ONE_MINUS_DST_ALPHA, 0x0305)
-GLENUM(GL_DST_COLOR, 0x0306)
-GLENUM(GL_ONE_MINUS_DST_COLOR, 0x0307)
-GLENUM(GL_SRC_ALPHA_SATURATE, 0x0308)
-GLENUM(GL_FRONT, 0x0404)
-GLENUM(GL_BACK, 0x0405)
-GLENUM(GL_FRONT_AND_BACK, 0x0408)
-GLENUM(GL_INVALID_ENUM, 0x0500)
-GLENUM(GL_INVALID_VALUE, 0x0501)
-GLENUM(GL_INVALID_OPERATION, 0x0502)
-GLENUM(GL_STACK_OVERFLOW, 0x0503)
-GLENUM(GL_STACK_UNDERFLOW, 0x0504)
-GLENUM(GL_OUT_OF_MEMORY, 0x0505)
-GLENUM(GL_EXP, 0x0800)
-GLENUM(GL_EXP2, 0x0801)
-GLENUM(GL_CW, 0x0900)
-GLENUM(GL_CCW, 0x0901)
-GLENUM(GL_POINT_SMOOTH, 0x0B10)
-GLENUM(GL_SMOOTH_POINT_SIZE_RANGE, 0x0B12)
-GLENUM(GL_LINE_SMOOTH, 0x0B20)
-GLENUM(GL_SMOOTH_LINE_WIDTH_RANGE, 0x0B22)
-GLENUM(GL_CULL_FACE, 0x0B44)
-GLENUM(GL_LIGHTING, 0x0B50)
-GLENUM(GL_LIGHT_MODEL_TWO_SIDE, 0x0B52)
-GLENUM(GL_LIGHT_MODEL_AMBIENT, 0x0B53)
-GLENUM(GL_COLOR_MATERIAL, 0x0B57)
-GLENUM(GL_FOG, 0x0B60)
-GLENUM(GL_FOG_DENSITY, 0x0B62)
-GLENUM(GL_FOG_START, 0x0B63)
-GLENUM(GL_FOG_END, 0x0B64)
-GLENUM(GL_FOG_MODE, 0x0B65)
-GLENUM(GL_FOG_COLOR, 0x0B66)
-GLENUM(GL_DEPTH_TEST, 0x0B71)
-GLENUM(GL_STENCIL_TEST, 0x0B90)
-GLENUM(GL_NORMALIZE, 0x0BA1)
-GLENUM(GL_ALPHA_TEST, 0x0BC0)
-GLENUM(GL_DITHER, 0x0BD0)
-GLENUM(GL_BLEND, 0x0BE2)
-GLENUM(GL_COLOR_LOGIC_OP, 0x0BF2)
-GLENUM(GL_SCISSOR_TEST, 0x0C11)
-GLENUM(GL_PERSPECTIVE_CORRECTION_HINT, 0x0C50)
-GLENUM(GL_POINT_SMOOTH_HINT, 0x0C51)
-GLENUM(GL_LINE_SMOOTH_HINT, 0x0C52)
-GLENUM(GL_POLYGON_SMOOTH_HINT, 0x0C53)
-GLENUM(GL_FOG_HINT, 0x0C54)
-GLENUM(GL_UNPACK_ALIGNMENT, 0x0CF5)
-GLENUM(GL_PACK_ALIGNMENT, 0x0D05)
-GLENUM(GL_MAX_LIGHTS, 0x0D31)
-GLENUM(GL_MAX_CLIP_PLANES, 0x0D32)
-GLENUM(GL_MAX_TEXTURE_SIZE, 0x0D33)
-GLENUM(GL_MAX_MODELVIEW_STACK_DEPTH, 0x0D36)
-GLENUM(GL_MAX_PROJECTION_STACK_DEPTH, 0x0D38)
-GLENUM(GL_MAX_TEXTURE_STACK_DEPTH, 0x0D39)
-GLENUM(GL_MAX_VIEWPORT_DIMS, 0x0D3A)
-GLENUM(GL_RED_BITS, 0x0D52)
-GLENUM(GL_GREEN_BITS, 0x0D53)
-GLENUM(GL_BLUE_BITS, 0x0D54)
-GLENUM(GL_ALPHA_BITS, 0x0D55)
-GLENUM(GL_DEPTH_BITS, 0x0D56)
-GLENUM(GL_STENCIL_BITS, 0x0D57)
-GLENUM(GL_TEXTURE_2D, 0x0DE1)
-GLENUM(GL_DONT_CARE, 0x1100)
-GLENUM(GL_FASTEST, 0x1101)
-GLENUM(GL_NICEST, 0x1102)
-GLENUM(GL_AMBIENT, 0x1200)
-GLENUM(GL_DIFFUSE, 0x1201)
-GLENUM(GL_SPECULAR, 0x1202)
-GLENUM(GL_POSITION, 0x1203)
-GLENUM(GL_SPOT_DIRECTION, 0x1204)
-GLENUM(GL_SPOT_EXPONENT, 0x1205)
-GLENUM(GL_SPOT_CUTOFF, 0x1206)
-GLENUM(GL_CONSTANT_ATTENUATION, 0x1207)
-GLENUM(GL_LINEAR_ATTENUATION, 0x1208)
-GLENUM(GL_QUADRATIC_ATTENUATION, 0x1209)
-GLENUM(GL_BYTE, 0x1400)
-GLENUM(GL_UNSIGNED_BYTE, 0x1401)
-GLENUM(GL_SHORT, 0x1402)
-GLENUM(GL_UNSIGNED_SHORT, 0x1403)
-GLENUM(GL_FLOAT, 0x1406)
-GLENUM(GL_FIXED, 0x140C)
-GLENUM(GL_CLEAR, 0x1500)
-GLENUM(GL_AND, 0x1501)
-GLENUM(GL_AND_REVERSE, 0x1502)
-GLENUM(GL_COPY, 0x1503)
-GLENUM(GL_AND_INVERTED, 0x1504)
-GLENUM(GL_NOOP, 0x1505)
-GLENUM(GL_XOR, 0x1506)
-GLENUM(GL_OR, 0x1507)
-GLENUM(GL_NOR, 0x1508)
-GLENUM(GL_EQUIV, 0x1509)
-GLENUM(GL_INVERT, 0x150A)
-GLENUM(GL_OR_REVERSE, 0x150B)
-GLENUM(GL_COPY_INVERTED, 0x150C)
-GLENUM(GL_OR_INVERTED, 0x150D)
-GLENUM(GL_NAND, 0x150E)
-GLENUM(GL_SET, 0x150F)
-GLENUM(GL_EMISSION, 0x1600)
-GLENUM(GL_SHININESS, 0x1601)
-GLENUM(GL_AMBIENT_AND_DIFFUSE, 0x1602)
-GLENUM(GL_MODELVIEW, 0x1700)
-GLENUM(GL_PROJECTION, 0x1701)
-GLENUM(GL_TEXTURE, 0x1702)
-GLENUM(GL_ALPHA, 0x1906)
-GLENUM(GL_RGB, 0x1907)
-GLENUM(GL_RGBA, 0x1908)
-GLENUM(GL_LUMINANCE, 0x1909)
-GLENUM(GL_LUMINANCE_ALPHA, 0x190A)
-GLENUM(GL_FLAT, 0x1D00)
-GLENUM(GL_SMOOTH, 0x1D01)
-GLENUM(GL_KEEP, 0x1E00)
-GLENUM(GL_REPLACE, 0x1E01)
-GLENUM(GL_REPLACE, 0x1E01)
-GLENUM(GL_INCR, 0x1E02)
-GLENUM(GL_DECR, 0x1E03)
-GLENUM(GL_VENDOR, 0x1F00)
-GLENUM(GL_RENDERER, 0x1F01)
-GLENUM(GL_VERSION, 0x1F02)
-GLENUM(GL_EXTENSIONS, 0x1F03)
-GLENUM(GL_MODULATE, 0x2100)
-GLENUM(GL_DECAL, 0x2101)
-GLENUM(GL_TEXTURE_ENV_MODE, 0x2200)
-GLENUM(GL_TEXTURE_ENV_COLOR, 0x2201)
-GLENUM(GL_TEXTURE_ENV, 0x2300)
-GLENUM(GL_NEAREST, 0x2600)
-GLENUM(GL_LINEAR, 0x2601)
-GLENUM(GL_NEAREST_MIPMAP_NEAREST, 0x2700)
-GLENUM(GL_LINEAR_MIPMAP_NEAREST, 0x2701)
-GLENUM(GL_NEAREST_MIPMAP_LINEAR, 0x2702)
-GLENUM(GL_LINEAR_MIPMAP_LINEAR, 0x2703)
-GLENUM(GL_TEXTURE_MAG_FILTER, 0x2800)
-GLENUM(GL_TEXTURE_MIN_FILTER, 0x2801)
-GLENUM(GL_TEXTURE_WRAP_S, 0x2802)
-GLENUM(GL_TEXTURE_WRAP_T, 0x2803)
-GLENUM(GL_CLAMP, 0x2900)
-GLENUM(GL_REPEAT, 0x2901)
-GLENUM(GL_CLIP_PLANE0, 0x3000)
-GLENUM(GL_CLIP_PLANE1, 0x3001)
-GLENUM(GL_CLIP_PLANE2, 0x3002)
-GLENUM(GL_CLIP_PLANE3, 0x3003)
-GLENUM(GL_CLIP_PLANE4, 0x3004)
-GLENUM(GL_CLIP_PLANE5, 0x3005)
-GLENUM(GL_LIGHT0, 0x4000)
-GLENUM(GL_LIGHT1, 0x4001)
-GLENUM(GL_LIGHT2, 0x4002)
-GLENUM(GL_LIGHT3, 0x4003)
-GLENUM(GL_LIGHT4, 0x4004)
-GLENUM(GL_LIGHT5, 0x4005)
-GLENUM(GL_LIGHT6, 0x4006)
-GLENUM(GL_LIGHT7, 0x4007)
-GLENUM(GL_DIRECT_TEXTURE_2D_QUALCOMM, 0x7E80)
-GLENUM(GL_UNSIGNED_SHORT_4_4_4_4, 0x8033)
-GLENUM(GL_UNSIGNED_SHORT_5_5_5_1, 0x8034)
-GLENUM(GL_POLYGON_OFFSET_FILL, 0x8037)
-GLENUM(GL_RESCALE_NORMAL, 0x803A)
-GLENUM(GL_VERTEX_ARRAY, 0x8074)
-GLENUM(GL_NORMAL_ARRAY, 0x8075)
-GLENUM(GL_COLOR_ARRAY, 0x8076)
-GLENUM(GL_TEXTURE_COORD_ARRAY, 0x8078)
-GLENUM(GL_MULTISAMPLE, 0x809D)
-GLENUM(GL_SAMPLE_ALPHA_TO_COVERAGE, 0x809E)
-GLENUM(GL_SAMPLE_ALPHA_TO_ONE, 0x809F)
-GLENUM(GL_SAMPLE_COVERAGE, 0x80A0)
-GLENUM(GL_MAX_ELEMENTS_VERTICES, 0x80E8)
-GLENUM(GL_MAX_ELEMENTS_INDICES, 0x80E9)
-GLENUM(GL_CLAMP_TO_EDGE, 0x812F)
-GLENUM(GL_GENERATE_MIPMAP, 0x8191)
-GLENUM(GL_GENERATE_MIPMAP_HINT, 0x8192)
-GLENUM(GL_UNSIGNED_SHORT_5_6_5, 0x8363)
-GLENUM(GL_ALIASED_POINT_SIZE_RANGE, 0x846D)
-GLENUM(GL_ALIASED_LINE_WIDTH_RANGE, 0x846E)
-GLENUM(GL_TEXTURE0, 0x84C0)
-GLENUM(GL_TEXTURE1, 0x84C1)
-GLENUM(GL_TEXTURE2, 0x84C2)
-GLENUM(GL_TEXTURE3, 0x84C3)
-GLENUM(GL_TEXTURE4, 0x84C4)
-GLENUM(GL_TEXTURE5, 0x84C5)
-GLENUM(GL_TEXTURE6, 0x84C6)
-GLENUM(GL_TEXTURE7, 0x84C7)
-GLENUM(GL_TEXTURE8, 0x84C8)
-GLENUM(GL_TEXTURE9, 0x84C9)
-GLENUM(GL_TEXTURE10, 0x84CA)
-GLENUM(GL_TEXTURE11, 0x84CB)
-GLENUM(GL_TEXTURE12, 0x84CC)
-GLENUM(GL_TEXTURE13, 0x84CD)
-GLENUM(GL_TEXTURE14, 0x84CE)
-GLENUM(GL_TEXTURE15, 0x84CF)
-GLENUM(GL_TEXTURE16, 0x84D0)
-GLENUM(GL_TEXTURE17, 0x84D1)
-GLENUM(GL_TEXTURE18, 0x84D2)
-GLENUM(GL_TEXTURE19, 0x84D3)
-GLENUM(GL_TEXTURE20, 0x84D4)
-GLENUM(GL_TEXTURE21, 0x84D5)
-GLENUM(GL_TEXTURE22, 0x84D6)
-GLENUM(GL_TEXTURE23, 0x84D7)
-GLENUM(GL_TEXTURE24, 0x84D8)
-GLENUM(GL_TEXTURE25, 0x84D9)
-GLENUM(GL_TEXTURE26, 0x84DA)
-GLENUM(GL_TEXTURE27, 0x84DB)
-GLENUM(GL_TEXTURE28, 0x84DC)
-GLENUM(GL_TEXTURE29, 0x84DD)
-GLENUM(GL_TEXTURE30, 0x84DE)
-GLENUM(GL_TEXTURE31, 0x84DF)
-GLENUM(GL_MAX_TEXTURE_UNITS, 0x84E2)
-GLENUM(GL_NUM_COMPRESSED_TEXTURE_FORMATS, 0x86A2)
-GLENUM(GL_COMPRESSED_TEXTURE_FORMATS, 0x86A3)
-GLENUM(GL_BUFFER_SIZE, 0x8764)
-GLENUM(GL_BUFFER_USAGE, 0x8765)
-GLENUM(GL_POINT_SPRITE_OES, 0x8861)
-GLENUM(GL_COORD_REPLACE_OES, 0x8862)
-GLENUM(GL_ARRAY_BUFFER, 0x8892)
-GLENUM(GL_ELEMENT_ARRAY_BUFFER, 0x8893)
-GLENUM(GL_ARRAY_BUFFER_BINDING, 0x8894)
-GLENUM(GL_ELEMENT_ARRAY_BUFFER_BINDING, 0x8895)
-GLENUM(GL_VERTEX_ARRAY_BUFFER_BINDING, 0x8896)
-GLENUM(GL_NORMAL_ARRAY_BUFFER_BINDING, 0x8897)
-GLENUM(GL_COLOR_ARRAY_BUFFER_BINDING, 0x8898)
-GLENUM(GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING, 0x889A)
-GLENUM(GL_STATIC_DRAW, 0x88E4)
-GLENUM(GL_DYNAMIC_DRAW, 0x88E8)
-GLENUM(GL_POINT_SIZE_ARRAY_TYPE_OES, 0x898A)
-GLENUM(GL_POINT_SIZE_ARRAY_STRIDE_OES, 0x898B)
-GLENUM(GL_POINT_SIZE_ARRAY_POINTER_OES, 0x898C)
-GLENUM(GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES, 0x898D)
-GLENUM(GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES, 0x898E)
-GLENUM(GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES, 0x898F)
-GLENUM(GL_PALETTE4_RGB8_OES, 0x8B90)
-GLENUM(GL_PALETTE4_RGBA8_OES, 0x8B91)
-GLENUM(GL_PALETTE4_R5_G6_B5_OES, 0x8B92)
-GLENUM(GL_PALETTE4_RGBA4_OES, 0x8B93)
-GLENUM(GL_PALETTE4_RGB5_A1_OES, 0x8B94)
-GLENUM(GL_PALETTE8_RGB8_OES, 0x8B95)
-GLENUM(GL_PALETTE8_RGBA8_OES, 0x8B96)
-GLENUM(GL_PALETTE8_R5_G6_B5_OES, 0x8B97)
-GLENUM(GL_PALETTE8_RGBA4_OES, 0x8B98)
-GLENUM(GL_PALETTE8_RGB5_A1_OES, 0x8B99)
-GLENUM(GL_IMPLEMENTATION_COLOR_READ_TYPE_OES, 0x8B9A)
-GLENUM(GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES, 0x8B9B)
-GLENUM(GL_POINT_SIZE_ARRAY_OES, 0x8B9C)
-GLENUM(GL_TEXTURE_CROP_RECT_OES, 0x8B9D)
-GLENUM(GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES, 0x8B9F)
diff --git a/opengl/libs/hooks.h b/opengl/libs/hooks.h
index fd97254..37292ee 100644
--- a/opengl/libs/hooks.h
+++ b/opengl/libs/hooks.h
@@ -21,10 +21,14 @@
 #include <string.h>
 #include <errno.h>
 
+#include <pthread.h>
+
 #include <EGL/egl.h>
 #include <EGL/eglext.h>
 #include <GLES/gl.h>
 #include <GLES/glext.h>
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
 
 #if !defined(__arm__)
 #define USE_SLOW_BINDING            1
@@ -76,11 +80,15 @@
 
 struct gl_hooks_t {
     struct gl_t {
-        #include "gl_entries.in"
-        #include "glext_entries.in"
+        #include "GLES_CM/gl_entries.in"
+        #include "GLES_CM/glext_entries.in"
     } gl;
+    struct gl2_t {
+        #include "GLES2/gl2_entries.in"
+        #include "GLES2/gl2ext_entries.in"
+    } gl2;
     struct egl_t {
-        #include "egl_entries.in"
+        #include "EGL/egl_entries.in"
     } egl;
     struct gl_ext_t {
         void (*extensions[MAX_NUMBER_OF_GL_EXTENSIONS])(void);
@@ -94,6 +102,13 @@
 
 extern gl_hooks_t gHooks[IMPL_NUM_IMPLEMENTATIONS];
 extern pthread_key_t gGLWrapperKey;
+extern "C" void gl_unimplemented();
+
+extern char const * const gl_names[];
+extern char const * const gl2_names[];
+extern char const * const egl_names[];
+
+// ----------------------------------------------------------------------------
 
 #if USE_FAST_TLS_KEY
 
diff --git a/opengl/libs/tools/enumextract.sh b/opengl/libs/tools/enumextract.sh
deleted file mode 100644
index 5707302..0000000
--- a/opengl/libs/tools/enumextract.sh
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/bin/sh
-
-awk '
-/^#define GL_/ {
-    names[count] = $2;
-    values[count] = $3;
-    sort[count] = $3 + 0;
-    count++;
-}
-END {
-    for (i = 1; i < count; i++) {
-        for (j = 0; j < i; j++) {
-            if (sort[i] < sort[j]) {
-                tn = names[i];
-                tv = values[i];
-                ts = sort[i];
-                names[i] = names[j];
-                values[i] = values[j];
-                sort[i] = sort[j];
-                names[j] = tn;
-                values[j] = tv;
-                sort[j] = ts;
-            }
-        }
-    }
- 
-    for (i = 0; i < count; i++) {
-        printf("GLENUM(%s, %s)\n", names[i], values[i]);
-    }
-}
-' < $1
-
diff --git a/opengl/libs/tools/genfiles b/opengl/libs/tools/genfiles
index 107768b..4f8eda4 100755
--- a/opengl/libs/tools/genfiles
+++ b/opengl/libs/tools/genfiles
@@ -15,6 +15,13 @@
 # limitations under the License.
 
 ./glapigen ../../include/GLES/gl.h > ../GLES_CM/gl_api.in 
-./glentrygen ../../include/GLES/gl.h > ../gl_entries.in 
+./glentrygen ../../include/GLES/gl.h > ../GLES_CM/gl_entries.in 
+
 ./glapigen ../../include/GLES/glext.h > ../GLES_CM/glext_api.in 
-./glentrygen ../../include/GLES/glext.h > ../glext_entries.in 
+./glentrygen ../../include/GLES/glext.h > ../GLES_CM/glext_entries.in 
+
+./glapigen ../../include/GLES2/gl2.h > ../GLES2/gl2_api.in 
+./glentrygen ../../include/GLES2/gl2.h > ../GLES2/gl2_entries.in 
+
+./glapigen ../../include/GLES2/gl2ext.h > ../GLES2/gl2ext_api.in 
+./glentrygen ../../include/GLES2/gl2ext.h > ../GLES2/gl2ext_entries.in 
diff --git a/opengl/libs/tools/glapigen b/opengl/libs/tools/glapigen
index a2c3a7b..bd8dda3 100755
--- a/opengl/libs/tools/glapigen
+++ b/opengl/libs/tools/glapigen
@@ -16,16 +16,23 @@
 
 use strict;
 
+sub rtrim($)
+{
+    my $string = shift;
+    $string =~ s/\s+$//;
+    return $string;
+}
+
 while (my $line = <>) {
   next if $line =~ /^\//;
   next if $line =~ /^#/;
   next if $line =~ /^\s*$/;
-  if ($line !~ /^GL_API\s+(.+)\s+GL_APIENTRY\s+([\w]+)\s*\(([^\)]+)\);/) {
+  if ($line !~ /^GL_API(CALL)?\s+(.+)\s+GL_APIENTRY\s+([\w]+)\s*\(([^\)]+)\);/) {
     next;
   }
-  my $type = $1;
-  my $name = $2;
-  my $args = $3;
+  my $type = rtrim($2);
+  my $name = $3;
+  my $args = $4;
 
   #printf("%s", $line);
   
diff --git a/opengl/libs/tools/glentrygen b/opengl/libs/tools/glentrygen
index 5e0f7b6..170f041 100755
--- a/opengl/libs/tools/glentrygen
+++ b/opengl/libs/tools/glentrygen
@@ -16,16 +16,23 @@
 
 use strict;
 
+sub rtrim($)
+{
+    my $string = shift;
+    $string =~ s/\s+$//;
+    return $string;
+}
+
 while (my $line = <>) {
   next if $line =~ /^\//;
   next if $line =~ /^#/;
   next if $line =~ /^\s*$/;
-  if ($line !~ /^GL_API\s+(.+)\s+GL_APIENTRY\s+([\w]+)\s*\(([^\)]+)\);/) {
+  if ($line !~ /^GL_API(CALL)?\s+(.+)\s+GL_APIENTRY\s+([\w]+)\s*\(([^\)]+)\);/) {
     next;
   }
-  my $type = $1;
-  my $name = $2;
-  my $args = $3;
+  my $type = rtrim($2);
+  my $name = $3;
+  my $args = $4;
 
   printf("GL_ENTRY(%s, %s, %s)\n", $type, $name, $args);
 }
diff --git a/opengl/tests/copybits/Android.mk b/opengl/tests/copybits/Android.mk
new file mode 100644
index 0000000..d5ded42
--- /dev/null
+++ b/opengl/tests/copybits/Android.mk
@@ -0,0 +1,18 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+	copybits.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+	libcutils \
+    libEGL \
+    libGLESv1_CM \
+    libui
+
+LOCAL_MODULE:= test-opengl-copybits
+
+LOCAL_MODULE_TAGS := tests
+
+include $(BUILD_EXECUTABLE)
+
diff --git a/opengl/tests/copybits/copybits.cpp b/opengl/tests/copybits/copybits.cpp
new file mode 100644
index 0000000..f8ca9b2
--- /dev/null
+++ b/opengl/tests/copybits/copybits.cpp
@@ -0,0 +1,722 @@
+// Test software OpenGL hardware accelleration using copybits.
+
+#define LOG_TAG "copybits_test"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <sys/types.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/time.h>
+
+#include <ui/PixelFormat.h>
+
+#include <cutils/log.h>
+#include <cutils/native_handle.h>
+
+#include <utils/Atomic.h>
+
+#include <private/ui/SurfaceBuffer.h>
+#include <pixelflinger/pixelflinger.h>
+
+#include <hardware/gralloc.h>
+#include <hardware/hardware.h>
+
+#define EGL_EGLEXT_PROTOTYPES
+#define GL_GLEXT_PROTOTYPES
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+
+extern "C" EGLNativeWindowType android_createDisplaySurface(void);
+
+using namespace android;
+
+EGLDisplay eglDisplay;
+EGLSurface eglSurface;
+EGLContext eglContext;
+GLuint texture;
+
+hw_module_t const* gralloc_module;
+alloc_device_t  *sAllocDev;
+
+#define FIXED_ONE 0x10000 /* 1.0 in 16.16 fixed point. */
+
+int init_gl_surface();
+void free_gl_surface();
+void init_scene();
+
+int create_physical_texture();
+int readTimer();
+
+// ===========================================================================
+// Buffer an implementation of android_native_buffer_t
+// ===========================================================================
+
+class NativeBuffer;
+
+class Buffer : public android::SurfaceBuffer
+{
+public:
+    // creates w * h buffer
+    Buffer(uint32_t w, uint32_t h, PixelFormat format, uint32_t usage);
+
+    // return status
+    status_t initCheck() const;
+
+    uint32_t getWidth() const           { return width; }
+    uint32_t getHeight() const          { return height; }
+    uint32_t getStride() const          { return stride; }
+    uint32_t getUsage() const           { return usage; }
+    PixelFormat getPixelFormat() const  { return format; }
+    
+    
+    android_native_buffer_t* getNativeBuffer() const;
+
+    void setPixel(int x, int y, int r, int g, int b, int a);
+
+    status_t lock(GGLSurface* surface, uint32_t usage);
+    void lock() {
+        GGLSurface s;
+        lock(&s, GRALLOC_USAGE_SW_WRITE_OFTEN);
+        mData = (void*)s.data;
+    }
+
+private:
+    friend class LightRefBase<Buffer>;
+    Buffer(const Buffer& rhs);
+    virtual ~Buffer();
+    Buffer& operator = (const Buffer& rhs);
+    const Buffer& operator = (const Buffer& rhs) const;
+
+    status_t initSize(uint32_t w, uint32_t h);
+
+    ssize_t                 mInitCheck;
+    void*                   mData;
+};
+
+Buffer::Buffer(uint32_t w, uint32_t h, PixelFormat format, uint32_t usage)
+    : SurfaceBuffer(), mInitCheck(NO_INIT)
+{
+    this->usage = usage;
+    this->format = format;
+    if (w>0 && h>0) {
+        mInitCheck = initSize(w, h);
+    }
+}
+
+Buffer::~Buffer()
+{
+    if (handle) {
+        sAllocDev->free(sAllocDev, handle);
+    }
+}
+
+status_t Buffer::initCheck() const {
+    return mInitCheck;
+}
+
+android_native_buffer_t* Buffer::getNativeBuffer() const
+{
+    return static_cast<android_native_buffer_t*>(const_cast<Buffer*>(this));
+}
+
+status_t Buffer::initSize(uint32_t w, uint32_t h)
+{
+    status_t err = NO_ERROR;
+
+    err = sAllocDev->alloc(sAllocDev, w, h, format, usage, &handle, &stride);
+    
+    if (err == NO_ERROR) {
+        if (err == NO_ERROR) {
+            width  = w;
+            height = h;
+        }
+    }
+
+    return err;
+}
+
+status_t Buffer::lock(GGLSurface* sur, uint32_t usage) 
+{
+    void* vaddr;
+    status_t res = SurfaceBuffer::lock(usage, &vaddr);
+    if (res == NO_ERROR && sur) {
+        sur->version = sizeof(GGLSurface);
+        sur->width = width;
+        sur->height = height;
+        sur->stride = stride;
+        sur->format = format;
+        sur->data = static_cast<GGLubyte*>(vaddr);
+    }
+    return res;
+}
+
+
+void Buffer::setPixel(int x, int y, int r, int g, int b, int a) {
+    if (x < 0 || (unsigned int) x >= width
+            || y < 0 || (unsigned int) y >= height) {
+        // clipped
+        return;
+    }
+    int index = stride * y + x;
+    switch (format) {
+    case HAL_PIXEL_FORMAT_RGB_565: {
+            unsigned short val = (unsigned short) (
+                    ((0x1f & (r >> 3)) << 11)
+                    | ((0x3f & (g >> 2)) << 5)
+                    | (0x1f & (b >> 3)));
+            ((unsigned short*) mData)[index]= val;
+        }
+        break;
+    case HAL_PIXEL_FORMAT_RGBA_8888: { // ABGR
+        unsigned int val = (unsigned int)
+            (((a & 0xff) << 24)
+                    | ((b & 0xff) << 16)
+                    | ((g & 0xff) << 8)
+                    | (r & 0xff));
+            ((unsigned int*) mData)[index] = val;
+        }
+        break;
+    default:
+        // Unsupported pixel format
+        break;
+    }
+}
+
+
+static void gluLookAt(float eyeX, float eyeY, float eyeZ,
+        float centerX, float centerY, float centerZ, float upX, float upY,
+        float upZ)
+{
+    // See the OpenGL GLUT documentation for gluLookAt for a description
+    // of the algorithm. We implement it in a straightforward way:
+
+    float fx = centerX - eyeX;
+    float fy = centerY - eyeY;
+    float fz = centerZ - eyeZ;
+
+    // Normalize f
+    float rlf = 1.0f / sqrtf(fx*fx + fy*fy + fz*fz);
+    fx *= rlf;
+    fy *= rlf;
+    fz *= rlf;
+
+    // Normalize up
+    float rlup = 1.0f / sqrtf(upX*upX + upY*upY + upZ*upZ);
+    upX *= rlup;
+    upY *= rlup;
+    upZ *= rlup;
+
+    // compute s = f x up (x means "cross product")
+
+    float sx = fy * upZ - fz * upY;
+    float sy = fz * upX - fx * upZ;
+    float sz = fx * upY - fy * upX;
+
+    // compute u = s x f
+    float ux = sy * fz - sz * fy;
+    float uy = sz * fx - sx * fz;
+    float uz = sx * fy - sy * fx;
+
+    float m[16] ;
+    m[0] = sx;
+    m[1] = ux;
+    m[2] = -fx;
+    m[3] = 0.0f;
+
+    m[4] = sy;
+    m[5] = uy;
+    m[6] = -fy;
+    m[7] = 0.0f;
+
+    m[8] = sz;
+    m[9] = uz;
+    m[10] = -fz;
+    m[11] = 0.0f;
+
+    m[12] = 0.0f;
+    m[13] = 0.0f;
+    m[14] = 0.0f;
+    m[15] = 1.0f;
+
+    glMultMatrixf(m);
+    glTranslatef(-eyeX, -eyeY, -eyeZ);
+}
+
+int init_gralloc() {
+    int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &gralloc_module);
+    LOGE_IF(err, "FATAL: can't find the %s module", GRALLOC_HARDWARE_MODULE_ID);
+
+    if (err == 0) {
+        gralloc_open(gralloc_module, &sAllocDev);
+    }
+    return err;
+}
+
+int init_gl_surface(void)
+{
+    EGLint numConfigs = 1;
+    EGLConfig myConfig = {0};
+    EGLint attrib[] =
+    {
+            EGL_DEPTH_SIZE,     16,
+            EGL_NONE
+    };
+
+    printf("init_gl_surface\n");
+    if ( (eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY)) == EGL_NO_DISPLAY )
+    {
+        printf("eglGetDisplay failed\n");
+        return 0;
+    }
+
+    if ( eglInitialize(eglDisplay, NULL, NULL) != EGL_TRUE )
+    {
+        printf("eglInitialize failed\n");
+        return 0;
+    }
+
+    if ( eglChooseConfig(eglDisplay, attrib, &myConfig, 1, &numConfigs) != EGL_TRUE )
+    {
+        printf("eglChooseConfig failed\n");
+        return 0;
+    }
+
+    if ( (eglSurface = eglCreateWindowSurface(eglDisplay, myConfig,
+            android_createDisplaySurface(), 0)) == EGL_NO_SURFACE )
+    {
+        printf("eglCreateWindowSurface failed\n");
+        return 0;
+    }
+
+    if ( (eglContext = eglCreateContext(eglDisplay, myConfig, 0, 0)) == EGL_NO_CONTEXT )
+    {
+        printf("eglCreateContext failed\n");
+        return 0;
+    }
+
+    if ( eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext) != EGL_TRUE )
+    {
+        printf("eglMakeCurrent failed\n");
+        return 0;
+    }
+
+#if EGL_ANDROID_swap_rectangle
+    eglSetSwapRectangleANDROID(eglDisplay, eglSurface, 0, 0, 320, 480);
+#endif
+    
+    return 1;
+}
+
+void free_gl_surface(void)
+{
+    if (eglDisplay != EGL_NO_DISPLAY)
+    {
+        eglMakeCurrent( eglDisplay, EGL_NO_SURFACE,
+                EGL_NO_SURFACE, EGL_NO_CONTEXT );
+        eglDestroyContext( eglDisplay, eglContext );
+        eglDestroySurface( eglDisplay, eglSurface );
+        eglTerminate( eglDisplay );
+        eglDisplay = EGL_NO_DISPLAY;
+    }
+}
+
+void init_scene(void)
+{
+    glDisable(GL_DITHER);
+    glEnable(GL_CULL_FACE);
+    float ratio = 320.0f /  480.0f;
+    glViewport(0, 0, 320, 480);
+
+    glMatrixMode(GL_PROJECTION);
+    glLoadIdentity();
+    glFrustumf(-ratio, ratio, -1, 1, 1, 10);
+
+    glMatrixMode(GL_MODELVIEW);
+
+    glLoadIdentity();
+    gluLookAt(
+            0, 0, 3,  // eye
+            0, 0, 0,  // center
+            0, 1, 0); // up
+
+    glEnable(GL_TEXTURE_2D);
+}
+
+// #define USE_ALPHA_COLOR
+
+#define USE_GL_REPLACE
+//#define USE_GL_MODULATE
+
+// #define USE_BLEND
+
+#define USE_565
+// #define USE_8888
+
+// #define USE_NEAREST
+#define USE_LINEAR
+
+#define USE_SCALE
+
+void setSmoothGradient(Buffer* bufferObject) {
+    int pixels = bufferObject->getHeight() * bufferObject->getWidth();
+    int step = 0;
+    for (unsigned int y = 0; y < bufferObject->getHeight(); y++) {
+        for(unsigned int x = 0; x < bufferObject->getWidth() ; x++) {
+            int grey = step * 255 / pixels;
+            bufferObject->setPixel(x, y, grey, grey, grey, 255);
+            ++step;
+        }
+    }
+}
+
+void setSmoothAlphaGradient(Buffer* bufferObject) {
+    int pixels = bufferObject->getHeight() * bufferObject->getWidth();
+    int step = 0;
+    for (unsigned int y = 0; y < bufferObject->getHeight(); y++) {
+        for(unsigned int x = 0; x < bufferObject->getWidth() ; x++) {
+            int grey = step * 255 / pixels;
+            bufferObject->setPixel(x, y, 255, 255, 255, grey);
+            ++step;
+        }
+    }
+}
+
+void setOrientedCheckerboard(Buffer* bufferObject) {
+    bufferObject->setPixel(0, 0, 0, 0, 0, 255);
+    for(unsigned int x = 1; x < bufferObject->getWidth() ; x++) {
+        bufferObject->setPixel(x, 0, 0, 255, 0, 255);
+    }
+    for (unsigned int y = 1; y < bufferObject->getHeight(); y++) {
+        for(unsigned int x = 0; x < bufferObject->getWidth() ; x++) {
+            if ((x ^ y ) & 1) {
+                bufferObject->setPixel(x, y, 255, 255, 255, 255);
+            } else {
+                bufferObject->setPixel(x, y, 255, 0, 0, 255);
+            }
+        }
+    }
+}
+
+int create_physical_texture(unsigned int w, unsigned int h)
+{
+
+#ifdef USE_565
+    PixelFormat format = HAL_PIXEL_FORMAT_RGB_565;
+#else
+    PixelFormat format = HAL_PIXEL_FORMAT_RGBA_8888;
+#endif
+    int usage = GRALLOC_USAGE_SW_READ_OFTEN |
+        GRALLOC_USAGE_SW_WRITE_OFTEN |
+        GRALLOC_USAGE_HW_TEXTURE |
+        GRALLOC_USAGE_HW_2D; /* This is the key to allocating the texture in pmem. */
+    int32_t stride;
+    buffer_handle_t handle;
+
+    // Allocate the hardware buffer
+    Buffer* bufferObject = new Buffer(w, h, format, usage);
+
+    android_native_buffer_t* buffer = bufferObject->getNativeBuffer();
+
+    buffer->common.incRef(&buffer->common);
+
+    // create the new EGLImageKHR
+    EGLint attrs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_NONE };
+    EGLDisplay dpy = eglGetCurrentDisplay();
+    EGLImageKHR image = eglCreateImageKHR(dpy, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
+            (EGLClientBuffer)buffer, attrs);
+    if (image == EGL_NO_IMAGE_KHR) {
+        printf("Could not create an image %d\n", eglGetError());
+        return -1;
+    }
+
+    bufferObject->lock();
+    setOrientedCheckerboard(bufferObject);
+    // setSmoothGradient(bufferObject);
+    // setSmoothAlphaGradient(bufferObject);
+    bufferObject->unlock();
+
+    glGenTextures(1, &texture);
+    glBindTexture(GL_TEXTURE_2D, texture);
+    glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image);
+#ifdef USE_LINEAR
+    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+#elif defined(USE_NEAREST)
+    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+#endif
+
+#ifdef USE_GL_REPLACE
+    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+#elif defined(USE_GL_MODULATE)
+    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+#endif
+
+#ifdef USE_ALPHA_COLOR
+    glColor4f(1.0f, 1.0f, 1.0f, 0.4f);
+#else
+    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
+#endif
+
+#ifdef USE_BLEND
+    glEnable(GL_BLEND);
+    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+#endif
+    return 0;
+}
+
+static const int SCALE_COUNT = 12;
+
+int scale(int base, int factor) {
+    static const float kTable[SCALE_COUNT] = {
+            0.24f, 0.25f, 0.5f, 0.75f, 1.0f,
+            1.5f, 2.0f, 2.5f, 3.0f, 3.5f, 4.0f, 5.0f
+    };
+    return base * kTable[factor];
+}
+
+class Timer {
+    struct timeval  first;
+    double elapsedSeconds;
+
+public:
+    Timer() {}
+    void start() {
+        gettimeofday(&first, NULL);
+    }
+
+    void stop() {
+        struct timeval  second,
+                        elapsed;
+        gettimeofday(&second, NULL);
+
+        if (first.tv_usec > second.tv_usec) {
+           second.tv_usec += 1000000;
+           second.tv_sec--;
+        }
+
+        elapsedSeconds = (second.tv_sec  - first.tv_sec) +
+            (second.tv_usec - first.tv_usec) / 1000000.0;
+    }
+
+    double getElapsedSeconds() {
+        return elapsedSeconds;
+    }
+
+    double getElapsedMs() {
+        return elapsedSeconds* 1000.0f;
+    }
+};
+
+int testTime()
+{
+    static const int WIDTH = 320;
+    static const int HEIGHT = 480;
+    static const int SCALE = 8;
+
+    if (create_physical_texture(WIDTH, HEIGHT) != 0) {
+        return -1;
+    }
+    // Need to do a dummy eglSwapBuffers first. Don't know why.
+    glClearColor(0.4, 1.0, 0.4, 0.4);
+    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
+    eglSwapBuffers(eglDisplay, eglSurface);
+
+    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
+
+#if defined(USE_SCALE)
+    static const int scaleOffset = 0;
+#else
+    static const int scaleOffset = 1;
+#endif
+    printf("ms\n");
+    for(int j = 0; j < SCALE; j++) {
+        int w = WIDTH >> (j + scaleOffset);
+        int h = HEIGHT >> j;
+        int cropRect[4] = {0,h,w,-h}; // Left bottom width height. Width and Height can be neg to flip.
+        glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, cropRect);
+        Timer timer;
+        timer.start();
+
+        int copyCount = 1000;
+        for (int i = 0; i < copyCount; i++) {
+            glDrawTexiOES(0, 0, 0, w, h);
+        }
+
+        timer.stop();
+        printf("%g\n", timer.getElapsedMs() / copyCount);
+    }
+
+    eglSwapBuffers(eglDisplay, eglSurface);
+    return 0;
+}
+
+int testStretch()
+{
+    static const int WIDTH = 8;
+    static const int HEIGHT = 8;
+
+    if (create_physical_texture(WIDTH, HEIGHT) != 0) {
+        return -1;
+    }
+    // Need to do a dummy eglSwapBuffers first. Don't know why.
+    glClearColor(0.4, 1.0, 0.4, 1.0);
+    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
+    eglSwapBuffers(eglDisplay, eglSurface);
+    
+    int cropRect[4] = {0,HEIGHT,WIDTH,-HEIGHT}; // Left bottom width height. Width and Height can be neg to flip.
+    glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, cropRect);
+
+    for(int frame = 0; frame < 2; frame++) {
+        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
+        int baseX = 10;
+        for (int x = 0; x < SCALE_COUNT; x++) {
+            int baseY = 10;
+            int width = scale(WIDTH, x);
+            for (int y = 0; y < SCALE_COUNT; y++) {
+                int height = scale(HEIGHT, y);
+                glDrawTexxOES(baseX << 16, baseY << 16, 0, width << 16, height << 16);
+                baseY += height + 10;
+            }
+            baseX += width + 10;
+        }
+
+        eglSwapBuffers(eglDisplay, eglSurface);
+        LOGD("wait 1s");
+        usleep(1000000);
+    }
+    return 0;
+}
+
+int testRot90()
+{
+    static const int WIDTH = 8;
+    static const int HEIGHT = 8;
+
+    if (create_physical_texture(WIDTH, HEIGHT) != 0) {
+        return -1;
+    }
+
+    glMatrixMode(GL_PROJECTION);
+    glLoadIdentity();
+    glOrthof(0, 320, 480, 0, 0, 1);
+
+    glMatrixMode(GL_MODELVIEW);
+
+    glLoadIdentity();
+
+    // Need to do a dummy eglSwapBuffers first. Don't know why.
+    glClearColor(0.4, 0.4, 0.4, 0.4);
+    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
+    eglSwapBuffers(eglDisplay, eglSurface);
+
+    glEnable(GL_TEXTURE_2D);
+    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
+    glDisable(GL_BLEND);
+    glShadeModel(GL_FLAT);
+    glDisable(GL_DITHER);
+    glDisable(GL_CULL_FACE);
+
+    for(int frame = 0; frame < 2; frame++) {
+        LOGD("frame = %d", frame);
+        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
+        int baseX = 10;
+        for (int x = 0; x < SCALE_COUNT; x++) {
+            int baseY = 10;
+            int width = scale(WIDTH, x);
+            for (int y = 0; y < SCALE_COUNT; y++) {
+                int height = scale(HEIGHT, y);
+
+                // Code copied from SurfaceFlinger LayerBase.cpp
+
+                const GLfixed texCoords[4][2] = {
+                        { 0,        0 },
+                        { 0,        0x10000 },
+                        { 0x10000,  0x10000 },
+                        { 0x10000,  0 }
+                };
+
+                GLfixed fx = baseX << 16;
+                GLfixed fy = baseY << 16;
+                GLfixed fw = width << 16;
+                GLfixed fh = height << 16;
+
+                /*
+                 * Vertex pattern:
+                 *    (2)--(3)
+                 *     |\   |
+                 *     | \  |
+                 *     |  \ |
+                 *     |   \|
+                 *    (1)--(0)
+                 *
+                 */
+
+                const GLfixed vertices[4][2] = {
+                        {fx + fw, fy},
+                        {fx,      fy},
+                        {fx,      fy + fh},
+                        {fx + fw, fy + fh}
+                };
+
+                static const bool rotate90 = true;
+
+                glMatrixMode(GL_TEXTURE);
+                glLoadIdentity();
+
+                glEnableClientState(GL_VERTEX_ARRAY);
+                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+                glVertexPointer(2, GL_FIXED, 0, vertices);
+                glTexCoordPointer(2, GL_FIXED, 0, texCoords);
+
+                LOGD("testRot90 %d, %d %d, %d", baseX, baseY, width, height);
+                glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
+
+                baseY += height + 10;
+            }
+            baseX += width + 10;
+        }
+
+        eglSwapBuffers(eglDisplay, eglSurface);
+    }
+    return 0;
+}
+
+int main(int argc, char **argv)
+{
+
+    int q;
+    int start, end;
+
+    if (init_gralloc()) {
+        printf("gralloc initialization failed - exiting\n");
+        return 0;
+    }
+
+    printf("Initializing EGL...\n");
+
+    if(!init_gl_surface())
+    {
+        printf("GL initialisation failed - exiting\n");
+        return 0;
+    }
+
+    init_scene();
+
+    printf("Start test...\n");
+    // testTime();
+     testStretch();
+    //testRot90();
+    free_gl_surface();
+
+    return 0;
+}
diff --git a/packages/SettingsProvider/etc/bookmarks.xml b/packages/SettingsProvider/etc/bookmarks.xml
index 5af416a..734e0cd 100644
--- a/packages/SettingsProvider/etc/bookmarks.xml
+++ b/packages/SettingsProvider/etc/bookmarks.xml
@@ -39,10 +39,12 @@
         package="com.android.calendar"
         class="com.android.calendar.LaunchActivity"
         shortcut="l" />
+<!--
     <bookmark
         package="com.google.android.apps.maps"
         class="com.google.android.maps.MapsActivity"
         shortcut="m" />
+-->
     <bookmark
         package="com.android.music"
         class="com.android.music.MusicBrowserActivity"
diff --git a/packages/SettingsProvider/res/values/defaults.xml b/packages/SettingsProvider/res/values/defaults.xml
index f8adaa1..af02741 100644
--- a/packages/SettingsProvider/res/values/defaults.xml
+++ b/packages/SettingsProvider/res/values/defaults.xml
@@ -36,6 +36,7 @@
          user opt-in via Setup Wizard or Settings.  
     -->
     <string name="def_location_providers_allowed">gps</string>
+    <bool name="assisted_gps_enabled">true</bool>
     <!--  0 == mobile, 1 == wifi. -->
     <integer name="def_network_preference">1</integer>
     <bool name="def_usb_mass_storage_enabled">true</bool>
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
index 6dd1175..f00fd39 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
@@ -56,7 +56,7 @@
  * Database helper class for {@link SettingsProvider}.
  * Mostly just has a bit {@link #onCreate} to initialize the database.
  */
-class DatabaseHelper extends SQLiteOpenHelper {
+public class DatabaseHelper extends SQLiteOpenHelper {
     /**
      * Path to file containing default bookmarks, relative to ANDROID_ROOT.
      */
@@ -64,7 +64,7 @@
 
     private static final String TAG = "SettingsProvider";
     private static final String DATABASE_NAME = "settings.db";
-    private static final int DATABASE_VERSION = 35;
+    private static final int DATABASE_VERSION = 37;
 
     private Context mContext;
 
@@ -389,6 +389,21 @@
         if (upgradeVersion == 34) {
             db.beginTransaction();
             try {
+                String value =
+                        mContext.getResources().getBoolean(R.bool.assisted_gps_enabled) ? "1" : "0";
+                db.execSQL("INSERT OR IGNORE INTO secure(name,value) values('" +
+                        Settings.Secure.ASSISTED_GPS_ENABLED + "','" + value + "');");
+                db.setTransactionSuccessful();
+            } finally {
+                db.endTransaction();
+            }
+
+            upgradeVersion = 35;
+        }
+
+        if (upgradeVersion == 35) {
+            db.beginTransaction();
+            try {
                 SQLiteStatement stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
                         + " VALUES(?,?);");
                 loadSecure35Settings(stmt);
@@ -397,9 +412,29 @@
             } finally {
                 db.endTransaction();
             }
-            upgradeVersion = 35;
+            upgradeVersion = 36;
         }
-        
+        if (upgradeVersion == 36) {
+           // This upgrade adds the STREAM_SYSTEM_ENFORCED type to the list of
+            // types affected by ringer modes (silent, vibrate, etc.)
+            db.beginTransaction();
+            try {
+                db.execSQL("DELETE FROM system WHERE name='"
+                        + Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
+                int newValue = (1 << AudioManager.STREAM_RING)
+                        | (1 << AudioManager.STREAM_NOTIFICATION)
+                        | (1 << AudioManager.STREAM_SYSTEM)
+                        | (1 << AudioManager.STREAM_SYSTEM_ENFORCED);
+                db.execSQL("INSERT INTO system ('name', 'value') values ('"
+                        + Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+                        + String.valueOf(newValue) + "')");
+                db.setTransactionSuccessful();
+            } finally {
+                db.endTransaction();
+            }
+            upgradeVersion = 36;
+        }
+
         if (upgradeVersion != currentVersion) {
             Log.w(TAG, "Got stuck trying to upgrade from version " + upgradeVersion
                     + ", must wipe the settings provider");
@@ -560,7 +595,7 @@
         // By default, only the ring/notification and system streams are affected
         loadSetting(stmt, Settings.System.MODE_RINGER_STREAMS_AFFECTED,
                 (1 << AudioManager.STREAM_RING) | (1 << AudioManager.STREAM_NOTIFICATION) |
-                (1 << AudioManager.STREAM_SYSTEM));
+                (1 << AudioManager.STREAM_SYSTEM) | (1 << AudioManager.STREAM_SYSTEM_ENFORCED));
 
         loadSetting(stmt, Settings.System.MUTE_STREAMS_AFFECTED,
                 ((1 << AudioManager.STREAM_MUSIC) |
@@ -667,6 +702,9 @@
         loadStringSetting(stmt, Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
                 R.string.def_location_providers_allowed);
 
+        loadBooleanSetting(stmt, Settings.Secure.ASSISTED_GPS_ENABLED,
+                R.bool.assisted_gps_enabled);
+
         loadIntegerSetting(stmt, Settings.Secure.NETWORK_PREFERENCE,
                 R.integer.def_network_preference);
 
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
index ca739e6..b13883e 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
@@ -118,16 +118,19 @@
 
     byte[] getSyncProviders() {
         byte[] sync = new byte[1 + PROVIDERS.length];
+        // TODO: Sync backup needs to be moved to SystemBackupAgent
+        /*
         try {
             sync[0] = (byte) (mContentService.getListenForNetworkTickles() ? 1 : 0);
             for (int i = 0; i < PROVIDERS.length; i++) {
                 sync[i + 1] = (byte) 
-                        (mContentService.getSyncProviderAutomatically(PROVIDERS[i]) ? 1 : 0);
+                        (mContentService.getSyncAutomatically(PROVIDERS[i]) ? 1 : 0);
             }
         } catch (RemoteException re) {
             Log.w(TAG, "Unable to backup sync providers");
             return sync;
         }
+        */
         return sync;
     }
 
@@ -136,12 +139,15 @@
 
         try {
             backup.readEntityData(sync, 0, sync.length);
+            // TODO: Sync backup needs to be moved to SystemBackupAgent
+            /*
             mContentService.setListenForNetworkTickles(sync[0] == 1);
             for (int i = 0; i < PROVIDERS.length; i++) {
                 mContentService.setSyncProviderAutomatically(PROVIDERS[i], sync[i + 1] > 0);
             }
         } catch (RemoteException re) {
             Log.w(TAG, "Unable to restore sync providers");
+            */
         } catch (java.io.IOException ioe) {
             Log.w(TAG, "Unable to read sync settings");
         }
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index c0de9a5..1451682 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -45,8 +45,7 @@
     private static final String TABLE_FAVORITES = "favorites";
     private static final String TABLE_OLD_FAVORITES = "old_favorites";
 
-    private DatabaseHelper mOpenHelper;
-    
+    protected DatabaseHelper mOpenHelper;
     private BackupManager mBackupManager;
 
     /**
diff --git a/packages/SubscribedFeedsProvider/AndroidManifest.xml b/packages/SubscribedFeedsProvider/AndroidManifest.xml
index ca00a9b..d839c4e 100644
--- a/packages/SubscribedFeedsProvider/AndroidManifest.xml
+++ b/packages/SubscribedFeedsProvider/AndroidManifest.xml
@@ -19,7 +19,7 @@
                 android:writePermission="android.permission.SUBSCRIBED_FEEDS_WRITE" />
         <receiver android:name="SubscribedFeedsBroadcastReceiver">
             <intent-filter>
-                <action android:name="android.intent.action.GTALK_DATA_MESSAGE_RECEIVED" />
+                <action android:name="android.intent.action.REMOTE_INTENT" />
                 <category android:name="GSYNC_TICKLE"/>
             </intent-filter>
             <intent-filter>
diff --git a/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsIntentService.java b/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsIntentService.java
index 8b3bedf..3cd2cc4 100644
--- a/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsIntentService.java
+++ b/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsIntentService.java
@@ -16,13 +16,14 @@
 import android.app.AlarmManager;
 import android.app.PendingIntent;
 import android.os.Bundle;
-import android.os.RemoteException;
 import android.text.TextUtils;
-import android.net.Uri;
+import android.accounts.Account;
 
 import java.util.ArrayList;
 import java.util.Calendar;
 
+import com.google.android.collect.Lists;
+
 /**
  * A service to handle various intents asynchronously.
  */
@@ -30,7 +31,8 @@
     private static final String TAG = "Sync";
 
     private static final String[] sAccountProjection =
-            new String[] {SubscribedFeeds.Accounts._SYNC_ACCOUNT};
+            new String[] {SubscribedFeeds.Accounts._SYNC_ACCOUNT,
+                    SubscribedFeeds.Accounts._SYNC_ACCOUNT_TYPE};
 
     /** How often to refresh the subscriptions, in milliseconds */
     private static final long SUBSCRIPTION_REFRESH_INTERVAL = 1000L * 60 * 60 * 24; // one day
@@ -39,8 +41,7 @@
 
     private static final String sSubscribedFeedsPrefs = "subscribedFeeds";
 
-    private static final String GTALK_DATA_MESSAGE_RECEIVED =
-            "android.intent.action.GTALK_DATA_MESSAGE_RECEIVED";
+    private static final String REMOTE_INTENT_ACTION = Intent.ACTION_REMOTE_INTENT;
 
     private static final String SUBSCRIBED_FEEDS_REFRESH_ACTION =
             "com.android.subscribedfeeds.action.REFRESH";
@@ -52,13 +53,14 @@
     }
 
     protected void onHandleIntent(Intent intent) {
-        if (GTALK_DATA_MESSAGE_RECEIVED.equals(intent.getAction())) {
-            boolean fromTrustedServer = intent.getBooleanExtra("from_trusted_server", false);
+        if (REMOTE_INTENT_ACTION.equals(intent.getAction())) {
+            boolean fromTrustedServer = intent.getBooleanExtra(
+                    "android.intent.extra.from_trusted_server", false);
             if (fromTrustedServer) {
-                String account = intent.getStringExtra("account");
-                String token = intent.getStringExtra("message_token");
+                String accountName = intent.getStringExtra("account");
+                String token = intent.getStringExtra(Intent.EXTRA_REMOTE_INTENT_TOKEN);
 
-                if (TextUtils.isEmpty(account) || TextUtils.isEmpty(token)) {
+                if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(token)) {
                     if (Config.LOGD) {
                         Log.d(TAG, "Ignoring malformed tickle -- missing account or token.");
                     }
@@ -67,10 +69,10 @@
 
                 if (Config.LOGD) {
                     Log.d(TAG, "Received network tickle for "
-                            + account + " - " + token);
+                            + accountName + " - " + token);
                 }
 
-                handleTickle(this, account, token);
+                handleTickle(this, accountName, token);
             } else {
                 if (Log.isLoggable(TAG, Log.VERBOSE)) {
                     Log.v(TAG, "Ignoring tickle -- not from trusted server.");
@@ -102,16 +104,19 @@
         alarmManager.set(AlarmManager.RTC, when, pendingIntent);
     }
 
-    private void handleTickle(Context context, String account, String feed) {
+    private void handleTickle(Context context, String accountName, String feed) {
         Cursor c = null;
         final String where = SubscribedFeeds.Feeds._SYNC_ACCOUNT + "= ? "
+                + "and " + SubscribedFeeds.Feeds._SYNC_ACCOUNT_TYPE + "= ? "
                 + "and " + SubscribedFeeds.Feeds.FEED + "= ?";
         try {
+            // TODO(fredq) fix the hardcoded type
+            final Account account = new Account(accountName, "com.google.GAIA");
             c = context.getContentResolver().query(SubscribedFeeds.Feeds.CONTENT_URI,
-                    null, where, new String[]{account, feed}, null);
+                    null, where, new String[]{account.mName, account.mType, feed}, null);
             if (c.getCount() == 0) {
                 Log.w(TAG, "received tickle for non-existent feed: "
-                        + "account " + account + ", feed " + feed);
+                        + "account " + accountName + ", feed " + feed);
                 EventLog.writeEvent(LOG_TICKLE, "unknown");
             }
             while (c.moveToNext()) {
@@ -119,21 +124,14 @@
                 String authority = c.getString(c.getColumnIndexOrThrow(
                         SubscribedFeeds.Feeds.AUTHORITY));
                 EventLog.writeEvent(LOG_TICKLE, authority);
-                try {
-                    if (!ContentResolver.getContentService()
-                            .getSyncProviderAutomatically(authority)) {
-                        Log.d(TAG, "supressing tickle since provider " + authority
-                                + " is configured to not sync automatically");
-                        continue;
-                    }
-                } catch (RemoteException e) {
+                if (!ContentResolver.getSyncAutomatically(account, authority)) {
+                    Log.d(TAG, "supressing tickle since provider " + authority
+                            + " is configured to not sync automatically");
                     continue;
                 }
-                Uri uri = Uri.parse("content://" + authority);
                 Bundle extras = new Bundle();
-                extras.putString(ContentResolver.SYNC_EXTRAS_ACCOUNT, account);
                 extras.putString("feed", feed);
-                context.getContentResolver().startSync(uri, extras);
+                ContentResolver.requestSync(account, authority, extras);
             }
         } finally {
             if (c != null) c.deactivate();
@@ -150,31 +148,35 @@
      */
     private void handleRefreshAlarm(Context context) {
         // retrieve the list of accounts from the subscribed feeds
-        ArrayList<String> accounts = new ArrayList<String>();
+        ArrayList<Account> accounts = Lists.newArrayList();
         ContentResolver contentResolver = context.getContentResolver();
         Cursor c = contentResolver.query(SubscribedFeeds.Accounts.CONTENT_URI,
                 sAccountProjection, null, null, null);
-        while (c.moveToNext()) {
-            String account = c.getString(0);
-            if (TextUtils.isEmpty(account)) {
-                continue;
+        try {
+            while (c.moveToNext()) {
+                String accountName = c.getString(0);
+                String accountType = c.getString(1);
+                accounts.add(new Account(accountName, accountType));
             }
-            accounts.add(account);
+        } finally {
+            c.close();
         }
-        c.deactivate();
 
         // Clear the auth tokens for all these accounts so that we are sure
         // they will still be valid until the next time we refresh them.
-        // TODO: add this when the google login service is done
+        // TODO(fredq): add this when the google login service is done
 
         // mark the feeds dirty, by setting the accounts to the same value,
         //  which will trigger a sync.
         try {
             ContentValues values = new ContentValues();
-            for (String account : accounts) {
-                values.put(SyncConstValue._SYNC_ACCOUNT, account);
+            for (Account account : accounts) {
+                values.put(SyncConstValue._SYNC_ACCOUNT, account.mName);
+                values.put(SyncConstValue._SYNC_ACCOUNT_TYPE, account.mType);
                 contentResolver.update(SubscribedFeeds.Feeds.CONTENT_URI, values,
-                        SubscribedFeeds.Feeds._SYNC_ACCOUNT + "=?", new String[] {account});
+                        SubscribedFeeds.Feeds._SYNC_ACCOUNT + "=? AND "
+                                + SubscribedFeeds.Feeds._SYNC_ACCOUNT_TYPE + "=?",
+                        new String[] {account.mName, account.mType});
             }
         } catch (SQLiteFullException e) {
             Log.w(TAG, "disk full while trying to mark the feeds as dirty, skipping");
diff --git a/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsProvider.java b/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsProvider.java
index 9ecc3d6..d87f5e7 100644
--- a/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsProvider.java
+++ b/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsProvider.java
@@ -39,7 +39,7 @@
 public class SubscribedFeedsProvider extends AbstractSyncableContentProvider {
     private static final String TAG = "SubscribedFeedsProvider";
     private static final String DATABASE_NAME = "subscribedfeeds.db";
-    private static final int DATABASE_VERSION = 10;
+    private static final int DATABASE_VERSION = 11;
 
     private static final int FEEDS = 1;
     private static final int FEED_ID = 2;
@@ -88,6 +88,7 @@
         db.execSQL("CREATE TABLE feeds (" +
                     "_id INTEGER PRIMARY KEY," +
                     "_sync_account TEXT," + // From the sync source
+                    "_sync_account_type TEXT," + // From the sync source
                     "_sync_id TEXT," + // From the sync source
                     "_sync_time TEXT," + // From the sync source
                     "_sync_version TEXT," + // From the sync source
@@ -106,8 +107,8 @@
                     "WHEN old._sync_id is not null " +
                     "BEGIN " +
                         "INSERT INTO _deleted_feeds " +
-                            "(_sync_id, _sync_account, _sync_version) " +
-                            "VALUES (old._sync_id, old._sync_account, " +
+                            "(_sync_id, _sync_account, _sync_account_type, _sync_version) " +
+                            "VALUES (old._sync_id, old._sync_account, old._sync_account_type, " +
                             "old._sync_version);" +
                     "END");
 
@@ -116,6 +117,7 @@
                     "_sync_id TEXT," +
                     (isTemporary() ? "_sync_local_id INTEGER," : "") + // Used while syncing,
                     "_sync_account TEXT," +
+                    "_sync_account_type TEXT," +
                     "_sync_mark INTEGER, " + // Used to filter out new rows
                     "UNIQUE(_sync_id))");
     }
@@ -170,7 +172,8 @@
                 qb.setDistinct(true);
                 qb.setProjectionMap(ACCOUNTS_PROJECTION_MAP);
                 return qb.query(getDatabase(), projection, selection, selectionArgs,
-                        SubscribedFeeds.Feeds._SYNC_ACCOUNT, null, sortOrder);
+                        SubscribedFeeds.Feeds._SYNC_ACCOUNT_TYPE + ","
+                                + SubscribedFeeds.Feeds._SYNC_ACCOUNT, null, sortOrder);
             case FEED_ID:
                 qb.setTables(sFeedsTable);
                 qb.appendWhere(sFeedsTable + "._id=");
@@ -310,6 +313,8 @@
             DatabaseUtils.cursorStringToContentValues(diffsCursor,
                     SubscribedFeeds.Feeds._SYNC_ACCOUNT, mValues);
             DatabaseUtils.cursorStringToContentValues(diffsCursor,
+                    SubscribedFeeds.Feeds._SYNC_ACCOUNT_TYPE, mValues);
+            DatabaseUtils.cursorStringToContentValues(diffsCursor,
                     SubscribedFeeds.Feeds._SYNC_VERSION, mValues);
             db.replace(mDeletedTable, SubscribedFeeds.Feeds._SYNC_ID, mValues);
         }
@@ -369,5 +374,7 @@
         ACCOUNTS_PROJECTION_MAP = map;
         map.put(SubscribedFeeds.Accounts._COUNT, "COUNT(*) AS _count");
         map.put(SubscribedFeeds.Accounts._SYNC_ACCOUNT, SubscribedFeeds.Accounts._SYNC_ACCOUNT);
+        map.put(SubscribedFeeds.Accounts._SYNC_ACCOUNT_TYPE,
+                SubscribedFeeds.Accounts._SYNC_ACCOUNT_TYPE);
     }
 }
diff --git a/packages/TtsService/jni/android_tts_SynthProxy.cpp b/packages/TtsService/jni/android_tts_SynthProxy.cpp
index 99d7723..a4090cf 100644
--- a/packages/TtsService/jni/android_tts_SynthProxy.cpp
+++ b/packages/TtsService/jni/android_tts_SynthProxy.cpp
@@ -71,7 +71,7 @@
         AudioTrack*               mAudioOut;
         AudioSystem::stream_type  mStreamType;
         uint32_t                  mSampleRate;
-        AudioSystem::audio_format mAudFormat;
+        uint32_t                  mAudFormat;
         int                       mNbChannels;
         int8_t *                  mBuffer;
         size_t                    mBufferSize;
@@ -118,7 +118,6 @@
             mSampleRate = rate;
             mAudFormat  = format;
             mNbChannels = channel;
-
             mStreamType = streamType;
 
             // retrieve system properties to ensure successful creation of the
@@ -139,7 +138,8 @@
             if (minBufCount < 2) minBufCount = 2;
             int minFrameCount = (afFrameCount * rate * minBufCount)/afSampleRate;
 
-            mAudioOut = new AudioTrack(mStreamType, rate, format, channel,
+            mAudioOut = new AudioTrack(mStreamType, rate, format,
+                    (channel == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
                     minFrameCount > 4096 ? minFrameCount : 4096,
                     0, 0, 0, 0); // not using an AudioTrack callback
 
@@ -182,7 +182,7 @@
  * Directly speaks using AudioTrack or write to file
  */
 static tts_callback_status ttsSynthDoneCB(void *& userdata, uint32_t rate,
-                           AudioSystem::audio_format format, int channel,
+                           uint32_t format, int channel,
                            int8_t *&wav, size_t &bufferSize, tts_synth_status status) {
     //LOGV("ttsSynthDoneCallback: %d bytes", bufferSize);
 
@@ -202,7 +202,7 @@
         }
 
         if (bufferSize > 0) {
-            prepAudioTrack(pJniData, pForAfter->streamType, rate, format, channel);
+            prepAudioTrack(pJniData, pForAfter->streamType, rate, (AudioSystem::audio_format)format, channel);
             if (pJniData->mAudioOut) {
                 pJniData->mAudioOut->write(wav, bufferSize);
                 memset(wav, 0, bufferSize);
diff --git a/preloaded-classes b/preloaded-classes
index 0520e41..3858883 100644
--- a/preloaded-classes
+++ b/preloaded-classes
@@ -1,7 +1,5 @@
 # Classes which are preloaded by com.android.internal.os.ZygoteInit.
 android.R$styleable
-android.accounts.AccountMonitor
-android.accounts.AccountMonitor$AccountUpdater
 android.app.Activity
 android.app.ActivityGroup
 android.app.ActivityManager$MemoryInfo$1
@@ -213,7 +211,6 @@
 android.media.AudioManager
 android.media.IAudioService$Stub
 android.media.IAudioService$Stub$Proxy
-android.media.MediaPlayer
 android.net.LocalSocket
 android.net.LocalSocketAddress
 android.net.LocalSocketAddress$Namespace
@@ -488,7 +485,6 @@
 android.webkit.JWebCoreJavaBridge
 android.webkit.LoadListener
 android.webkit.MimeTypeMap
-android.webkit.TextDialog
 android.webkit.URLUtil
 android.webkit.WebBackForwardList
 android.webkit.WebHistoryItem
@@ -504,14 +500,14 @@
 android.webkit.WebSettings$TextSize
 android.webkit.WebSyncManager
 android.webkit.WebSyncManager$SyncHandler
+android.webkit.WebTextView
 android.webkit.WebView
 android.webkit.WebView$ExtendedZoomControls
-android.webkit.WebView$FocusNode
 android.webkit.WebView$PrivateHandler
 android.webkit.WebViewCore
+android.webkit.WebViewCore$CursorData
 android.webkit.WebViewCore$EventHub
 android.webkit.WebViewCore$EventHub$1
-android.webkit.WebViewCore$FocusData
 android.webkit.WebViewCore$WebCoreThread
 android.webkit.WebViewCore$WebCoreThread$1
 android.webkit.WebViewDatabase
diff --git a/services/java/com/android/server/BackupManagerService.java b/services/java/com/android/server/BackupManagerService.java
index 6e28515..e74b37b 100644
--- a/services/java/com/android/server/BackupManagerService.java
+++ b/services/java/com/android/server/BackupManagerService.java
@@ -100,18 +100,18 @@
     private PowerManager mPowerManager;
     private AlarmManager mAlarmManager;
 
-    private boolean mEnabled;   // access to this is synchronized on 'this'
-    private boolean mProvisioned;
-    private PowerManager.WakeLock mWakelock;
-    private final BackupHandler mBackupHandler = new BackupHandler();
-    private PendingIntent mRunBackupIntent;
-    private BroadcastReceiver mRunBackupReceiver;
-    private IntentFilter mRunBackupFilter;
+    boolean mEnabled;   // access to this is synchronized on 'this'
+    boolean mProvisioned;
+    PowerManager.WakeLock mWakelock;
+    final BackupHandler mBackupHandler = new BackupHandler();
+    PendingIntent mRunBackupIntent;
+    BroadcastReceiver mRunBackupReceiver;
+    IntentFilter mRunBackupFilter;
     // map UIDs to the set of backup client services within that UID's app set
-    private final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
+    final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
         = new SparseArray<HashSet<ApplicationInfo>>();
     // set of backup services that have pending changes
-    private class BackupRequest {
+    class BackupRequest {
         public ApplicationInfo appInfo;
         public boolean fullBackup;
 
@@ -125,35 +125,35 @@
         }
     }
     // Backups that we haven't started yet.
-    private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
+    HashMap<ApplicationInfo,BackupRequest> mPendingBackups
             = new HashMap<ApplicationInfo,BackupRequest>();
 
     // Pseudoname that we use for the Package Manager metadata "package"
-    private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
+    static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
 
     // locking around the pending-backup management
-    private final Object mQueueLock = new Object();
+    final Object mQueueLock = new Object();
 
     // The thread performing the sequence of queued backups binds to each app's agent
     // in succession.  Bind notifications are asynchronously delivered through the
     // Activity Manager; use this lock object to signal when a requested binding has
     // completed.
-    private final Object mAgentConnectLock = new Object();
-    private IBackupAgent mConnectedAgent;
-    private volatile boolean mConnecting;
+    final Object mAgentConnectLock = new Object();
+    IBackupAgent mConnectedAgent;
+    volatile boolean mConnecting;
 
     // A similar synchronicity mechanism around clearing apps' data for restore
-    private final Object mClearDataLock = new Object();
-    private volatile boolean mClearingData;
+    final Object mClearDataLock = new Object();
+    volatile boolean mClearingData;
 
     // Transport bookkeeping
-    private final HashMap<String,IBackupTransport> mTransports
+    final HashMap<String,IBackupTransport> mTransports
             = new HashMap<String,IBackupTransport>();
-    private String mCurrentTransport;
-    private IBackupTransport mLocalTransport, mGoogleTransport;
-    private RestoreSession mActiveRestoreSession;
+    String mCurrentTransport;
+    IBackupTransport mLocalTransport, mGoogleTransport;
+    RestoreSession mActiveRestoreSession;
 
-    private class RestoreParams {
+    class RestoreParams {
         public IBackupTransport transport;
         public IRestoreObserver observer;
         public long token;
@@ -165,7 +165,7 @@
         }
     }
 
-    private class ClearParams {
+    class ClearParams {
         public IBackupTransport transport;
         public PackageInfo packageInfo;
 
@@ -176,11 +176,17 @@
     }
 
     // Where we keep our journal files and other bookkeeping
-    private File mBaseStateDir;
-    private File mDataDir;
-    private File mJournalDir;
-    private File mJournal;
-    private RandomAccessFile mJournalStream;
+    File mBaseStateDir;
+    File mDataDir;
+    File mJournalDir;
+    File mJournal;
+    RandomAccessFile mJournalStream;
+
+    // Keep a log of all the apps we've ever backed up
+    private File mEverStored;
+    private RandomAccessFile mEverStoredStream;
+    HashSet<String> mEverStoredApps = new HashSet<String>();
+
 
     public BackupManagerService(Context context) {
         mContext = context;
@@ -215,6 +221,9 @@
         mJournalDir.mkdirs();   // creates mBaseStateDir along the way
         makeJournalLocked();    // okay because no other threads are running yet
 
+        // Set up the various sorts of package tracking we do
+        initPackageTracking();
+
         // Build our mapping of uid to backup client services.  This implicitly
         // schedules a backup pass on the Package Manager metadata the first
         // time anything needs to be backed up.
@@ -249,14 +258,6 @@
         // leftover journal files into the pending backup set
         parseLeftoverJournals();
 
-        // Register for broadcasts about package install, etc., so we can
-        // update the provider list.
-        IntentFilter filter = new IntentFilter();
-        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
-        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
-        filter.addDataScheme("package");
-        mContext.registerReceiver(mBroadcastReceiver, filter);
-
         // Power management
         mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
 
@@ -281,6 +282,67 @@
         }
     }
 
+    private void initPackageTracking() {
+        if (DEBUG) Log.v(TAG, "Initializing package tracking");
+
+        // Keep a log of what apps we've ever backed up.  Because we might have
+        // rebooted in the middle of an operation that was removing something from
+        // this log, we sanity-check its contents here and reconstruct it.
+        mEverStored = new File(mBaseStateDir, "processed");
+        File tempProcessedFile = new File(mBaseStateDir, "processed.new");
+        try {
+            RandomAccessFile temp = new RandomAccessFile(tempProcessedFile, "rw");
+            mEverStoredStream = new RandomAccessFile(mEverStored, "r");
+
+            // parse its existing contents
+            mEverStoredStream.seek(0);
+            temp.seek(0);
+            try {
+                while (true) {
+                    PackageInfo info;
+                    String pkg = mEverStoredStream.readUTF();
+                    try {
+                        info = mPackageManager.getPackageInfo(pkg, 0);
+                        mEverStoredApps.add(pkg);
+                        temp.writeUTF(pkg);
+                        if (DEBUG) Log.v(TAG, "   + " + pkg);
+                    } catch (NameNotFoundException e) {
+                        // nope, this package was uninstalled; don't include it
+                        if (DEBUG) Log.v(TAG, "   - " + pkg);
+                    }
+                }
+            } catch (EOFException e) {
+                // now we're at EOF
+            }
+
+            // Once we've rewritten the backup history log, atomically replace the
+            // old one with the new one then reopen the file for continuing use.
+            temp.close();
+            mEverStoredStream.close();
+            tempProcessedFile.renameTo(mEverStored);
+            mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
+        } catch (IOException e) {
+            Log.e(TAG, "Unable to open known-stored file!");
+            mEverStoredStream = null;
+        }
+
+        // If we were in the middle of removing something from the ever-backed-up
+        // file, there might be a transient "processed.new" file still present.
+        // We've reconstructed a coherent state at this point though, so we can
+        // safely discard that file now.
+        if (tempProcessedFile.exists()) {
+            tempProcessedFile.delete();
+        }
+
+        // Register for broadcasts about package install, etc., so we can
+        // update the provider list.
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
+        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+        filter.addDataScheme("package");
+        mContext.registerReceiver(mBroadcastReceiver, filter);
+    }
+
     private void makeJournalLocked() {
         try {
             mJournal = File.createTempFile("journal", null, mJournalDir);
@@ -485,6 +547,17 @@
                     mBackupParticipants.put(uid, set);
                 }
                 set.add(pkg.applicationInfo);
+
+                // If we've never seen this app before, schedule a backup for it
+                if (!mEverStoredApps.contains(pkg.packageName)) {
+                    if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
+                            + " never backed up; scheduling");
+                    try {
+                        dataChanged(pkg.packageName);
+                    } catch (RemoteException e) {
+                        // can't happen; it's a local method call
+                    }
+                }
             }
         }
     }
@@ -528,6 +601,7 @@
                     for (ApplicationInfo entry: set) {
                         if (entry.packageName.equals(pkg.packageName)) {
                             set.remove(entry);
+                            removeEverBackedUp(pkg.packageName);
                             break;
                         }
                     }
@@ -540,7 +614,7 @@
     }
 
     // Returns the set of all applications that define an android:backupAgent attribute
-    private List<PackageInfo> allAgentPackages() {
+    List<PackageInfo> allAgentPackages() {
         // !!! TODO: cache this and regenerate only when necessary
         int flags = PackageManager.GET_SIGNATURES;
         List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
@@ -570,6 +644,65 @@
         addPackageParticipantsLockedInner(packageName, allApps);
     }
 
+    // Called from the backup thread: record that the given app has been successfully
+    // backed up at least once
+    void logBackupComplete(String packageName) {
+        if (mEverStoredStream != null && !packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
+            synchronized (mEverStoredApps) {
+                if (mEverStoredApps.add(packageName)) {
+                    try {
+                        mEverStoredStream.writeUTF(packageName);
+                    } catch (IOException e) {
+                        Log.e(TAG, "Unable to log backup of " + packageName + ", ceasing log");
+                        try {
+                            mEverStoredStream.close();
+                        } catch (IOException ioe) {
+                            // we're dropping it; no need to handle an exception on close here
+                        }
+                        mEverStoredStream = null;
+                    }
+                }
+            }
+        }
+    }
+
+    // Remove our awareness of having ever backed up the given package
+    void removeEverBackedUp(String packageName) {
+        if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName
+                + ", new set:");
+
+        if (mEverStoredStream != null) {
+            synchronized (mEverStoredApps) {
+                // Rewrite the file and rename to overwrite.  If we reboot in the middle,
+                // we'll recognize on initialization time that the package no longer
+                // exists and fix it up then.
+                File tempKnownFile = new File(mBaseStateDir, "processed.new");
+                try {
+                    mEverStoredStream.close();
+                    RandomAccessFile known = new RandomAccessFile(tempKnownFile, "rw");
+                    mEverStoredApps.remove(packageName);
+                    for (String s : mEverStoredApps) {
+                        known.writeUTF(s);
+                        if (DEBUG) Log.v(TAG, "    " + s);
+                    }
+                    known.close();
+                    tempKnownFile.renameTo(mEverStored);
+                    mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
+                } catch (IOException e) {
+                    // Bad: we couldn't create the new copy.  For safety's sake we
+                    // abandon the whole process and remove all what's-backed-up
+                    // state entirely, meaning we'll force a backup pass for every
+                    // participant on the next boot or [re]install.
+                    Log.w(TAG, "Error rewriting backed-up set; halting log");
+                    mEverStoredStream = null;
+                    mEverStoredApps.clear();
+                    tempKnownFile.delete();
+                    mEverStored.delete();
+                }
+            }
+        }
+    }
+
     // Return the given transport
     private IBackupTransport getTransport(String transportName) {
         synchronized (mTransports) {
@@ -799,6 +932,7 @@
                 boolean success = false;
                 try {
                     agent.doBackup(savedState, backupData, newState);
+                    logBackupComplete(packageName);
                     success = true;
                 } finally {
                     if (savedState != null) {
@@ -1142,7 +1276,13 @@
                 File savedStateName = new File(mStateDir, packageName);
                 newStateName.renameTo(savedStateName);
             } catch (Exception e) {
+                // If the agent fails restore, it might have put the app's data
+                // into an incoherent state.  For consistency we wipe its data
+                // again in this case before propagating the exception
                 Log.e(TAG, "Error restoring data for " + packageName, e);
+                clearApplicationDataSynchronous(packageName);
+            } finally {
+                backupDataName.delete();
             }
         }
     }
@@ -1235,7 +1375,8 @@
                 }
             }
         } else {
-            Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'");
+            Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
+                    + " uid=" + Binder.getCallingUid());
         }
     }
 
@@ -1301,7 +1442,7 @@
     // Run a backup pass immediately for any applications that have declared
     // that they have pending updates.
     public void backupNow() throws RemoteException {
-        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "backupNow");
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
 
         if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
         synchronized (mQueueLock) {
@@ -1370,13 +1511,13 @@
 
     // Report whether the backup mechanism is currently enabled
     public boolean isBackupEnabled() {
-        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
         return mEnabled;    // no need to synchronize just to read it
     }
 
     // Report the name of the currently active transport
     public String getCurrentTransport() {
-        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
                 "getCurrentTransport");
         Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
         return mCurrentTransport;
@@ -1405,7 +1546,7 @@
     // name is not one of the available transports, no action is taken and the method
     // returns null.
     public String selectBackupTransport(String transport) {
-        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
 
         synchronized (mTransports) {
             String prevTransport = null;
@@ -1459,7 +1600,7 @@
 
     // Hand off a restore session
     public IRestoreSession beginRestoreSession(String transport) {
-        mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
 
         synchronized(this) {
             if (mActiveRestoreSession != null) {
@@ -1485,12 +1626,14 @@
 
         // --- Binder interface ---
         public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
-            mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
+            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
                     "getAvailableRestoreSets");
 
             try {
             synchronized(this) {
-                if (mRestoreSets == null) {
+                if (mRestoreTransport == null) {
+                    Log.w(TAG, "Null transport getting restore sets");
+                } else if (mRestoreSets == null) { // valid transport; do the one-time fetch
                     mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
                 }
                 return mRestoreSets;
@@ -1504,7 +1647,7 @@
 
         public int performRestore(long token, IRestoreObserver observer)
                 throws android.os.RemoteException {
-            mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "performRestore");
+            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "performRestore");
 
             Log.d(TAG, "performRestore token=" + token + " observer=" + observer);
 
@@ -1525,7 +1668,7 @@
         }
 
         public void endRestoreSession() throws android.os.RemoteException {
-            mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
+            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
                     "endRestoreSession");
 
             Log.d(TAG, "endRestoreSession");
@@ -1546,8 +1689,6 @@
     @Override
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         synchronized (mQueueLock) {
-            long oldId = Binder.clearCallingIdentity();
-
             pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
                     + " / " + (!mProvisioned ? "not " : "") + "provisioned");
             pw.println("Available transports:");
@@ -1566,12 +1707,14 @@
                     pw.println("    " + app.toString());
                 }
             }
+            pw.println("Ever backed up: " + mEverStoredApps.size());
+            for (String pkg : mEverStoredApps) {
+                pw.println("    " + pkg);
+            }
             pw.println("Pending: " + mPendingBackups.size());
             for (BackupRequest req : mPendingBackups.values()) {
                 pw.println("    " + req);
             }
-
-            Binder.restoreCallingIdentity(oldId);
         }
     }
 }
diff --git a/services/java/com/android/server/BatteryService.java b/services/java/com/android/server/BatteryService.java
index 90d8c9d..a682fcb 100644
--- a/services/java/com/android/server/BatteryService.java
+++ b/services/java/com/android/server/BatteryService.java
@@ -92,6 +92,9 @@
     // This should probably be exposed in the API, though it's not critical
     private static final int BATTERY_PLUGGED_NONE = 0;
 
+    private static final int BATTERY_LEVEL_CLOSE_WARNING = 20;
+    private static final int BATTERY_LEVEL_WARNING = 15;
+
     private final Context mContext;
     private final IBatteryStats mBatteryStats;
     
@@ -120,6 +123,7 @@
     private long mDischargeStartTime;
     private int mDischargeStartLevel;
     
+    private boolean mSentLowBatteryBroadcast = false;
     
     public BatteryService(Context context) {
         mContext = context;
@@ -250,16 +254,28 @@
             // Separate broadcast is sent for power connected / not connected
             // since the standard intent will not wake any applications and some
             // applications may want to have smart behavior based on this.
+            Intent statusIntent = new Intent();
+            statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
             if (mPlugType != 0 && mLastPlugType == 0) {
-                Intent intent = new Intent(Intent.ACTION_POWER_CONNECTED);
-                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
-                mContext.sendBroadcast(intent);
+                statusIntent.setAction(Intent.ACTION_POWER_CONNECTED);
+                mContext.sendBroadcast(statusIntent);
             }
             else if (mPlugType == 0 && mLastPlugType != 0) {
-                Intent intent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
-                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
-                mContext.sendBroadcast(intent);
+                statusIntent.setAction(Intent.ACTION_POWER_DISCONNECTED);
+                mContext.sendBroadcast(statusIntent);
             }
+
+            final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
+            final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
+
+            /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
+             * - is just un-plugged (previously was plugged) and battery level is under WARNING, or
+             * - is not plugged and battery level crosses the WARNING boundary (becomes < 15).
+             */
+            final boolean sendBatteryLow = !plugged
+                && mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
+                && mBatteryLevel < BATTERY_LEVEL_WARNING
+                && (oldPlugged || mLastBatteryLevel >= BATTERY_LEVEL_WARNING);
             
             mLastBatteryStatus = mBatteryStatus;
             mLastBatteryHealth = mBatteryHealth;
@@ -269,8 +285,17 @@
             mLastBatteryVoltage = mBatteryVoltage;
             mLastBatteryTemperature = mBatteryTemperature;
             mLastBatteryLevelCritical = mBatteryLevelCritical;
-            
+
             sendIntent();
+            if (sendBatteryLow) {
+                mSentLowBatteryBroadcast = true;
+                statusIntent.setAction(Intent.ACTION_BATTERY_LOW);
+                mContext.sendBroadcast(statusIntent);
+            } else if (mSentLowBatteryBroadcast && mLastBatteryLevel >= BATTERY_LEVEL_CLOSE_WARNING) {
+                mSentLowBatteryBroadcast = false;
+                statusIntent.setAction(Intent.ACTION_BATTERY_OKAY);
+                mContext.sendBroadcast(statusIntent);
+            }
             
             // This needs to be done after sendIntent() so that we get the lastest battery stats.
             if (logOutlier && dischargeDuration != 0) {
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index 493bd09..62b839d 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -74,7 +74,7 @@
 
     private static class ConnectivityThread extends Thread {
         private Context mContext;
-        
+
         private ConnectivityThread(Context context) {
             super("ConnectivityThread");
             mContext = context;
@@ -89,11 +89,11 @@
             }
             Looper.loop();
         }
-        
+
         public static ConnectivityService getServiceInstance(Context context) {
             ConnectivityThread thread = new ConnectivityThread(context);
             thread.start();
-            
+
             synchronized (thread) {
                 while (sServiceInstance == null) {
                     try {
@@ -101,27 +101,28 @@
                         thread.wait();
                     } catch (InterruptedException ignore) {
                         Log.e(TAG,
-                            "Unexpected InterruptedException while waiting for ConnectivityService thread");
+                            "Unexpected InterruptedException while waiting"+
+                            " for ConnectivityService thread");
                     }
                 }
             }
-            
+
             return sServiceInstance;
         }
     }
-    
+
     public static ConnectivityService getInstance(Context context) {
         return ConnectivityThread.getServiceInstance(context);
     }
-    
+
     private ConnectivityService(Context context) {
         if (DBG) Log.v(TAG, "ConnectivityService starting up");
         mContext = context;
         mNetTrackers = new NetworkStateTracker[2];
         Handler handler = new MyHandler();
-        
+
         mNetworkPreference = getPersistedNetworkPreference();
-                
+
         /*
          * Create the network state trackers for Wi-Fi and mobile
          * data. Maybe this could be done with a factory class,
@@ -137,7 +138,7 @@
 
         mMobileDataStateTracker = new MobileDataStateTracker(context, handler);
         mNetTrackers[ConnectivityManager.TYPE_MOBILE] = mMobileDataStateTracker;
-        
+
         mActiveNetwork = null;
         mNumDnsEntries = 0;
 
@@ -148,11 +149,12 @@
             t.startMonitoring();
 
         // Constructing this starts it too
-        mWifiWatchdogService = new WifiWatchdogService(context, mWifiStateTracker);
+        mWifiWatchdogService = new WifiWatchdogService(context,
+                mWifiStateTracker);
     }
 
     /**
-     * Sets the preferred network. 
+     * Sets the preferred network.
      * @param preference the new preference
      */
     public synchronized void setNetworkPreference(int preference) {
@@ -173,9 +175,10 @@
 
     private void persistNetworkPreference(int networkPreference) {
         final ContentResolver cr = mContext.getContentResolver();
-        Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, networkPreference);
+        Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE,
+                networkPreference);
     }
-    
+
     private int getPersistedNetworkPreference() {
         final ContentResolver cr = mContext.getContentResolver();
 
@@ -187,9 +190,9 @@
 
         return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
     }
-    
+
     /**
-     * Make the state of network connectivity conform to the preference settings.
+     * Make the state of network connectivity conform to the preference settings
      * In this method, we only tear down a non-preferred network. Establishing
      * a connection to the preferred network is taken care of when we handle
      * the disconnect event from the non-preferred network
@@ -207,7 +210,8 @@
                         ConnectivityManager.TYPE_WIFI);
 
                 if (t.getNetworkInfo().getType() != mNetworkPreference) {
-                    NetworkStateTracker otherTracker = mNetTrackers[otherNetType];
+                    NetworkStateTracker otherTracker =
+                            mNetTrackers[otherNetType];
                     if (otherTracker.isAvailable()) {
                         teardown(t);
                     }
@@ -229,7 +233,8 @@
      * Return NetworkInfo for the active (i.e., connected) network interface.
      * It is assumed that at most one network is active at a time. If more
      * than one is active, it is indeterminate which will be returned.
-     * @return the info for the active network, or {@code null} if none is active
+     * @return the info for the active network, or {@code null} if none is
+     * active
      */
     public NetworkInfo getActiveNetworkInfo() {
         enforceAccessPermission();
@@ -287,7 +292,8 @@
         }
         NetworkStateTracker tracker = mNetTrackers[networkType];
         if (tracker != null) {
-            return tracker.startUsingNetworkFeature(feature, getCallingPid(), getCallingUid());
+            return tracker.startUsingNetworkFeature(feature, getCallingPid(),
+                    getCallingUid());
         }
         return -1;
     }
@@ -299,7 +305,8 @@
         }
         NetworkStateTracker tracker = mNetTrackers[networkType];
         if (tracker != null) {
-            return tracker.stopUsingNetworkFeature(feature, getCallingPid(), getCallingUid());
+            return tracker.stopUsingNetworkFeature(feature, getCallingPid(),
+                    getCallingUid());
         }
         return -1;
     }
@@ -307,9 +314,10 @@
     /**
      * Ensure that a network route exists to deliver traffic to the specified
      * host via the specified network interface.
-     * @param networkType the type of the network over which traffic to the specified
-     * host is to be routed
-     * @param hostAddress the IP address of the host to which the route is desired
+     * @param networkType the type of the network over which traffic to the
+     * specified host is to be routed
+     * @param hostAddress the IP address of the host to which the route is
+     * desired
      * @return {@code true} on success, {@code false} on failure
      */
     public boolean requestRouteToHost(int networkType, int hostAddress) {
@@ -340,7 +348,7 @@
         return Settings.Secure.getInt(mContext.getContentResolver(),
                 Settings.Secure.BACKGROUND_DATA, 1) == 1;
     }
-    
+
     /**
      * @see ConnectivityManager#setBackgroundDataSetting(boolean)
      */
@@ -348,22 +356,24 @@
         mContext.enforceCallingOrSelfPermission(
                 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
                 "ConnectivityService");
-        
+
         if (getBackgroundDataSetting() == allowBackgroundDataUsage) return;
 
         Settings.Secure.putInt(mContext.getContentResolver(),
-                Settings.Secure.BACKGROUND_DATA, allowBackgroundDataUsage ? 1 : 0);
-        
+                Settings.Secure.BACKGROUND_DATA,
+                allowBackgroundDataUsage ? 1 : 0);
+
         Intent broadcast = new Intent(
                 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
         mContext.sendBroadcast(broadcast);
-    }    
-    
+    }
+
     private int getNumConnectedNetworks() {
         int numConnectedNets = 0;
 
         for (NetworkStateTracker nt : mNetTrackers) {
-            if (nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
+            if (nt.getNetworkInfo().isConnected() &&
+                    !nt.isTeardownRequested()) {
                 ++numConnectedNets;
             }
         }
@@ -371,21 +381,22 @@
     }
 
     private void enforceAccessPermission() {
-        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NETWORK_STATE,
-                                          "ConnectivityService");
+        mContext.enforceCallingOrSelfPermission(
+                android.Manifest.permission.ACCESS_NETWORK_STATE,
+                "ConnectivityService");
     }
 
     private void enforceChangePermission() {
-        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE,
-                                          "ConnectivityService");
-
+        mContext.enforceCallingOrSelfPermission(
+                android.Manifest.permission.CHANGE_NETWORK_STATE,
+                "ConnectivityService");
     }
 
     /**
-     * Handle a {@code DISCONNECTED} event. If this pertains to the non-active network,
-     * we ignore it. If it is for the active network, we send out a broadcast.
-     * But first, we check whether it might be possible to connect to a different
-     * network.
+     * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
+     * network, we ignore it. If it is for the active network, we send out a
+     * broadcast. But first, we check whether it might be possible to connect
+     * to a different network.
      * @param info the {@code NetworkInfo} for the network
      */
     private void handleDisconnect(NetworkInfo info) {
@@ -399,7 +410,8 @@
          * getting the disconnect for a network that we explicitly disabled
          * in accordance with network preference policies.
          */
-        if (mActiveNetwork == null ||  info.getType() != mActiveNetwork.getNetworkInfo().getType())
+        if (mActiveNetwork == null ||
+                info.getType() != mActiveNetwork.getNetworkInfo().getType())
             return;
 
         NetworkStateTracker newNet;
@@ -439,28 +451,33 @@
             intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
         }
         if (info.getExtraInfo() != null) {
-            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
+            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
+                    info.getExtraInfo());
         }
         if (switchTo != null) {
             otherNetworkConnected = switchTo.isConnected();
             if (DBG) {
                 if (otherNetworkConnected) {
-                    Log.v(TAG, "Switching to already connected " + switchTo.getTypeName());
+                    Log.v(TAG, "Switching to already connected " +
+                            switchTo.getTypeName());
                 } else {
-                    Log.v(TAG, "Attempting to switch to " + switchTo.getTypeName());
+                    Log.v(TAG, "Attempting to switch to " +
+                            switchTo.getTypeName());
                 }
             }
-            intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
+            intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
+                    switchTo);
         } else {
             intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
         }
-        if (DBG) Log.v(TAG, "Sending DISCONNECT bcast for " + info.getTypeName() +
+        if (DBG) Log.v(TAG, "Sending DISCONNECT bcast for " +
+                info.getTypeName() +
                 (switchTo == null ? "" : " other=" + switchTo.getTypeName()));
 
         mContext.sendStickyBroadcast(intent);
         /*
-         * If the failover network is already connected, then immediately send out
-         * a followup broadcast indicating successful failover
+         * If the failover network is already connected, then immediately send
+         * out a followup broadcast indicating successful failover
          */
         if (switchTo != null && otherNetworkConnected)
             sendConnectedBroadcast(switchTo);
@@ -477,7 +494,8 @@
             intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
         }
         if (info.getExtraInfo() != null) {
-            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
+            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
+                    info.getExtraInfo());
         }
         mContext.sendStickyBroadcast(intent);
     }
@@ -499,9 +517,10 @@
                 } else {
                     reasonText = " (" + reason + ").";
                 }
-                Log.v(TAG, "Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
+                Log.v(TAG, "Attempt to connect to " + info.getTypeName() +
+                        " failed" + reasonText);
             }
-            
+
             Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
             intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
             intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
@@ -509,7 +528,8 @@
                 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
             }
             if (extraInfo != null) {
-                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
+                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
+                        extraInfo);
             }
             if (info.isFailover()) {
                 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
@@ -562,32 +582,34 @@
          */
         if (!toredown || deadnet.getNetworkInfo().getType() != info.getType()) {
             mActiveNetwork = thisNet;
-            if (DBG) Log.v(TAG, "Sending CONNECT bcast for " + info.getTypeName());
+            if (DBG) Log.v(TAG, "Sending CONNECT bcast for " +
+                    info.getTypeName());
             thisNet.updateNetworkSettings();
             sendConnectedBroadcast(info);
             if (isFailover) {
                 otherNet.releaseWakeLock();
             }
         } else {
-            if (DBG) Log.v(TAG, "Not broadcasting CONNECT_ACTION to torn down network " +
-                info.getTypeName());
+            if (DBG) Log.v(TAG, "Not broadcasting CONNECT_ACTION to torn " +
+                    "down network " + info.getTypeName());
         }
     }
 
     private void handleScanResultsAvailable(NetworkInfo info) {
         int networkType = info.getType();
         if (networkType != ConnectivityManager.TYPE_WIFI) {
-            if (DBG) Log.v(TAG, "Got ScanResultsAvailable for " + info.getTypeName() + " network."
-                + " Don't know how to handle.");
+            if (DBG) Log.v(TAG, "Got ScanResultsAvailable for " +
+                    info.getTypeName() + " network. Don't know how to handle.");
         }
-        
+
         mNetTrackers[networkType].interpretScanResultsAvailable();
     }
 
-    private void handleNotificationChange(boolean visible, int id, Notification notification) {
+    private void handleNotificationChange(boolean visible, int id,
+            Notification notification) {
         NotificationManager notificationManager = (NotificationManager) mContext
                 .getSystemService(Context.NOTIFICATION_SERVICE);
-        
+
         if (visible) {
             notificationManager.notify(id, notification);
         } else {
@@ -629,12 +651,15 @@
         int index = 1;
         String lastDns = "";
         int numConnectedNets = 0;
-        int incrValue = ConnectivityManager.TYPE_MOBILE - ConnectivityManager.TYPE_WIFI;
+        int incrValue = ConnectivityManager.TYPE_MOBILE -
+                ConnectivityManager.TYPE_WIFI;
         int stopValue = ConnectivityManager.TYPE_MOBILE + incrValue;
 
-        for (int netType = ConnectivityManager.TYPE_WIFI; netType != stopValue; netType += incrValue) {
+        for (int netType = ConnectivityManager.TYPE_WIFI; netType != stopValue;
+                netType += incrValue) {
             NetworkStateTracker nt = mNetTrackers[netType];
-            if (nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
+            if (nt.getNetworkInfo().isConnected() &&
+                    !nt.isTeardownRequested()) {
                 ++numConnectedNets;
                 String[] dnsList = nt.getNameServers();
                 for (int i = 0; i < dnsList.length && dnsList[i] != null; i++) {
@@ -652,23 +677,26 @@
         }
         mNumDnsEntries = index - 1;
         // Notify the name resolver library of the change
-        SystemProperties.set("net.dnschange", String.valueOf(sDnsChangeCounter++));
+        SystemProperties.set("net.dnschange",
+                String.valueOf(sDnsChangeCounter++));
         return numConnectedNets;
     }
 
     @Override
     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
+        if (mContext.checkCallingOrSelfPermission(
+                android.Manifest.permission.DUMP)
                 != PackageManager.PERMISSION_GRANTED) {
-            pw.println("Permission Denial: can't dump ConnectivityService from from pid="
-                    + Binder.getCallingPid()
-                    + ", uid=" + Binder.getCallingUid());
+            pw.println("Permission Denial: can't dump ConnectivityService " +
+                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
+                    Binder.getCallingUid());
             return;
         }
         if (mActiveNetwork == null) {
             pw.println("No active network");
         } else {
-            pw.println("Active network: " + mActiveNetwork.getNetworkInfo().getTypeName());
+            pw.println("Active network: " +
+                    mActiveNetwork.getNetworkInfo().getTypeName());
         }
         pw.println();
         for (NetworkStateTracker nst : mNetTrackers) {
@@ -685,29 +713,37 @@
             switch (msg.what) {
                 case NetworkStateTracker.EVENT_STATE_CHANGED:
                     info = (NetworkInfo) msg.obj;
-                    if (DBG) Log.v(TAG, "ConnectivityChange for " + info.getTypeName() + ": " +
+                    if (DBG) Log.v(TAG, "ConnectivityChange for " +
+                            info.getTypeName() + ": " +
                             info.getState() + "/" + info.getDetailedState());
 
                     // Connectivity state changed:
                     // [31-13] Reserved for future use
-                    // [12-9] Network subtype (for mobile network, as defined by TelephonyManager)
-                    // [8-3] Detailed state ordinal (as defined by NetworkInfo.DetailedState)
+                    // [12-9] Network subtype (for mobile network, as defined
+                    //         by TelephonyManager)
+                    // [8-3] Detailed state ordinal (as defined by
+                    //         NetworkInfo.DetailedState)
                     // [2-0] Network type (as defined by ConnectivityManager)
                     int eventLogParam = (info.getType() & 0x7) |
                             ((info.getDetailedState().ordinal() & 0x3f) << 3) |
                             (info.getSubtype() << 9);
-                    EventLog.writeEvent(EVENTLOG_CONNECTIVITY_STATE_CHANGED, eventLogParam);
-                    
-                    if (info.getDetailedState() == NetworkInfo.DetailedState.FAILED) {
+                    EventLog.writeEvent(EVENTLOG_CONNECTIVITY_STATE_CHANGED,
+                            eventLogParam);
+
+                    if (info.getDetailedState() ==
+                            NetworkInfo.DetailedState.FAILED) {
                         handleConnectionFailure(info);
-                    } else if (info.getState() == NetworkInfo.State.DISCONNECTED) {
+                    } else if (info.getState() ==
+                            NetworkInfo.State.DISCONNECTED) {
                         handleDisconnect(info);
                     } else if (info.getState() == NetworkInfo.State.SUSPENDED) {
                         // TODO: need to think this over.
-                        // the logic here is, handle SUSPENDED the same as DISCONNECTED. The
-                        // only difference being we are broadcasting an intent with NetworkInfo
-                        // that's suspended. This allows the applications an opportunity to
-                        // handle DISCONNECTED and SUSPENDED differently, or not.
+                        // the logic here is, handle SUSPENDED the same as
+                        // DISCONNECTED. The only difference being we are
+                        // broadcasting an intent with NetworkInfo that's
+                        // suspended. This allows the applications an
+                        // opportunity to handle DISCONNECTED and SUSPENDED
+                        // differently, or not.
                         handleDisconnect(info);
                     } else if (info.getState() == NetworkInfo.State.CONNECTED) {
                         handleConnect(info);
@@ -719,9 +755,10 @@
                     info = (NetworkInfo) msg.obj;
                     handleScanResultsAvailable(info);
                     break;
-                    
+
                 case NetworkStateTracker.EVENT_NOTIFICATION_CHANGED:
-                    handleNotificationChange(msg.arg1 == 1, msg.arg2, (Notification) msg.obj);
+                    handleNotificationChange(msg.arg1 == 1, msg.arg2,
+                            (Notification) msg.obj);
 
                 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
                     handleConfigurationChange();
diff --git a/services/java/com/android/server/HardwareService.java b/services/java/com/android/server/HardwareService.java
index 5bc9b5f..7597f85 100755
--- a/services/java/com/android/server/HardwareService.java
+++ b/services/java/com/android/server/HardwareService.java
@@ -37,6 +37,9 @@
 import android.os.SystemClock;
 import android.util.Log;
 
+import java.util.LinkedList;
+import java.util.ListIterator;
+
 public class HardwareService extends IHardwareService.Stub {
     private static final String TAG = "HardwareService";
 
@@ -50,9 +53,62 @@
     static final int LIGHT_FLASH_NONE = 0;
     static final int LIGHT_FLASH_TIMED = 1;
 
+    private final LinkedList<Vibration> mVibrations;
+    private Vibration mCurrentVibration;
+
     private boolean mAttentionLightOn;
     private boolean mPulsing;
 
+    private class Vibration implements IBinder.DeathRecipient {
+        private final IBinder mToken;
+        private final long    mTimeout;
+        private final long    mStartTime;
+        private final long[]  mPattern;
+        private final int     mRepeat;
+
+        Vibration(IBinder token, long millis) {
+            this(token, millis, null, 0);
+        }
+
+        Vibration(IBinder token, long[] pattern, int repeat) {
+            this(token, 0, pattern, repeat);
+        }
+
+        private Vibration(IBinder token, long millis, long[] pattern,
+                int repeat) {
+            mToken = token;
+            mTimeout = millis;
+            mStartTime = SystemClock.uptimeMillis();
+            mPattern = pattern;
+            mRepeat = repeat;
+        }
+
+        public void binderDied() {
+            synchronized (mVibrations) {
+                mVibrations.remove(this);
+                if (this == mCurrentVibration) {
+                    doCancelVibrateLocked();
+                    startNextVibrationLocked();
+                }
+            }
+        }
+
+        public boolean hasLongerTimeout(long millis) {
+            if (mTimeout == 0) {
+                // This is a pattern, return false to play the simple
+                // vibration.
+                return false;
+            }
+            if ((mStartTime + mTimeout)
+                    < (SystemClock.uptimeMillis() + millis)) {
+                // If this vibration will end before the time passed in, let
+                // the new vibration play.
+                return false;
+            }
+            return true;
+        }
+    }
+
     HardwareService(Context context) {
         // Reset the hardware to a default state, in case this is a runtime
         // restart instead of a fresh boot.
@@ -66,6 +122,8 @@
         mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
         mWakeLock.setReferenceCounted(true);
 
+        mVibrations = new LinkedList<Vibration>();
+
         mBatteryStats = BatteryStatsService.getService();
         
         IntentFilter filter = new IntentFilter();
@@ -78,13 +136,24 @@
         super.finalize();
     }
 
-    public void vibrate(long milliseconds) {
+    public void vibrate(long milliseconds, IBinder token) {
         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.VIBRATE)
                 != PackageManager.PERMISSION_GRANTED) {
             throw new SecurityException("Requires VIBRATE permission");
         }
-        doCancelVibrate();
-        vibratorOn(milliseconds);
+        if (mCurrentVibration != null
+                && mCurrentVibration.hasLongerTimeout(milliseconds)) {
+            // Ignore this vibration since the current vibration will play for
+            // longer than milliseconds.
+            return;
+        }
+        Vibration vib = new Vibration(token, milliseconds);
+        synchronized (mVibrations) {
+            removeVibrationLocked(token);
+            doCancelVibrateLocked();
+            mCurrentVibration = vib;
+            startVibrationLocked(vib);
+        }
     }
 
     private boolean isAll0(long[] pattern) {
@@ -121,34 +190,25 @@
                 return;
             }
 
-            synchronized (this) {
-                Death death = new Death(token);
-                try {
-                    token.linkToDeath(death, 0);
-                } catch (RemoteException e) {
-                    return;
+            Vibration vib = new Vibration(token, pattern, repeat);
+            try {
+                token.linkToDeath(vib, 0);
+            } catch (RemoteException e) {
+                return;
+            }
+
+            synchronized (mVibrations) {
+                removeVibrationLocked(token);
+                doCancelVibrateLocked();
+                if (repeat >= 0) {
+                    mVibrations.addFirst(vib);
+                    startNextVibrationLocked();
+                } else {
+                    // A negative repeat means that this pattern is not meant
+                    // to repeat. Treat it like a simple vibration.
+                    mCurrentVibration = vib;
+                    startVibrationLocked(vib);
                 }
-
-                Thread oldThread = mThread;
-
-                if (oldThread != null) {
-                    // stop the old one
-                    synchronized (mThread) {
-                        mThread.mDone = true;
-                        mThread.notify();
-                    }
-                }
-
-                if (mDeath != null) {
-                    mToken.unlinkToDeath(mDeath, 0);
-                }
-
-                mDeath = death;
-                mToken = token;
-
-                // start the new thread
-                mThread = new VibrateThread(pattern, repeat);
-                mThread.start();
             }
         }
         finally {
@@ -156,7 +216,7 @@
         }
     }
 
-    public void cancelVibrate() {
+    public void cancelVibrate(IBinder token) {
         mContext.enforceCallingOrSelfPermission(
                 android.Manifest.permission.VIBRATE,
                 "cancelVibrate");
@@ -164,7 +224,13 @@
         // so wakelock calls will succeed
         long identity = Binder.clearCallingIdentity();
         try {
-            doCancelVibrate();
+            synchronized (mVibrations) {
+                final Vibration vib = removeVibrationLocked(token);
+                if (vib == mCurrentVibration) {
+                    doCancelVibrateLocked();
+                    startNextVibrationLocked();
+                }
+            }
         }
         finally {
             Binder.restoreCallingIdentity(identity);
@@ -277,27 +343,74 @@
         }
     };
 
-    private void doCancelVibrate() {
-        synchronized (this) {
-            if (mThread != null) {
-                synchronized (mThread) {
-                    mThread.mDone = true;
-                    mThread.notify();
-                }
-                mThread = null;
+    private final Runnable mVibrationRunnable = new Runnable() {
+        public void run() {
+            synchronized (mVibrations) {
+                doCancelVibrateLocked();
+                startNextVibrationLocked();
             }
-            vibratorOff();
+        }
+    };
+
+    // Lock held on mVibrations
+    private void doCancelVibrateLocked() {
+        if (mThread != null) {
+            synchronized (mThread) {
+                mThread.mDone = true;
+                mThread.notify();
+            }
+            mThread = null;
+        }
+        vibratorOff();
+        mH.removeCallbacks(mVibrationRunnable);
+    }
+
+    // Lock held on mVibrations
+    private void startNextVibrationLocked() {
+        if (mVibrations.size() <= 0) {
+            return;
+        }
+        mCurrentVibration = mVibrations.getFirst();
+        startVibrationLocked(mCurrentVibration);
+    }
+
+    // Lock held on mVibrations
+    private void startVibrationLocked(final Vibration vib) {
+        if (vib.mTimeout != 0) {
+            vibratorOn(vib.mTimeout);
+            mH.postDelayed(mVibrationRunnable, vib.mTimeout);
+        } else {
+            // mThread better be null here. doCancelVibrate should always be
+            // called before startNextVibrationLocked or startVibrationLocked.
+            mThread = new VibrateThread(vib);
+            mThread.start();
         }
     }
 
+    // Lock held on mVibrations
+    private Vibration removeVibrationLocked(IBinder token) {
+        ListIterator<Vibration> iter = mVibrations.listIterator(0);
+        while (iter.hasNext()) {
+            Vibration vib = iter.next();
+            if (vib.mToken == token) {
+                iter.remove();
+                return vib;
+            }
+        }
+        // We might be looking for a simple vibration which is only stored in
+        // mCurrentVibration.
+        if (mCurrentVibration != null && mCurrentVibration.mToken == token) {
+            return mCurrentVibration;
+        }
+        return null;
+    }
+
     private class VibrateThread extends Thread {
-        long[] mPattern;
-        int mRepeat;
+        final Vibration mVibration;
         boolean mDone;
     
-        VibrateThread(long[] pattern, int repeat) {
-            mPattern = pattern;
-            mRepeat = repeat;
+        VibrateThread(Vibration vib) {
+            mVibration = vib;
             mWakeLock.acquire();
         }
 
@@ -323,8 +436,9 @@
             Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_DISPLAY);
             synchronized (this) {
                 int index = 0;
-                long[] pattern = mPattern;
+                long[] pattern = mVibration.mPattern;
                 int len = pattern.length;
+                int repeat = mVibration.mRepeat;
                 long duration = 0;
 
                 while (!mDone) {
@@ -347,50 +461,37 @@
                             HardwareService.this.vibratorOn(duration);
                         }
                     } else {
-                        if (mRepeat < 0) {
+                        if (repeat < 0) {
                             break;
                         } else {
-                            index = mRepeat;
+                            index = repeat;
                             duration = 0;
                         }
                     }
                 }
-                if (mDone) {
-                    // make sure vibrator is off if we were cancelled.
-                    // otherwise, it will turn off automatically 
-                    // when the last timeout expires.
-                    HardwareService.this.vibratorOff();
-                }
                 mWakeLock.release();
             }
-            synchronized (HardwareService.this) {
+            synchronized (mVibrations) {
                 if (mThread == this) {
                     mThread = null;
                 }
+                if (!mDone) {
+                    // If this vibration finished naturally, start the next
+                    // vibration.
+                    mVibrations.remove(mVibration);
+                    startNextVibrationLocked();
+                }
             }
         }
     };
 
-    private class Death implements IBinder.DeathRecipient {
-        IBinder mMe;
-
-        Death(IBinder me) {
-            mMe = me;
-        }
-
-        public void binderDied() {
-            synchronized (HardwareService.this) {
-                if (mMe == mToken) {
-                    doCancelVibrate();
-                }
-            }
-        }
-    }
-
     BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
         public void onReceive(Context context, Intent intent) {
             if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
-                doCancelVibrate();
+                synchronized (mVibrations) {
+                    doCancelVibrateLocked();
+                    mVibrations.clear();
+                }
             }
         }
     };
@@ -407,8 +508,6 @@
     private final IBatteryStats mBatteryStats;
     
     volatile VibrateThread mThread;
-    volatile Death mDeath;
-    volatile IBinder mToken;
 
     private int mNativePointer;
 
diff --git a/services/java/com/android/server/HeadsetObserver.java b/services/java/com/android/server/HeadsetObserver.java
index 9b0a2d4..bee3108 100644
--- a/services/java/com/android/server/HeadsetObserver.java
+++ b/services/java/com/android/server/HeadsetObserver.java
@@ -41,10 +41,16 @@
     private static final String HEADSET_STATE_PATH = "/sys/class/switch/h2w/state";
     private static final String HEADSET_NAME_PATH = "/sys/class/switch/h2w/name";
 
+    private static final int BIT_HEADSET = (1 << 0);
+    private static final int BIT_HEADSET_NO_MIC = (1 << 1);
+    private static final int BIT_TTY = (1 << 2);
+    private static final int BIT_FM_HEADSET = (1 << 3);
+    private static final int BIT_FM_SPEAKER = (1 << 4);
+
     private int mHeadsetState;
+    private int mPrevHeadsetState;
     private String mHeadsetName;
-    private boolean mAudioRouteNeedsUpdate;
-    private AudioManager mAudioManager;
+    private boolean mPendingIntent;
 
     private final Context mContext;
     private final WakeLock mWakeLock;  // held while there is a pending route change
@@ -76,6 +82,7 @@
 
         String newName = mHeadsetName;
         int newState = mHeadsetState;
+        mPrevHeadsetState = mHeadsetState;
         try {
             FileReader file = new FileReader(HEADSET_STATE_PATH);
             int len = file.read(buffer, 0, 1024);
@@ -91,20 +98,25 @@
             Log.e(TAG, "" , e);
         }
 
-        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
         update(newName, newState);
     }
 
     private synchronized final void update(String newName, int newState) {
         if (newName != mHeadsetName || newState != mHeadsetState) {
-            boolean isUnplug = (newState == 0 && mHeadsetState == 1);
+            boolean isUnplug = false;
+            if ( (mHeadsetState & BIT_HEADSET) > 0 || (mHeadsetState & BIT_HEADSET_NO_MIC) > 0) {
+                if ((newState & BIT_HEADSET) == 0 && (newState & BIT_HEADSET_NO_MIC) == 0)
+                    isUnplug = true;
+            }
             mHeadsetName = newName;
+            mPrevHeadsetState = mHeadsetState;
             mHeadsetState = newState;
-            mAudioRouteNeedsUpdate = true;
-
-            sendIntent(isUnplug);
+            mPendingIntent = true;
 
             if (isUnplug) {
+                Intent intent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
+                mContext.sendBroadcast(intent);
+
                 // It can take hundreds of ms flush the audio pipeline after
                 // apps pause audio playback, but audio route changes are
                 // immediate, so delay the route change by 1000ms.
@@ -113,12 +125,13 @@
                 mWakeLock.acquire();
                 mHandler.sendEmptyMessageDelayed(0, 1000);
             } else {
-                updateAudioRoute();
+                sendIntent();
+                mPendingIntent = false;
             }
         }
     }
 
-    private synchronized final void sendIntent(boolean isUnplug) {
+    private synchronized final void sendIntent() {
         //  Pack up the values and broadcast them to everyone
         Intent intent = new Intent(Intent.ACTION_HEADSET_PLUG);
         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
@@ -128,24 +141,15 @@
 
         // TODO: Should we require a permission?
         ActivityManagerNative.broadcastStickyIntent(intent, null);
-
-        if (isUnplug) {
-            intent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
-            mContext.sendBroadcast(intent);
-        }
-    }
-
-    private synchronized final void updateAudioRoute() {
-        if (mAudioRouteNeedsUpdate) {
-            mAudioManager.setWiredHeadsetOn(mHeadsetState == 1);
-            mAudioRouteNeedsUpdate = false;
-        }
     }
 
     private final Handler mHandler = new Handler() {
         @Override
         public void handleMessage(Message msg) {
-            updateAudioRoute();
+            if (mPendingIntent) {
+                sendIntent();
+                mPendingIntent = false;
+            }
             mWakeLock.release();
         }
     };
diff --git a/services/java/com/android/server/InputDevice.java b/services/java/com/android/server/InputDevice.java
index 7b8a2a4..0ac5740 100644
--- a/services/java/com/android/server/InputDevice.java
+++ b/services/java/com/android/server/InputDevice.java
@@ -26,6 +26,9 @@
     /** Amount that trackball needs to move in order to generate a key event. */
     static final int TRACKBALL_MOVEMENT_THRESHOLD = 6;
 
+    /** Maximum number of pointers we will track and report. */
+    static final int MAX_POINTERS = 2;
+    
     final int id;
     final int classes;
     final String name;
@@ -34,7 +37,7 @@
     final AbsoluteInfo absPressure;
     final AbsoluteInfo absSize;
     
-    long mDownTime = 0;
+    long mKeyDownTime = 0;
     int mMetaKeysState = 0;
     
     final MotionState mAbs = new MotionState(0, 0);
@@ -48,13 +51,13 @@
         float yMoveScale;
         MotionEvent currentMove = null;
         boolean changed = false;
-        boolean down = false;
-        boolean lastDown = false;
-        long downTime = 0;
-        int x = 0;
-        int y = 0;
-        int pressure = 1;
-        int size = 0;
+        boolean mLastAnyDown = false;
+        long mDownTime = 0;
+        final boolean[] mLastDown = new boolean[MAX_POINTERS];
+        final boolean[] mDown = new boolean[MAX_POINTERS];
+        final int[] mLastData = new int[MotionEvent.NUM_SAMPLE_DATA * MAX_POINTERS];
+        final int[] mCurData = new int[MotionEvent.NUM_SAMPLE_DATA * MAX_POINTERS];
+        final float[] mReportData = new float[MotionEvent.NUM_SAMPLE_DATA * MAX_POINTERS];
         
         MotionState(int mx, int my) {
             xPrecision = mx;
@@ -63,131 +66,256 @@
             yMoveScale = my != 0 ? (1.0f/my) : 1.0f;
         }
         
-        MotionEvent generateMotion(InputDevice device, long curTime,
-                boolean isAbs, Display display, int orientation,
+        MotionEvent generateAbsMotion(InputDevice device, long curTime,
+                long curTimeNano, Display display, int orientation,
                 int metaState) {
-            if (!changed) {
+            
+            final float[] scaled = mReportData;
+            final int[] cur = mCurData;
+            
+            boolean anyDown = false;
+            int firstDownChanged = -1;
+            int numPointers = 0;
+            for (int i=0; i<MAX_POINTERS; i++) {
+                boolean d = mDown[i];
+                anyDown |= d;
+                if (d != mLastDown[i] && firstDownChanged < 0) {
+                    firstDownChanged = i;
+                    mLastDown[i] = mDown[i];
+                    d = true;
+                }
+                
+                if (d) {
+                    final int src = i * MotionEvent.NUM_SAMPLE_DATA;
+                    final int dest = numPointers * MotionEvent.NUM_SAMPLE_DATA;
+                    numPointers++;
+                    scaled[dest + MotionEvent.SAMPLE_X] = cur[src + MotionEvent.SAMPLE_X];
+                    scaled[dest + MotionEvent.SAMPLE_Y] = cur[src + MotionEvent.SAMPLE_Y];
+                    scaled[dest + MotionEvent.SAMPLE_PRESSURE] = cur[src + MotionEvent.SAMPLE_PRESSURE];
+                    scaled[dest + MotionEvent.SAMPLE_SIZE] = cur[src + MotionEvent.SAMPLE_SIZE];
+                }
+            }
+            
+            if (numPointers <= 0) {
                 return null;
             }
             
-            float scaledX = x;
-            float scaledY = y;
-            float temp;
-            float scaledPressure = 1.0f;
-            float scaledSize = 0;
+            int action;
             int edgeFlags = 0;
-            if (isAbs) {
-                int w = display.getWidth()-1;
-                int h = display.getHeight()-1;
-                if (orientation == Surface.ROTATION_90
-                        || orientation == Surface.ROTATION_270) {
-                    int tmp = w;
-                    w = h;
-                    h = tmp;
+            if (anyDown != mLastAnyDown) {
+                final AbsoluteInfo absX = device.absX;
+                final AbsoluteInfo absY = device.absY;
+                if (anyDown && absX != null && absY != null) {
+                    // We don't let downs start unless we are
+                    // inside of the screen.  There are two reasons for
+                    // this: to avoid spurious touches when holding
+                    // the edges of the device near the touchscreen,
+                    // and to avoid reporting events if there are virtual
+                    // keys on the touchscreen outside of the display
+                    // area.
+                    // Note that we are only looking at the first pointer,
+                    // since what we are handling here is the first pointer
+                    // going down, and this is the coordinate that will be
+                    // used to dispatch the event.
+                    if (cur[MotionEvent.SAMPLE_X] < absX.minValue
+                            || cur[MotionEvent.SAMPLE_X] > absX.maxValue
+                            || cur[MotionEvent.SAMPLE_Y] < absY.minValue
+                            || cur[MotionEvent.SAMPLE_Y] > absY.maxValue) {
+                        if (false) Log.v("InputDevice", "Rejecting ("
+                                + cur[MotionEvent.SAMPLE_X] + ","
+                                + cur[MotionEvent.SAMPLE_Y] + "): outside of ("
+                                + absX.minValue + "," + absY.minValue
+                                + ")-(" + absX.maxValue + ","
+                                + absY.maxValue + ")");
+                        return null;
+                    }
                 }
-                if (device.absX != null) {
-                    scaledX = ((scaledX-device.absX.minValue)
-                                / device.absX.range) * w;
-                }
-                if (device.absY != null) {
-                    scaledY = ((scaledY-device.absY.minValue)
-                                / device.absY.range) * h;
-                }
-                if (device.absPressure != null) {
-                    scaledPressure = 
-                        ((pressure-device.absPressure.minValue)
-                                / (float)device.absPressure.range);
-                }
-                if (device.absSize != null) {
-                    scaledSize = 
-                        ((size-device.absSize.minValue)
-                                / (float)device.absSize.range);
-                }
-                switch (orientation) {
-                    case Surface.ROTATION_90:
-                        temp = scaledX;
-                        scaledX = scaledY;
-                        scaledY = w-temp;
-                        break;
-                    case Surface.ROTATION_180:
-                        scaledX = w-scaledX;
-                        scaledY = h-scaledY;
-                        break;
-                    case Surface.ROTATION_270:
-                        temp = scaledX;
-                        scaledX = h-scaledY;
-                        scaledY = temp;
-                        break;
-                }
-
-                if (scaledX == 0) {
-                    edgeFlags += MotionEvent.EDGE_LEFT;
-                } else if (scaledX == display.getWidth() - 1.0f) {
-                    edgeFlags += MotionEvent.EDGE_RIGHT;
-                }
-                
-                if (scaledY == 0) {
-                    edgeFlags += MotionEvent.EDGE_TOP;
-                } else if (scaledY == display.getHeight() - 1.0f) {
-                    edgeFlags += MotionEvent.EDGE_BOTTOM;
-                }
-                
-            } else {
-                scaledX *= xMoveScale;
-                scaledY *= yMoveScale;
-                switch (orientation) {
-                    case Surface.ROTATION_90:
-                        temp = scaledX;
-                        scaledX = scaledY;
-                        scaledY = -temp;
-                        break;
-                    case Surface.ROTATION_180:
-                        scaledX = -scaledX;
-                        scaledY = -scaledY;
-                        break;
-                    case Surface.ROTATION_270:
-                        temp = scaledX;
-                        scaledX = -scaledY;
-                        scaledY = temp;
-                        break;
-                }
-            }
-            
-            changed = false;
-            if (down != lastDown) {
-                int action;
-                lastDown = down;
-                if (down) {
+                mLastAnyDown = anyDown;
+                if (anyDown) {
                     action = MotionEvent.ACTION_DOWN;
-                    downTime = curTime;
+                    mDownTime = curTime;
                 } else {
                     action = MotionEvent.ACTION_UP;
                 }
                 currentMove = null;
-                if (!isAbs) {
-                    x = y = 0;
+            } else if (firstDownChanged >= 0) {
+                if (mDown[firstDownChanged]) {
+                    action = MotionEvent.ACTION_POINTER_DOWN
+                            | (firstDownChanged << MotionEvent.ACTION_POINTER_SHIFT);
+                } else {
+                    action = MotionEvent.ACTION_POINTER_UP
+                            | (firstDownChanged << MotionEvent.ACTION_POINTER_SHIFT);
                 }
-                return MotionEvent.obtain(downTime, curTime, action,
-                        scaledX, scaledY, scaledPressure, scaledSize, metaState,
-                        xPrecision, yPrecision, device.id, edgeFlags);
+                currentMove = null;
             } else {
-                if (currentMove != null) {
-                    if (false) Log.i("InputDevice", "Adding batch x=" + scaledX
-                            + " y=" + scaledY + " to " + currentMove);
-                    currentMove.addBatch(curTime, scaledX, scaledY,
-                            scaledPressure, scaledSize, metaState);
-                    if (WindowManagerPolicy.WATCH_POINTER) {
-                        Log.i("KeyInputQueue", "Updating: " + currentMove);
-                    }
-                    return null;
-                }
-                MotionEvent me = MotionEvent.obtain(downTime, curTime,
-                        MotionEvent.ACTION_MOVE, scaledX, scaledY,
-                        scaledPressure, scaledSize, metaState,
-                        xPrecision, yPrecision, device.id, edgeFlags);
-                currentMove = me;
-                return me;
+                action = MotionEvent.ACTION_MOVE;
             }
+            
+            final int dispW = display.getWidth()-1;
+            final int dispH = display.getHeight()-1;
+            int w = dispW;
+            int h = dispH;
+            if (orientation == Surface.ROTATION_90
+                    || orientation == Surface.ROTATION_270) {
+                int tmp = w;
+                w = h;
+                h = tmp;
+            }
+            
+            final AbsoluteInfo absX = device.absX;
+            final AbsoluteInfo absY = device.absY;
+            final AbsoluteInfo absPressure = device.absPressure;
+            final AbsoluteInfo absSize = device.absSize;
+            for (int i=0; i<numPointers; i++) {
+                final int j = i * MotionEvent.NUM_SAMPLE_DATA;
+            
+                if (absX != null) {
+                    scaled[j + MotionEvent.SAMPLE_X] =
+                            ((scaled[j + MotionEvent.SAMPLE_X]-absX.minValue)
+                                / absX.range) * w;
+                }
+                if (absY != null) {
+                    scaled[j + MotionEvent.SAMPLE_Y] =
+                            ((scaled[j + MotionEvent.SAMPLE_Y]-absY.minValue)
+                                / absY.range) * h;
+                }
+                if (absPressure != null) {
+                    scaled[j + MotionEvent.SAMPLE_PRESSURE] = 
+                            ((scaled[j + MotionEvent.SAMPLE_PRESSURE]-absPressure.minValue)
+                                / (float)absPressure.range);
+                }
+                if (absSize != null) {
+                    scaled[j + MotionEvent.SAMPLE_SIZE] = 
+                            ((scaled[j + MotionEvent.SAMPLE_SIZE]-absSize.minValue)
+                                / (float)absSize.range);
+                }
+                
+                switch (orientation) {
+                    case Surface.ROTATION_90: {
+                        final float temp = scaled[MotionEvent.SAMPLE_X];
+                        scaled[j + MotionEvent.SAMPLE_X] = scaled[j + MotionEvent.SAMPLE_Y];
+                        scaled[j + MotionEvent.SAMPLE_Y] = w-temp;
+                        break;
+                    }
+                    case Surface.ROTATION_180: {
+                        scaled[j + MotionEvent.SAMPLE_X] = w-scaled[j + MotionEvent.SAMPLE_X];
+                        scaled[j + MotionEvent.SAMPLE_Y] = h-scaled[j + MotionEvent.SAMPLE_Y];
+                        break;
+                    }
+                    case Surface.ROTATION_270: {
+                        final float temp = scaled[i + MotionEvent.SAMPLE_X];
+                        scaled[j + MotionEvent.SAMPLE_X] = h-scaled[j + MotionEvent.SAMPLE_Y];
+                        scaled[j + MotionEvent.SAMPLE_Y] = temp;
+                        break;
+                    }
+                }
+            }
+            
+            // We only consider the first pointer when computing the edge
+            // flags, since they are global to the event.
+            if (action == MotionEvent.ACTION_DOWN) {
+                if (scaled[MotionEvent.SAMPLE_X] <= 0) {
+                    edgeFlags |= MotionEvent.EDGE_LEFT;
+                } else if (scaled[MotionEvent.SAMPLE_X] >= dispW) {
+                    edgeFlags |= MotionEvent.EDGE_RIGHT;
+                }
+                if (scaled[MotionEvent.SAMPLE_Y] <= 0) {
+                    edgeFlags |= MotionEvent.EDGE_TOP;
+                } else if (scaled[MotionEvent.SAMPLE_Y] >= dispH) {
+                    edgeFlags |= MotionEvent.EDGE_BOTTOM;
+                }
+            }
+            
+            if (currentMove != null) {
+                if (false) Log.i("InputDevice", "Adding batch x="
+                        + scaled[MotionEvent.SAMPLE_X]
+                        + " y=" + scaled[MotionEvent.SAMPLE_Y]
+                        + " to " + currentMove);
+                currentMove.addBatch(curTime, scaled, metaState);
+                if (WindowManagerPolicy.WATCH_POINTER) {
+                    Log.i("KeyInputQueue", "Updating: " + currentMove);
+                }
+                return null;
+            }
+            
+            MotionEvent me = MotionEvent.obtainNano(mDownTime, curTime,
+                    curTimeNano, action, numPointers, scaled, metaState,
+                    xPrecision, yPrecision, device.id, edgeFlags);
+            if (action == MotionEvent.ACTION_MOVE) {
+                currentMove = me;
+            }
+            return me;
+        }
+        
+        MotionEvent generateRelMotion(InputDevice device, long curTime,
+                long curTimeNano, int orientation, int metaState) {
+            
+            final float[] scaled = mReportData;
+            
+            // For now we only support 1 pointer with relative motions.
+            scaled[MotionEvent.SAMPLE_X] = mCurData[MotionEvent.SAMPLE_X];
+            scaled[MotionEvent.SAMPLE_Y] = mCurData[MotionEvent.SAMPLE_Y];
+            scaled[MotionEvent.SAMPLE_PRESSURE] = 1.0f;
+            scaled[MotionEvent.SAMPLE_SIZE] = 0;
+            int edgeFlags = 0;
+            
+            int action;
+            if (mDown[0] != mLastDown[0]) {
+                mCurData[MotionEvent.SAMPLE_X] =
+                        mCurData[MotionEvent.SAMPLE_Y] = 0;
+                mLastDown[0] = mDown[0];
+                if (mDown[0]) {
+                    action = MotionEvent.ACTION_DOWN;
+                    mDownTime = curTime;
+                } else {
+                    action = MotionEvent.ACTION_UP;
+                }
+                currentMove = null;
+            } else {
+                action = MotionEvent.ACTION_MOVE;
+            }
+            
+            scaled[MotionEvent.SAMPLE_X] *= xMoveScale;
+            scaled[MotionEvent.SAMPLE_Y] *= yMoveScale;
+            switch (orientation) {
+                case Surface.ROTATION_90: {
+                    final float temp = scaled[MotionEvent.SAMPLE_X];
+                    scaled[MotionEvent.SAMPLE_X] = scaled[MotionEvent.SAMPLE_Y];
+                    scaled[MotionEvent.SAMPLE_Y] = -temp;
+                    break;
+                }
+                case Surface.ROTATION_180: {
+                    scaled[MotionEvent.SAMPLE_X] = -scaled[MotionEvent.SAMPLE_X];
+                    scaled[MotionEvent.SAMPLE_Y] = -scaled[MotionEvent.SAMPLE_Y];
+                    break;
+                }
+                case Surface.ROTATION_270: {
+                    final float temp = scaled[MotionEvent.SAMPLE_X];
+                    scaled[MotionEvent.SAMPLE_X] = -scaled[MotionEvent.SAMPLE_Y];
+                    scaled[MotionEvent.SAMPLE_Y] = temp;
+                    break;
+                }
+            }
+            
+            if (currentMove != null) {
+                if (false) Log.i("InputDevice", "Adding batch x="
+                        + scaled[MotionEvent.SAMPLE_X]
+                        + " y=" + scaled[MotionEvent.SAMPLE_Y]
+                        + " to " + currentMove);
+                currentMove.addBatch(curTime, scaled, metaState);
+                if (WindowManagerPolicy.WATCH_POINTER) {
+                    Log.i("KeyInputQueue", "Updating: " + currentMove);
+                }
+                return null;
+            }
+            
+            MotionEvent me = MotionEvent.obtainNano(mDownTime, curTime,
+                    curTimeNano, action, 1, scaled, metaState,
+                    xPrecision, yPrecision, device.id, edgeFlags);
+            if (action == MotionEvent.ACTION_MOVE) {
+                currentMove = me;
+            }
+            return me;
         }
     }
     
diff --git a/services/java/com/android/server/KeyInputQueue.java b/services/java/com/android/server/KeyInputQueue.java
index 411cd6b..e0ee7ed 100644
--- a/services/java/com/android/server/KeyInputQueue.java
+++ b/services/java/com/android/server/KeyInputQueue.java
@@ -18,10 +18,13 @@
 
 import android.content.Context;
 import android.content.res.Configuration;
-import android.os.SystemClock;
+import android.os.Environment;
+import android.os.LatencyTimer;
 import android.os.PowerManager;
+import android.os.SystemClock;
 import android.util.Log;
 import android.util.SparseArray;
+import android.util.Xml;
 import android.view.Display;
 import android.view.KeyEvent;
 import android.view.MotionEvent;
@@ -29,10 +32,29 @@
 import android.view.Surface;
 import android.view.WindowManagerPolicy;
 
+import com.android.internal.util.XmlUtils;
+
+import org.xmlpull.v1.XmlPullParser;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+
 public abstract class KeyInputQueue {
     static final String TAG = "KeyInputQueue";
 
-    SparseArray<InputDevice> mDevices = new SparseArray<InputDevice>();
+    static final boolean DEBUG_VIRTUAL_KEYS = false;
+    
+    private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
+
+    final SparseArray<InputDevice> mDevices = new SparseArray<InputDevice>();
+    final ArrayList<VirtualKey> mVirtualKeys = new ArrayList<VirtualKey>();
+    final HapticFeedbackCallback mHapticFeedbackCallback;
     
     int mGlobalMetaState = 0;
     boolean mHaveGlobalMetaState = false;
@@ -43,10 +65,14 @@
     int mCacheCount;
 
     Display mDisplay = null;
+    int mDisplayWidth;
+    int mDisplayHeight;
     
     int mOrientation = Surface.ROTATION_0;
     int[] mKeyRotationMap = null;
     
+    VirtualKey mPressedVirtualKey = null;
+    
     PowerManager.WakeLock mWakeLock;
 
     static final int[] KEY_90_MAP = new int[] {
@@ -73,14 +99,21 @@
     public static final int FILTER_REMOVE = 0;
     public static final int FILTER_KEEP = 1;
     public static final int FILTER_ABORT = -1;
-    
+
+    private static final boolean MEASURE_LATENCY = false;
+    private LatencyTimer lt;
+
     public interface FilterCallback {
         int filterEvent(QueuedEvent ev);
     }
     
+    public interface HapticFeedbackCallback {
+        void virtualKeyFeedback(KeyEvent event);
+    }
+    
     static class QueuedEvent {
         InputDevice inputDevice;
-        long when;
+        long whenNano;
         int flags; // From the raw event
         int classType; // One of the class constants in InputEvent
         Object event;
@@ -88,7 +121,7 @@
 
         void copyFrom(QueuedEvent that) {
             this.inputDevice = that.inputDevice;
-            this.when = that.when;
+            this.whenNano = that.whenNano;
             this.flags = that.flags;
             this.classType = that.classType;
             this.event = that.event;
@@ -106,7 +139,145 @@
         QueuedEvent next;
     }
 
-    KeyInputQueue(Context context) {
+    /**
+     * A key that exists as a part of the touch-screen, outside of the normal
+     * display area of the screen.
+     */
+    static class VirtualKey {
+        int scancode;
+        int centerx;
+        int centery;
+        int width;
+        int height;
+        
+        int hitLeft;
+        int hitTop;
+        int hitRight;
+        int hitBottom;
+        
+        InputDevice lastDevice;
+        int lastKeycode;
+        
+        boolean checkHit(int x, int y) {
+            return (x >= hitLeft && x <= hitRight
+                    && y >= hitTop && y <= hitBottom);
+        }
+        
+        void computeHitRect(InputDevice dev, int dw, int dh) {
+            if (dev == lastDevice) {
+                return;
+            }
+            
+            if (DEBUG_VIRTUAL_KEYS) Log.v(TAG, "computeHitRect for " + scancode
+                    + ": dev=" + dev + " absX=" + dev.absX + " absY=" + dev.absY);
+            
+            lastDevice = dev;
+            
+            int minx = dev.absX.minValue;
+            int maxx = dev.absX.maxValue;
+            
+            int halfw = width/2;
+            int left = centerx - halfw;
+            int right = centerx + halfw;
+            hitLeft = minx + ((left*maxx-minx)/dw);
+            hitRight = minx + ((right*maxx-minx)/dw);
+            
+            int miny = dev.absY.minValue;
+            int maxy = dev.absY.maxValue;
+            
+            int halfh = height/2;
+            int top = centery - halfh;
+            int bottom = centery + halfh;
+            hitTop = miny + ((top*maxy-miny)/dh);
+            hitBottom = miny + ((bottom*maxy-miny)/dh);
+        }
+    }
+
+    private void readVirtualKeys() {
+        try {
+            FileInputStream fis = new FileInputStream(
+                    "/sys/board_properties/virtualkeys.synaptics-rmi-touchscreen");
+            InputStreamReader isr = new InputStreamReader(fis);
+            BufferedReader br = new BufferedReader(isr);
+            String str = br.readLine();
+            if (str != null) {
+                String[] it = str.split(":");
+                if (DEBUG_VIRTUAL_KEYS) Log.v(TAG, "***** VIRTUAL KEYS: " + it);
+                final int N = it.length-6;
+                for (int i=0; i<=N; i+=6) {
+                    if (!"0x01".equals(it[i])) {
+                        Log.w(TAG, "Unknown virtual key type at elem #" + i
+                                + ": " + it[i]);
+                        continue;
+                    }
+                    try {
+                        VirtualKey sb = new VirtualKey();
+                        sb.scancode = Integer.parseInt(it[i+1]);
+                        sb.centerx = Integer.parseInt(it[i+2]);
+                        sb.centery = Integer.parseInt(it[i+3]);
+                        sb.width = Integer.parseInt(it[i+4]);
+                        sb.height = Integer.parseInt(it[i+5]);
+                        if (DEBUG_VIRTUAL_KEYS) Log.v(TAG, "Virtual key "
+                                + sb.scancode + ": center=" + sb.centerx + ","
+                                + sb.centery + " size=" + sb.width + "x"
+                                + sb.height);
+                        mVirtualKeys.add(sb);
+                    } catch (NumberFormatException e) {
+                        Log.w(TAG, "Bad number at region " + i + " in: "
+                                + str, e);
+                    }
+                }
+            }
+            br.close();
+        } catch (FileNotFoundException e) {
+            Log.i(TAG, "No virtual keys found");
+        } catch (IOException e) {
+            Log.w(TAG, "Error reading virtual keys", e);
+        }
+    }
+
+    private void readExcludedDevices() {
+        // Read partner-provided list of excluded input devices
+        XmlPullParser parser = null;
+        // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
+        File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
+        FileReader confreader = null;
+        try {
+            confreader = new FileReader(confFile);
+            parser = Xml.newPullParser();
+            parser.setInput(confreader);
+            XmlUtils.beginDocument(parser, "devices");
+
+            while (true) {
+                XmlUtils.nextElement(parser);
+                if (!"device".equals(parser.getName())) {
+                    break;
+                }
+                String name = parser.getAttributeValue(null, "name");
+                if (name != null) {
+                    Log.d(TAG, "addExcludedDevice " + name);
+                    addExcludedDevice(name);
+                }
+            }
+        } catch (FileNotFoundException e) {
+            // It's ok if the file does not exist.
+        } catch (Exception e) {
+            Log.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
+        } finally {
+            try { if (confreader != null) confreader.close(); } catch (IOException e) { }
+        }
+    }
+
+    KeyInputQueue(Context context, HapticFeedbackCallback  hapticFeedbackCallback) {
+        if (MEASURE_LATENCY) {
+            lt = new LatencyTimer(100, 1000);
+        }
+
+        mHapticFeedbackCallback = hapticFeedbackCallback;
+        
+        readVirtualKeys();
+        readExcludedDevices();
+        
         PowerManager pm = (PowerManager)context.getSystemService(
                                                         Context.POWER_SERVICE);
         mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
@@ -123,6 +294,12 @@
 
     public void setDisplay(Display display) {
         mDisplay = display;
+        
+        // We assume at this point that the display dimensions reflect the
+        // natural, unrotated display.  We will perform hit tests for soft
+        // buttons based on that display.
+        mDisplayWidth = display.getWidth();
+        mDisplayHeight = display.getHeight();
     }
     
     public void getInputConfiguration(Configuration config) {
@@ -157,6 +334,7 @@
     
     public static native String getDeviceName(int deviceId);
     public static native int getDeviceClasses(int deviceId);
+    public static native void addExcludedDevice(String deviceName);
     public static native boolean getAbsoluteInfo(int deviceId, int axis,
             InputDevice.AbsoluteInfo outInfo);
     public static native int getSwitchState(int sw);
@@ -165,6 +343,7 @@
     public static native int getScancodeState(int deviceId, int sw);
     public static native int getKeycodeState(int sw);
     public static native int getKeycodeState(int deviceId, int sw);
+    public static native int scancodeToKeycode(int deviceId, int scancode);
     public static native boolean hasKeys(int[] keycodes, boolean[] keyExists);
     
     public static KeyEvent newKeyEvent(InputDevice device, long downTime,
@@ -181,6 +360,7 @@
     
     Thread mThread = new Thread("InputDeviceReader") {
         public void run() {
+            Log.d(TAG, "InputDeviceReader.run()");
             android.os.Process.setThreadPriority(
                     android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);
             
@@ -241,7 +421,7 @@
                     
                     if (configChanged) {
                         synchronized (mFirst) {
-                            addLocked(di, SystemClock.uptimeMillis(), 0,
+                            addLocked(di, System.nanoTime(), 0,
                                     RawInputEvent.CLASS_CONFIGURATION_CHANGED,
                                     null);
                         }
@@ -256,6 +436,7 @@
                         // timebase as SystemClock.uptimeMillis().
                         //curTime = gotOne ? ev.when : SystemClock.uptimeMillis();
                         final long curTime = SystemClock.uptimeMillis();
+                        final long curTimeNano = System.nanoTime();
                         //Log.i(TAG, "curTime=" + curTime + ", systemClock=" + SystemClock.uptimeMillis());
                         
                         final int classes = di.classes;
@@ -271,14 +452,14 @@
                             boolean down;
                             if (ev.value != 0) {
                                 down = true;
-                                di.mDownTime = curTime;
+                                di.mKeyDownTime = curTime;
                             } else {
                                 down = false;
                             }
                             int keycode = rotateKeyCodeLocked(ev.keycode);
-                            addLocked(di, curTime, ev.flags,
+                            addLocked(di, curTimeNano, ev.flags,
                                     RawInputEvent.CLASS_KEYBOARD,
-                                    newKeyEvent(di, di.mDownTime, curTime, down,
+                                    newKeyEvent(di, di.mKeyDownTime, curTime, down,
                                             keycode, 0, scancode,
                                             ((ev.flags & WindowManagerPolicy.FLAG_WOKE_HERE) != 0)
                                              ? KeyEvent.FLAG_WOKE_HERE : 0));
@@ -286,29 +467,47 @@
                             if (ev.scancode == RawInputEvent.BTN_TOUCH &&
                                     (classes&RawInputEvent.CLASS_TOUCHSCREEN) != 0) {
                                 di.mAbs.changed = true;
-                                di.mAbs.down = ev.value != 0;
-                            }
-                            if (ev.scancode == RawInputEvent.BTN_MOUSE &&
+                                di.mAbs.mDown[0] = ev.value != 0;
+                            } else if (ev.scancode == RawInputEvent.BTN_2 &&
+                                    (classes&RawInputEvent.CLASS_TOUCHSCREEN) != 0) {
+                                di.mAbs.changed = true;
+                                di.mAbs.mDown[1] = ev.value != 0;
+                            } else if (ev.scancode == RawInputEvent.BTN_MOUSE &&
                                     (classes&RawInputEvent.CLASS_TRACKBALL) != 0) {
                                 di.mRel.changed = true;
-                                di.mRel.down = ev.value != 0;
+                                di.mRel.mDown[0] = ev.value != 0;
                                 send = true;
                             }
     
                         } else if (ev.type == RawInputEvent.EV_ABS &&
                                 (classes&RawInputEvent.CLASS_TOUCHSCREEN) != 0) {
+                            // Finger 1
                             if (ev.scancode == RawInputEvent.ABS_X) {
                                 di.mAbs.changed = true;
-                                di.mAbs.x = ev.value;
+                                di.mAbs.mCurData[MotionEvent.SAMPLE_X] = ev.value;
                             } else if (ev.scancode == RawInputEvent.ABS_Y) {
                                 di.mAbs.changed = true;
-                                di.mAbs.y = ev.value;
+                                di.mAbs.mCurData[MotionEvent.SAMPLE_Y] = ev.value;
                             } else if (ev.scancode == RawInputEvent.ABS_PRESSURE) {
                                 di.mAbs.changed = true;
-                                di.mAbs.pressure = ev.value;
+                                di.mAbs.mCurData[MotionEvent.SAMPLE_PRESSURE] = ev.value;
+                                di.mAbs.mCurData[MotionEvent.NUM_SAMPLE_DATA
+                                                 + MotionEvent.SAMPLE_PRESSURE] = ev.value;
                             } else if (ev.scancode == RawInputEvent.ABS_TOOL_WIDTH) {
                                 di.mAbs.changed = true;
-                                di.mAbs.size = ev.value;
+                                di.mAbs.mCurData[MotionEvent.SAMPLE_SIZE] = ev.value;
+                                di.mAbs.mCurData[MotionEvent.NUM_SAMPLE_DATA
+                                                 + MotionEvent.SAMPLE_SIZE] = ev.value;
+
+                            // Finger 2
+                            } else if (ev.scancode == RawInputEvent.ABS_HAT0X) {
+                                di.mAbs.changed = true;
+                                di.mAbs.mCurData[MotionEvent.NUM_SAMPLE_DATA
+                                                 + MotionEvent.SAMPLE_X] = ev.value;
+                            } else if (ev.scancode == RawInputEvent.ABS_HAT0Y) {
+                                di.mAbs.changed = true;
+                                di.mAbs.mCurData[MotionEvent.NUM_SAMPLE_DATA
+                                                 + MotionEvent.SAMPLE_Y] = ev.value;
                             }
     
                         } else if (ev.type == RawInputEvent.EV_REL &&
@@ -316,10 +515,10 @@
                             // Add this relative movement into our totals.
                             if (ev.scancode == RawInputEvent.REL_X) {
                                 di.mRel.changed = true;
-                                di.mRel.x += ev.value;
+                                di.mRel.mCurData[MotionEvent.SAMPLE_X] += ev.value;
                             } else if (ev.scancode == RawInputEvent.REL_Y) {
                                 di.mRel.changed = true;
-                                di.mRel.y += ev.value;
+                                di.mRel.mCurData[MotionEvent.SAMPLE_Y] += ev.value;
                             }
                         }
                         
@@ -330,36 +529,182 @@
                                 }
                                 
                                 MotionEvent me;
-                                me = di.mAbs.generateMotion(di, curTime, true,
-                                        mDisplay, mOrientation, mGlobalMetaState);
-                                if (false) Log.v(TAG, "Absolute: x=" + di.mAbs.x
-                                        + " y=" + di.mAbs.y + " ev=" + me);
-                                if (me != null) {
-                                    if (WindowManagerPolicy.WATCH_POINTER) {
-                                        Log.i(TAG, "Enqueueing: " + me);
+                                
+                                InputDevice.MotionState ms = di.mAbs;
+                                if (ms.changed) {
+                                    ms.changed = false;
+                                    
+                                    boolean doMotion = true;
+                                    
+                                    // Look for virtual buttons.
+                                    VirtualKey vk = mPressedVirtualKey;
+                                    if (vk != null) {
+                                        doMotion = false;
+                                        if (!ms.mDown[0]) {
+                                            mPressedVirtualKey = null;
+                                            ms.mLastDown[0] = ms.mDown[0];
+                                            if (DEBUG_VIRTUAL_KEYS) Log.v(TAG,
+                                                    "Generate key up for: " + vk.scancode);
+                                            KeyEvent event = newKeyEvent(di,
+                                                    di.mKeyDownTime, curTime, false,
+                                                    vk.lastKeycode,
+                                                    0, vk.scancode,
+                                                    KeyEvent.FLAG_VIRTUAL_HARD_KEY);
+                                            mHapticFeedbackCallback.virtualKeyFeedback(event);
+                                            addLocked(di, curTimeNano, ev.flags,
+                                                    RawInputEvent.CLASS_KEYBOARD,
+                                                    event);
+                                        } else if (isInsideDisplay(di)) {
+                                            // Whoops the pointer has moved into
+                                            // the display area!  Cancel the
+                                            // virtual key and start a pointer
+                                            // motion.
+                                            mPressedVirtualKey = null;
+                                            if (DEBUG_VIRTUAL_KEYS) Log.v(TAG,
+                                                    "Cancel key up for: " + vk.scancode);
+                                            KeyEvent event = newKeyEvent(di,
+                                                    di.mKeyDownTime, curTime, false,
+                                                    vk.lastKeycode,
+                                                    0, vk.scancode,
+                                                    KeyEvent.FLAG_CANCELED |
+                                                    KeyEvent.FLAG_VIRTUAL_HARD_KEY);
+                                            mHapticFeedbackCallback.virtualKeyFeedback(event);
+                                            addLocked(di, curTimeNano, ev.flags,
+                                                    RawInputEvent.CLASS_KEYBOARD,
+                                                    event);
+                                            doMotion = true;
+                                            for (int i=InputDevice.MAX_POINTERS-1; i>=0; i--) {
+                                                ms.mLastDown[i] = false;
+                                            }
+                                        }
                                     }
-                                    addLocked(di, curTime, ev.flags,
-                                            RawInputEvent.CLASS_TOUCHSCREEN, me);
+                                    if (doMotion && ms.mDown[0] && !ms.mLastDown[0]) {
+                                        vk = findSoftButton(di);
+                                        if (vk != null) {
+                                            doMotion = false;
+                                            mPressedVirtualKey = vk;
+                                            vk.lastKeycode = scancodeToKeycode(
+                                                    di.id, vk.scancode);
+                                            ms.mLastDown[0] = ms.mDown[0];
+                                            di.mKeyDownTime = curTime;
+                                            if (DEBUG_VIRTUAL_KEYS) Log.v(TAG,
+                                                    "Generate key down for: " + vk.scancode
+                                                    + " (keycode=" + vk.lastKeycode + ")");
+                                            KeyEvent event = newKeyEvent(di,
+                                                    di.mKeyDownTime, curTime, true,
+                                                    vk.lastKeycode, 0,
+                                                    vk.scancode,
+                                                    KeyEvent.FLAG_VIRTUAL_HARD_KEY);
+                                            mHapticFeedbackCallback.virtualKeyFeedback(event);
+                                            addLocked(di, curTimeNano, ev.flags,
+                                                    RawInputEvent.CLASS_KEYBOARD,
+                                                    event);
+                                        }
+                                    }
+                                    
+                                    if (doMotion) {
+                                        // XXX Need to be able to generate
+                                        // multiple events here, for example
+                                        // if two fingers change up/down state
+                                        // at the same time.
+                                        me = ms.generateAbsMotion(di, curTime,
+                                                curTimeNano, mDisplay,
+                                                mOrientation, mGlobalMetaState);
+                                        if (false) Log.v(TAG, "Absolute: x="
+                                                + di.mAbs.mCurData[MotionEvent.SAMPLE_X]
+                                                + " y="
+                                                + di.mAbs.mCurData[MotionEvent.SAMPLE_Y]
+                                                + " ev=" + me);
+                                        if (me != null) {
+                                            if (WindowManagerPolicy.WATCH_POINTER) {
+                                                Log.i(TAG, "Enqueueing: " + me);
+                                            }
+                                            addLocked(di, curTimeNano, ev.flags,
+                                                    RawInputEvent.CLASS_TOUCHSCREEN, me);
+                                        }
+                                    }
                                 }
-                                me = di.mRel.generateMotion(di, curTime, false,
-                                        mDisplay, mOrientation, mGlobalMetaState);
-                                if (false) Log.v(TAG, "Relative: x=" + di.mRel.x
-                                        + " y=" + di.mRel.y + " ev=" + me);
-                                if (me != null) {
-                                    addLocked(di, curTime, ev.flags,
-                                            RawInputEvent.CLASS_TRACKBALL, me);
+                                
+                                ms = di.mRel;
+                                if (ms.changed) {
+                                    ms.changed = false;
+                                    
+                                    me = ms.generateRelMotion(di, curTime,
+                                            curTimeNano,
+                                            mOrientation, mGlobalMetaState);
+                                    if (false) Log.v(TAG, "Relative: x="
+                                            + di.mRel.mCurData[MotionEvent.SAMPLE_X]
+                                            + " y="
+                                            + di.mRel.mCurData[MotionEvent.SAMPLE_Y]
+                                            + " ev=" + me);
+                                    if (me != null) {
+                                        addLocked(di, curTimeNano, ev.flags,
+                                                RawInputEvent.CLASS_TRACKBALL, me);
+                                    }
                                 }
                             }
                         }
                     }
                 }
-            }
-            catch (RuntimeException exc) {
+                
+            } catch (RuntimeException exc) {
                 Log.e(TAG, "InputReaderThread uncaught exception", exc);
             }
         }
     };
 
+    private boolean isInsideDisplay(InputDevice dev) {
+        final InputDevice.AbsoluteInfo absx = dev.absX;
+        final InputDevice.AbsoluteInfo absy = dev.absY;
+        final InputDevice.MotionState absm = dev.mAbs;
+        if (absx == null || absy == null || absm == null) {
+            return true;
+        }
+        
+        if (absm.mCurData[MotionEvent.SAMPLE_X] >= absx.minValue
+                && absm.mCurData[MotionEvent.SAMPLE_X] <= absx.maxValue
+                && absm.mCurData[MotionEvent.SAMPLE_Y] >= absy.minValue
+                && absm.mCurData[MotionEvent.SAMPLE_Y] <= absy.maxValue) {
+            if (DEBUG_VIRTUAL_KEYS) Log.v(TAG, "Input ("
+                    + absm.mCurData[MotionEvent.SAMPLE_X]
+                    + "," + absm.mCurData[MotionEvent.SAMPLE_Y]
+                    + ") inside of display");
+            return true;
+        }
+        
+        return false;
+    }
+    
+    private VirtualKey findSoftButton(InputDevice dev) {
+        final int N = mVirtualKeys.size();
+        if (N <= 0) {
+            return null;
+        }
+        
+        if (isInsideDisplay(dev)) {
+            return null;
+        }
+        
+        final InputDevice.MotionState absm = dev.mAbs;
+        for (int i=0; i<N; i++) {
+            VirtualKey sb = mVirtualKeys.get(i);
+            sb.computeHitRect(dev, mDisplayWidth, mDisplayHeight);
+            if (DEBUG_VIRTUAL_KEYS) Log.v(TAG, "Hit test ("
+                    + absm.mCurData[MotionEvent.SAMPLE_X] + ","
+                    + absm.mCurData[MotionEvent.SAMPLE_Y] + ") in code "
+                    + sb.scancode + " - (" + sb.hitLeft
+                    + "," + sb.hitTop + ")-(" + sb.hitRight + ","
+                    + sb.hitBottom + ")");
+            if (sb.checkHit(absm.mCurData[MotionEvent.SAMPLE_X],
+                    absm.mCurData[MotionEvent.SAMPLE_Y])) {
+                if (DEBUG_VIRTUAL_KEYS) Log.v(TAG, "Hit!");
+                return sb;
+            }
+        }
+        
+        return null;
+    }
+    
     /**
      * Returns a new meta state for the given keys and old state.
      */
@@ -506,8 +851,8 @@
             if (ev.event == ev.inputDevice.mRel.currentMove) {
                 if (false) Log.i(TAG, "Detach rel " + ev.event);
                 ev.inputDevice.mRel.currentMove = null;
-                ev.inputDevice.mRel.x = 0;
-                ev.inputDevice.mRel.y = 0;
+                ev.inputDevice.mRel.mCurData[MotionEvent.SAMPLE_X] = 0;
+                ev.inputDevice.mRel.mCurData[MotionEvent.SAMPLE_Y] = 0;
             }
             recycleLocked(ev);
         }
@@ -530,7 +875,7 @@
         }
     }
     
-    private QueuedEvent obtainLocked(InputDevice device, long when,
+    private QueuedEvent obtainLocked(InputDevice device, long whenNano,
             int flags, int classType, Object event) {
         QueuedEvent ev;
         if (mCacheCount == 0) {
@@ -542,7 +887,7 @@
             mCacheCount--;
         }
         ev.inputDevice = device;
-        ev.when = when;
+        ev.whenNano = whenNano;
         ev.flags = flags;
         ev.classType = classType;
         ev.event = event;
@@ -561,13 +906,13 @@
         }
     }
 
-    private void addLocked(InputDevice device, long when, int flags,
+    private void addLocked(InputDevice device, long whenNano, int flags,
             int classType, Object event) {
         boolean poke = mFirst.next == mLast;
 
-        QueuedEvent ev = obtainLocked(device, when, flags, classType, event);
+        QueuedEvent ev = obtainLocked(device, whenNano, flags, classType, event);
         QueuedEvent p = mLast.prev;
-        while (p != mFirst && ev.when < p.when) {
+        while (p != mFirst && ev.whenNano < p.whenNano) {
             p = p.prev;
         }
 
@@ -578,8 +923,15 @@
         ev.inQueue = true;
 
         if (poke) {
+            long time;
+            if (MEASURE_LATENCY) {
+                time = System.nanoTime();
+            }
             mFirst.notify();
             mWakeLock.acquire();
+            if (MEASURE_LATENCY) {
+                lt.sample("1 addLocked-queued event ", System.nanoTime() - time);
+            }
         }
     }
 
diff --git a/services/java/com/android/server/MasterClearReceiver.java b/services/java/com/android/server/MasterClearReceiver.java
index 5a42e76..3c366da 100644
--- a/services/java/com/android/server/MasterClearReceiver.java
+++ b/services/java/com/android/server/MasterClearReceiver.java
@@ -30,8 +30,8 @@
 
     @Override
     public void onReceive(Context context, Intent intent) {
-        if (intent.getAction().equals("android.intent.action.GTALK_DATA_MESSAGE_RECEIVED")) {
-            if (!intent.getBooleanExtra("from_trusted_server", false)) {
+        if (intent.getAction().equals(Intent.ACTION_REMOTE_INTENT)) {
+            if (!intent.getBooleanExtra("android.intent.extra.from_trusted_server", false)) {
                 Log.w(TAG, "Ignoring master clear request -- not from trusted server.");
                 return;
             }
diff --git a/services/java/com/android/server/PackageManagerService.java b/services/java/com/android/server/PackageManagerService.java
index 4afa03e..d6cd4ef 100644
--- a/services/java/com/android/server/PackageManagerService.java
+++ b/services/java/com/android/server/PackageManagerService.java
@@ -1678,6 +1678,9 @@
         }
     }
 
+    /**
+     * @deprecated
+     */
     public void querySyncProviders(List outNames, List outInfo) {
         synchronized (mPackages) {
             Iterator<Map.Entry<String, PackageParser.Provider>> i
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index aa1a5cf..48d97ec 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -32,12 +32,7 @@
 import android.database.ContentObserver;
 import android.database.Cursor;
 import android.media.AudioService;
-import android.os.IBinder;
-import android.os.Looper;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.os.SystemClock;
-import android.os.SystemProperties;
+import android.os.*;
 import android.provider.Contacts.People;
 import android.provider.Settings;
 import android.server.BluetoothA2dpService;
@@ -45,6 +40,7 @@
 import android.server.search.SearchManagerService;
 import android.util.EventLog;
 import android.util.Log;
+import android.accounts.AccountManagerService;
 
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
@@ -52,7 +48,6 @@
 class ServerThread extends Thread {
     private static final String TAG = "SystemServer";
     private final static boolean INCLUDE_DEMO = false;
-    private final static boolean INCLUDE_BACKUP = false;
 
     private static final int LOG_BOOT_PROGRESS_SYSTEM_RUN = 3010;
 
@@ -121,6 +116,14 @@
 
             mContentResolver = context.getContentResolver();
 
+            try {
+                Log.i(TAG, "Starting Account Manager.");
+                ServiceManager.addService(Context.ACCOUNT_SERVICE,
+                        new AccountManagerService(context));
+            } catch (Throwable e) {
+                Log.e(TAG, "Failure starting Account Manager", e);
+            }
+
             Log.i(TAG, "Starting Content Manager.");
             ContentService.main(context,
                     factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
@@ -173,7 +176,7 @@
                 bluetooth = new BluetoothDeviceService(context);
                 bluetooth.init();
                 ServiceManager.addService(Context.BLUETOOTH_SERVICE, bluetooth);
-                bluetoothA2dp = new BluetoothA2dpService(context);
+                bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);
                 ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,
                                           bluetoothA2dp);
 
@@ -319,10 +322,8 @@
             }
 
             try {
-                if (INCLUDE_BACKUP) {
-                    Log.i(TAG, "Starting Backup Service");
-                    ServiceManager.addService(Context.BACKUP_SERVICE, new BackupManagerService(context));
-                }
+                Log.i(TAG, "Starting Backup Service");
+                ServiceManager.addService(Context.BACKUP_SERVICE, new BackupManagerService(context));
             } catch (Throwable e) {
                 Log.e(TAG, "Failure starting Backup Service", e);
             }
@@ -422,19 +423,19 @@
     public static final int FACTORY_TEST_OFF = 0;
     public static final int FACTORY_TEST_LOW_LEVEL = 1;
     public static final int FACTORY_TEST_HIGH_LEVEL = 2;
-    
-    /** 
-     * This method is called from Zygote to initialize the system. This will cause the native 
+
+    /**
+     * This method is called from Zygote to initialize the system. This will cause the native
      * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
      * up into init2() to start the Android services.
-     */ 
+     */
     native public static void init1(String[] args);
 
     public static void main(String[] args) {
         // The system server has to run all of the time, so it needs to be
         // as efficient as possible with its memory usage.
         VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
-        
+
         System.loadLibrary("android_servers");
         init1(args);
     }
diff --git a/services/java/com/android/server/WifiService.java b/services/java/com/android/server/WifiService.java
index 394ed3a..f25c221 100644
--- a/services/java/com/android/server/WifiService.java
+++ b/services/java/com/android/server/WifiService.java
@@ -41,6 +41,7 @@
 import android.net.wifi.SupplicantState;
 import android.net.NetworkStateTracker;
 import android.net.DhcpInfo;
+import android.net.NetworkUtils;
 import android.os.Binder;
 import android.os.Handler;
 import android.os.HandlerThread;
@@ -142,28 +143,6 @@
     private final  WifiHandler mWifiHandler;
 
     /*
-     * Map used to keep track of hidden networks presence, which
-     * is needed to switch between active and passive scan modes.
-     * If there is at least one hidden network that is currently
-     * present (enabled), we want to do active scans instead of
-     * passive.
-     */
-    private final Map<Integer, Boolean> mIsHiddenNetworkPresent;
-    /*
-     * The number of currently present hidden networks. When this
-     * counter goes from 0 to 1 or from 1 to 0, we change the
-     * scan mode to active or passive respectively. Initially, we
-     * set the counter to 0 and we increment it every time we add
-     * a new present (enabled) hidden network.
-     */
-    private int mNumHiddenNetworkPresent;
-    /*
-     * Whether we change the scan mode is due to a hidden network
-     * (in this class, this is always the case)
-     */
-    private final static boolean SET_DUE_TO_A_HIDDEN_NETWORK = true;
-
-    /*
      * Cache of scan results objects (size is somewhat arbitrary)
      */
     private static final int SCAN_RESULT_CACHE_SIZE = 80;
@@ -195,12 +174,6 @@
         mWifiStateTracker.enableRssiPolling(true);
         mBatteryStats = BatteryStatsService.getService();
         
-        /*
-         * Initialize the hidden-networks state
-         */
-        mIsHiddenNetworkPresent = new HashMap<Integer, Boolean>();
-        mNumHiddenNetworkPresent = 0;
-
         mScanResultCache = new LinkedHashMap<String, ScanResult>(
             SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
                 /*
@@ -254,155 +227,6 @@
         setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
     }
 
-    /**
-     * Initializes the hidden networks state. Must be called when we
-     * enable Wi-Fi.
-     */
-    private synchronized void initializeHiddenNetworksState() {
-        // First, reset the state
-        resetHiddenNetworksState();
-
-        // ... then add networks that are marked as hidden
-        List<WifiConfiguration> networks = getConfiguredNetworks();
-        if (!networks.isEmpty()) {
-            for (WifiConfiguration config : networks) {
-                if (config != null && config.hiddenSSID) {
-                    addOrUpdateHiddenNetwork(
-                        config.networkId,
-                        config.status != WifiConfiguration.Status.DISABLED);
-                }
-            }
-
-        }
-    }
-
-    /**
-     * Resets the hidden networks state.
-     */
-    private synchronized void resetHiddenNetworksState() {
-        mNumHiddenNetworkPresent = 0;
-        mIsHiddenNetworkPresent.clear();
-    }
-
-    /**
-     * Marks all but netId network as not present.
-     */
-    private synchronized void markAllHiddenNetworksButOneAsNotPresent(int netId) {
-        for (Map.Entry<Integer, Boolean> entry : mIsHiddenNetworkPresent.entrySet()) {
-            if (entry != null) {
-                Integer networkId = entry.getKey();
-                if (networkId != netId) {
-                    updateNetworkIfHidden(
-                        networkId, false);
-                }
-            }
-        }
-    }
-
-    /**
-     * Updates the netId network presence status if netId is an existing
-     * hidden network.
-     */
-    private synchronized void updateNetworkIfHidden(int netId, boolean present) {
-        if (isHiddenNetwork(netId)) {
-            addOrUpdateHiddenNetwork(netId, present);
-        }
-    }
-
-    /**
-     * Updates the netId network presence status if netId is an existing
-     * hidden network. If the network does not exist, adds the network.
-     */
-    private synchronized void addOrUpdateHiddenNetwork(int netId, boolean present) {
-        if (0 <= netId) {
-
-            // If we are adding a new entry or modifying an existing one
-            Boolean isPresent = mIsHiddenNetworkPresent.get(netId);
-            if (isPresent == null || isPresent != present) {
-                if (present) {
-                    incrementHiddentNetworkPresentCounter();
-                } else {
-                    // If we add a new hidden network, no need to change
-                    // the counter (it must be 0)
-                    if (isPresent != null) {
-                        decrementHiddentNetworkPresentCounter();
-                    }
-                }
-                mIsHiddenNetworkPresent.put(netId, present);
-            }
-        } else {
-            Log.e(TAG, "addOrUpdateHiddenNetwork(): Invalid (negative) network id!");
-        }
-    }
-
-    /**
-     * Removes the netId network if it is hidden (being kept track of).
-     */
-    private synchronized void removeNetworkIfHidden(int netId) {
-        if (isHiddenNetwork(netId)) {
-            removeHiddenNetwork(netId);
-        }
-    }
-
-    /**
-     * Removes the netId network. For the call to be successful, the network
-     * must be hidden.
-     */
-    private synchronized void removeHiddenNetwork(int netId) {
-        if (0 <= netId) {
-            Boolean isPresent =
-                mIsHiddenNetworkPresent.remove(netId);
-            if (isPresent != null) {
-                // If we remove an existing hidden network that is not
-                // present, no need to change the counter
-                if (isPresent) {
-                    decrementHiddentNetworkPresentCounter();
-                }
-            } else {
-                if (DBG) {
-                    Log.d(TAG, "removeHiddenNetwork(): Removing a non-existent network!");
-                }
-            }
-        } else {
-            Log.e(TAG, "removeHiddenNetwork(): Invalid (negative) network id!");
-        }
-    }
-
-    /**
-     * Returns true if netId is an existing hidden network.
-     */
-    private synchronized boolean isHiddenNetwork(int netId) {
-        return mIsHiddenNetworkPresent.containsKey(netId);
-    }
-
-    /**
-     * Increments the present (enabled) hidden networks counter. If the
-     * counter value goes from 0 to 1, changes the scan mode to active.
-     */
-    private void incrementHiddentNetworkPresentCounter() {
-        ++mNumHiddenNetworkPresent;
-        if (1 == mNumHiddenNetworkPresent) {
-            // Switch the scan mode to "active"
-            mWifiStateTracker.setScanMode(true, SET_DUE_TO_A_HIDDEN_NETWORK);
-        }
-    }
-
-    /**
-     * Decrements the present (enabled) hidden networks counter. If the
-     * counter goes from 1 to 0, changes the scan mode back to passive.
-     */
-    private void decrementHiddentNetworkPresentCounter() {
-        if (0 < mNumHiddenNetworkPresent) {
-            --mNumHiddenNetworkPresent;
-            if (0 == mNumHiddenNetworkPresent) {
-                // Switch the scan mode to "passive"
-                mWifiStateTracker.setScanMode(false, SET_DUE_TO_A_HIDDEN_NETWORK);
-            }
-        } else {
-            Log.e(TAG, "Hidden-network counter invariant violation!");
-        }
-    }
-
     private boolean getPersistedWifiEnabled() {
         final ContentResolver cr = mContext.getContentResolver();
         try {
@@ -522,7 +346,7 @@
             }
 
             // We must reset the interface before we unload the driver
-            mWifiStateTracker.resetInterface();
+            mWifiStateTracker.resetInterface(false);
 
             if (!WifiNative.unloadDriver()) {
                 Log.e(TAG, "Failed to unload Wi-Fi driver.");
@@ -544,12 +368,10 @@
         setWifiEnabledState(eventualWifiState, uid);
 
         /*
-         * Initialize the hidden networks state and the number of allowed
-         * radio channels if Wi-Fi is being turned on.
+         * Initialize the number of allowed radio channels if Wi-Fi is being turned on.
          */
         if (enable) {
             mWifiStateTracker.setNumAllowedChannels();
-            initializeHiddenNetworksState();
         }
 
         return true;
@@ -884,15 +706,6 @@
         }
         mNeedReconfig = mNeedReconfig || doReconfig;
 
-        /*
-         * If we have hidden networks, we may have to change the scan mode
-         */
-        if (config.hiddenSSID) {
-            // Mark the network as present unless it is disabled
-            addOrUpdateHiddenNetwork(
-                netId, config.status != WifiConfiguration.Status.DISABLED);
-        }
-
         setVariables: {
             /*
              * Note that if a networkId for a non-existent network
@@ -1231,11 +1044,6 @@
     public boolean removeNetwork(int netId) {
         enforceChangePermission();
 
-        /*
-         * If we have hidden networks, we may have to change the scan mode
-         */
-        removeNetworkIfHidden(netId);
-
         return mWifiStateTracker.removeNetwork(netId);
     }
 
@@ -1249,18 +1057,14 @@
     public boolean enableNetwork(int netId, boolean disableOthers) {
         enforceChangePermission();
 
-        /*
-         * If we have hidden networks, we may have to change the scan mode
-         */
-         synchronized(this) {
-             if (disableOthers) {
-                 markAllHiddenNetworksButOneAsNotPresent(netId);
-             }
-             updateNetworkIfHidden(netId, true);
-         }
-
         synchronized (mWifiStateTracker) {
-            return WifiNative.enableNetworkCommand(netId, disableOthers);
+            String ifname = mWifiStateTracker.getInterfaceName();
+            NetworkUtils.enableInterface(ifname);
+            boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
+            if (!result) {
+                NetworkUtils.disableInterface(ifname);
+            }
+            return result;
         }
     }
 
@@ -1273,11 +1077,6 @@
     public boolean disableNetwork(int netId) {
         enforceChangePermission();
 
-        /*
-         * If we have hidden networks, we may have to change the scan mode
-         */
-        updateNetworkIfHidden(netId, false);
-
         synchronized (mWifiStateTracker) {
             return WifiNative.disableNetworkCommand(netId);
         }
@@ -1375,39 +1174,42 @@
                         level = 0;
                     }
 
+                    /*
+                     * The formatting of the results returned by
+                     * wpa_supplicant is intended to make the fields
+                     * line up nicely when printed,
+                     * not to make them easy to parse. So we have to
+                     * apply some heuristics to figure out which field
+                     * is the SSID and which field is the flags.
+                     */
+                    String ssid;
+                    String flags;
+                    if (result.length == 4) {
+                        if (result[3].charAt(0) == '[') {
+                            flags = result[3];
+                            ssid = "";
+                        } else {
+                            flags = "";
+                            ssid = result[3];
+                        }
+                    } else if (result.length == 5) {
+                        flags = result[3];
+                        ssid = result[4];
+                    } else {
+                        // Here, we must have 3 fields: no flags and ssid
+                        // set
+                        flags = "";
+                        ssid = "";
+                    }
+
                     // bssid is the hash key
                     scanResult = mScanResultCache.get(bssid);
                     if (scanResult != null) {
                         scanResult.level = level;
+                        scanResult.SSID = ssid;
+                        scanResult.capabilities = flags;
+                        scanResult.frequency = frequency;
                     } else {
-                        /*
-                         * The formatting of the results returned by
-                         * wpa_supplicant is intended to make the fields
-                         * line up nicely when printed,
-                         * not to make them easy to parse. So we have to
-                         * apply some heuristics to figure out which field
-                         * is the SSID and which field is the flags.
-                         */
-                        String ssid;
-                        String flags;
-                        if (result.length == 4) {
-                            if (result[3].charAt(0) == '[') {
-                                flags = result[3];
-                                ssid = "";
-                            } else {
-                                flags = "";
-                                ssid = result[3];
-                            }
-                        } else if (result.length == 5) {
-                            flags = result[3];
-                            ssid = result[4];
-                        } else {
-                            // Here, we must have 3 fields: no flags and ssid
-                            // set
-                            flags = "";
-                            ssid = "";
-                        }
-
                         // Do not add scan results that have no SSID set
                         if (0 < ssid.trim().length()) {
                             scanResult =
@@ -1479,14 +1281,17 @@
      * Set the number of radio frequency channels that are allowed to be used
      * in the current regulatory domain. This method should be used only
      * if the correct number of channels cannot be determined automatically
-     * for some reason. If the operation is successful, the new value is
+     * for some reason. If the operation is successful, the new value may be
      * persisted as a Secure setting.
      * @param numChannels the number of allowed channels. Must be greater than 0
      * and less than or equal to 16.
+     * @param persist {@code true} if the setting should be remembered.
      * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
      * {@code numChannels} is outside the valid range.
      */
-    public boolean setNumAllowedChannels(int numChannels) {
+    public boolean setNumAllowedChannels(int numChannels, boolean persist) {
+        Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
+                " with persist set to "+persist);
         enforceChangePermission();
         /*
          * Validate the argument. We'd like to let the Wi-Fi driver do this,
@@ -1505,9 +1310,11 @@
             return false;
         }
 
-        Settings.Secure.putInt(mContext.getContentResolver(),
-                               Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
-                               numChannels);
+        if (persist) {
+            Settings.Secure.putInt(mContext.getContentResolver(),
+                                   Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
+                                   numChannels);
+        }
         mWifiStateTracker.setNumAllowedChannels(numChannels);
         return true;
     }
diff --git a/services/java/com/android/server/WindowManagerService.java b/services/java/com/android/server/WindowManagerService.java
index 4998945..78ca831 100644
--- a/services/java/com/android/server/WindowManagerService.java
+++ b/services/java/com/android/server/WindowManagerService.java
@@ -66,6 +66,7 @@
 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;
@@ -124,7 +125,8 @@
 import java.util.List;
 
 /** {@hide} */
-public class WindowManagerService extends IWindowManager.Stub implements Watchdog.Monitor {
+public class WindowManagerService extends IWindowManager.Stub
+        implements Watchdog.Monitor, KeyInputQueue.HapticFeedbackCallback {
     static final String TAG = "WindowManager";
     static final boolean DEBUG = false;
     static final boolean DEBUG_FOCUS = false;
@@ -138,6 +140,8 @@
     static final boolean DEBUG_STARTING_WINDOW = false;
     static final boolean DEBUG_REORDER = false;
     static final boolean SHOW_TRANSACTIONS = false;
+    static final boolean MEASURE_LATENCY = false;
+    static private LatencyTimer lt;
 
     static final boolean PROFILE_ORIENTATION = false;
     static final boolean BLUR = true;
@@ -512,6 +516,10 @@
 
     private WindowManagerService(Context context, PowerManagerService pm,
             boolean haveInputMethods) {
+        if (MEASURE_LATENCY) {
+            lt = new LatencyTimer(100, 1000);
+        }
+        
         mContext = context;
         mHaveInputMethods = haveInputMethods;
         mLimitedAlphaCompositing = context.getResources().getBoolean(
@@ -3822,7 +3830,7 @@
     private final void wakeupIfNeeded(WindowState targetWin, int eventType) {
         long curTime = SystemClock.uptimeMillis();
 
-        if (eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT) {
+        if (eventType == TOUCH_EVENT || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT) {
             if (mLastTouchEventType == eventType &&
                     (curTime - mLastUserActivityCallTime) < MIN_TIME_BETWEEN_USERACTIVITIES) {
                 return;
@@ -3882,8 +3890,16 @@
         if (DEBUG_INPUT || WindowManagerPolicy.WATCH_POINTER) Log.v(TAG,
                 "dispatchPointer " + ev);
 
+        if (MEASURE_LATENCY) {
+            lt.sample("3 Wait for last dispatch ", System.nanoTime() - qev.whenNano);
+        }
+
         Object targetObj = mKeyWaiter.waitForNextEventTarget(null, qev,
                 ev, true, false, pid, uid);
+        
+        if (MEASURE_LATENCY) {
+            lt.sample("3 Last dispatch finished ", System.nanoTime() - qev.whenNano);
+        }
 
         int action = ev.getAction();
 
@@ -3921,7 +3937,8 @@
         WindowState target = (WindowState)targetObj;
 
         final long eventTime = ev.getEventTime();
-
+        final long eventTimeNano = ev.getEventTimeNano();
+        
         //Log.i(TAG, "Sending " + ev + " to " + target);
 
         if (uid != 0 && uid != target.mSession.mUid) {
@@ -3938,6 +3955,10 @@
                 return INJECT_NO_PERMISSION;
             }
         }
+        
+        if (MEASURE_LATENCY) {
+            lt.sample("4 in dispatchPointer     ", System.nanoTime() - eventTimeNano);
+        }
 
         if ((target.mAttrs.flags &
                         WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES) != 0) {
@@ -4021,6 +4042,10 @@
             }
         }
 
+        if (MEASURE_LATENCY) {
+            lt.sample("5 in dispatchPointer     ", System.nanoTime() - eventTimeNano);
+        }
+
         synchronized(mWindowMap) {
             if (qev != null && action == MotionEvent.ACTION_MOVE) {
                 mKeyWaiter.bindTargetWindowLocked(target,
@@ -4058,7 +4083,16 @@
             if (DEBUG_INPUT || DEBUG_FOCUS || WindowManagerPolicy.WATCH_POINTER) {
                 Log.v(TAG, "Delivering pointer " + qev + " to " + target);
             }
+            
+            if (MEASURE_LATENCY) {
+                lt.sample("6 before svr->client ipc ", System.nanoTime() - eventTimeNano);
+            }
+
             target.mClient.dispatchPointer(ev, eventTime);
+
+            if (MEASURE_LATENCY) {
+                lt.sample("7 after  svr->client ipc ", System.nanoTime() - eventTimeNano);
+            }
             return INJECT_SUCCEEDED;
         } catch (android.os.RemoteException e) {
             Log.i(TAG, "WINDOW DIED during motion dispatch: " + target);
@@ -4653,7 +4687,8 @@
                                     callingPid, callingUid)
                                     == PackageManager.PERMISSION_GRANTED) {
                         mPolicy.interceptKeyTi(null, keycode,
-                                nextKey.getMetaState(), down, repeatCount);
+                                nextKey.getMetaState(), down, repeatCount,
+                                nextKey.getFlags());
                     }
                     Log.w(TAG, "Event timeout during app switch: dropping "
                             + nextKey);
@@ -4676,7 +4711,8 @@
                                 callingPid, callingUid)
                                 == PackageManager.PERMISSION_GRANTED) {
                     if (mPolicy.interceptKeyTi(focus,
-                            keycode, nextKey.getMetaState(), down, repeatCount)) {
+                            keycode, nextKey.getMetaState(), down, repeatCount, 
+                            nextKey.getFlags())) {
                         return CONSUMED_EVENT_TOKEN;
                     }
                 }
@@ -5096,7 +5132,7 @@
         PowerManager.WakeLock mHoldingScreen;
 
         KeyQ() {
-            super(mContext);
+            super(mContext, WindowManagerService.this);
             PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
             mHoldingScreen = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
                     "KEEP_SCREEN_ON_FLAG");
@@ -5227,7 +5263,7 @@
                 }
             }
         }
-    };
+    }
 
     public boolean detectSafeMode() {
         mSafeMode = mPolicy.detectSafeMode();
@@ -5292,9 +5328,13 @@
                 if (DEBUG_INPUT && ev != null) Log.v(
                         TAG, "Event: type=" + ev.classType + " data=" + ev.event);
 
+                if (MEASURE_LATENCY) {
+                    lt.sample("2 got event              ", System.nanoTime() - ev.whenNano);
+                }
+
                 try {
                     if (ev != null) {
-                        curTime = ev.when;
+                        curTime = SystemClock.uptimeMillis();
                         int eventType;
                         if (ev.classType == RawInputEvent.CLASS_TOUCHSCREEN) {
                             eventType = eventType((MotionEvent)ev.event);
@@ -5305,17 +5345,29 @@
                             eventType = LocalPowerManager.OTHER_EVENT;
                         }
                         try {
-                            long now = SystemClock.uptimeMillis();
-
-                            if ((now - mLastBatteryStatsCallTime)
+                            if ((curTime - mLastBatteryStatsCallTime)
                                     >= MIN_TIME_BETWEEN_USERACTIVITIES) {
-                                mLastBatteryStatsCallTime = now;
+                                mLastBatteryStatsCallTime = curTime;
                                 mBatteryStats.noteInputEvent();
                             }
                         } catch (RemoteException e) {
                             // Ignore
                         }
-                        mPowerManager.userActivity(curTime, false, eventType, false);
+
+                        if (eventType != TOUCH_EVENT
+                                && eventType != LONG_TOUCH_EVENT
+                                && eventType != CHEEK_EVENT) {
+                            mPowerManager.userActivity(curTime, false,
+                                    eventType, false);
+                        } else if (mLastTouchEventType != eventType
+                                || (curTime - mLastUserActivityCallTime)
+                                >= MIN_TIME_BETWEEN_USERACTIVITIES) {
+                            mLastUserActivityCallTime = curTime;
+                            mLastTouchEventType = eventType;
+                            mPowerManager.userActivity(curTime, false,
+                                    eventType, false);
+                        }
+
                         switch (ev.classType) {
                             case RawInputEvent.CLASS_KEYBOARD:
                                 KeyEvent ke = (KeyEvent)ev.event;
@@ -9153,6 +9205,10 @@
         synchronized (mKeyWaiter) { }
     }
 
+    public void virtualKeyFeedback(KeyEvent event) {
+        mPolicy.keyFeedbackFromInput(event);
+    }
+    
     /**
      * DimAnimator class that controls the dim animation. This holds the surface and
      * all state used for dim animation. 
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index 81a715d..8a4b8f9 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -318,6 +318,12 @@
     // Memory pages are 4K.
     static final int PAGE_SIZE = 4*1024;
     
+    // System property defining error report receiver for system apps
+    static final String SYSTEM_APPS_ERROR_RECEIVER_PROPERTY = "ro.error.receiver.system.apps";
+
+    // System property defining default error report receiver
+    static final String DEFAULT_ERROR_RECEIVER_PROPERTY = "ro.error.receiver.default";
+
     // Corresponding memory levels for above adjustments.
     final int EMPTY_APP_MEM;
     final int HIDDEN_APP_MEM;
@@ -8096,27 +8102,62 @@
 
     private ComponentName getErrorReportReceiver(ProcessRecord app) {
         IPackageManager pm = ActivityThread.getPackageManager();
+
         try {
-            // was an installer package name specified when this app was
-            // installed?
-            String installerPackageName = pm.getInstallerPackageName(app.info.packageName);
-            if (installerPackageName == null) {
-                return null;
+            // look for receiver in the installer package
+            String candidate = pm.getInstallerPackageName(app.info.packageName);
+            ComponentName result = getErrorReportReceiver(pm, app.info.packageName, candidate);
+            if (result != null) {
+                return result;
             }
 
-            // is there an Activity in this package that handles ACTION_APP_ERROR?
-            Intent intent = new Intent(Intent.ACTION_APP_ERROR);
-            intent.setPackage(installerPackageName);
-            ResolveInfo info = pm.resolveIntent(intent, null, 0);
-            if (info == null || info.activityInfo == null) {
-                return null;
+            // if the error app is on the system image, look for system apps
+            // error receiver
+            if ((app.info.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
+                candidate = SystemProperties.get(SYSTEM_APPS_ERROR_RECEIVER_PROPERTY);
+                result = getErrorReportReceiver(pm, app.info.packageName, candidate);
+                if (result != null) {
+                    return result;
+                }
             }
 
-            return new ComponentName(installerPackageName, info.activityInfo.name);
+            // if there is a default receiver, try that
+            candidate = SystemProperties.get(DEFAULT_ERROR_RECEIVER_PROPERTY);
+            return getErrorReportReceiver(pm, app.info.packageName, candidate);
         } catch (RemoteException e) {
-            // will return null and no error report will be delivered
+            // should not happen
+            Log.e(TAG, "error talking to PackageManager", e);
+            return null;
         }
-        return null;
+    }
+
+    /**
+     * Return activity in receiverPackage that handles ACTION_APP_ERROR.
+     *
+     * @param pm PackageManager isntance
+     * @param errorPackage package which caused the error
+     * @param receiverPackage candidate package to receive the error
+     * @return activity component within receiverPackage which handles
+     * ACTION_APP_ERROR, or null if not found
+     */
+    private ComponentName getErrorReportReceiver(IPackageManager pm, String errorPackage,
+            String receiverPackage) throws RemoteException {
+        if (receiverPackage == null || receiverPackage.length() == 0) {
+            return null;
+        }
+
+        // break the loop if it's the error report receiver package that crashed
+        if (receiverPackage.equals(errorPackage)) {
+            return null;
+        }
+
+        Intent intent = new Intent(Intent.ACTION_APP_ERROR);
+        intent.setPackage(receiverPackage);
+        ResolveInfo info = pm.resolveIntent(intent, null, 0);
+        if (info == null || info.activityInfo == null) {
+            return null;
+        }
+        return new ComponentName(receiverPackage, info.activityInfo.name);
     }
 
     void makeAppNotRespondingLocked(ProcessRecord app,
@@ -8438,6 +8479,7 @@
                 report.crashInfo.throwFileName = trace.getFileName();
                 report.crashInfo.throwClassName = trace.getClassName();
                 report.crashInfo.throwMethodName = trace.getMethodName();
+                report.crashInfo.throwLineNumber = trace.getLineNumber();
             } else if (r.notResponding) {
                 report.type = ApplicationErrorReport.TYPE_ANR;
                 report.anrInfo = new ApplicationErrorReport.AnrInfo();
diff --git a/services/java/com/android/server/status/StatusBarPolicy.java b/services/java/com/android/server/status/StatusBarPolicy.java
index a4b47b5..c8db95b 100644
--- a/services/java/com/android/server/status/StatusBarPolicy.java
+++ b/services/java/com/android/server/status/StatusBarPolicy.java
@@ -76,15 +76,8 @@
     private static StatusBarPolicy sInstance;
 
     // message codes for the handler
-    private static final int EVENT_DATA_CONN_STATE_CHANGED = 2;
-    private static final int EVENT_DATA_ACTIVITY = 3;
     private static final int EVENT_BATTERY_CLOSE = 4;
 
-    // indices into mBatteryThresholds
-    private static final int BATTERY_THRESHOLD_CLOSE_WARNING = 0;
-    private static final int BATTERY_THRESHOLD_WARNING = 1;
-    private static final int BATTERY_THRESHOLD_EMPTY = 2;
-
     private final Context mContext;
     private final StatusBarService mService;
     private final Handler mHandler = new StatusBarHandler();
@@ -99,16 +92,13 @@
     private IBinder mBatteryIcon;
     private IconData mBatteryData;
     private boolean mBatteryFirst = true;
-    private int mBatteryPlugged;
+    private boolean mBatteryPlugged;
     private int mBatteryLevel;
-    private int mBatteryThreshold = 0; // index into mBatteryThresholds
-    private int[] mBatteryThresholds = new int[] { 20, 15, -1 };
     private AlertDialog mLowBatteryDialog;
     private TextView mBatteryLevelTextView;
     private View mBatteryView;
     private int mBatteryViewSequence;
     private boolean mBatteryShowLowOnEndCall = false;
-    private boolean mSentLowBatteryBroadcast = false;
     private static final boolean SHOW_LOW_BATTERY_WARNING = true;
 
     // phone
@@ -363,6 +353,9 @@
             else if (action.equals(Intent.ACTION_TIME_CHANGED)) {
                 updateClock();
             }
+            else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
+                updateBattery(intent);
+            }
             else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
                 updateClock();
             }
@@ -377,8 +370,11 @@
             else if (action.equals(Intent.ACTION_SYNC_STATE_CHANGED)) {
                 updateSyncState(intent);
             }
-            else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
-                updateBattery(intent);
+            else if (action.equals(Intent.ACTION_BATTERY_LOW)) {
+                onBatteryLow(intent);
+            }
+            else if (action.equals(Intent.ACTION_BATTERY_OKAY)) {
+                onBatteryOkay(intent);
             }
             else if (action.equals(BluetoothIntent.BLUETOOTH_STATE_CHANGED_ACTION) ||
                     action.equals(BluetoothIntent.HEADSET_STATE_CHANGED_ACTION) ||
@@ -521,6 +517,8 @@
         filter.addAction(Intent.ACTION_TIME_CHANGED);
         filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
+        filter.addAction(Intent.ACTION_BATTERY_LOW);
+        filter.addAction(Intent.ACTION_BATTERY_OKAY);
         filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
         filter.addAction(Intent.ACTION_ALARM_CHANGED);
         filter.addAction(Intent.ACTION_SYNC_STATE_CHANGED);
@@ -564,38 +562,22 @@
         //mService.setIconVisibility(mSyncFailingIcon, isFailing && !isActive);
     }
 
-    private void pickNextBatteryLevel(int level) {
-        final int N = mBatteryThresholds.length;
-        for (int i=0; i<N; i++) {
-            if (level >= mBatteryThresholds[i]) {
-                mBatteryThreshold = i;
-                break;
-            }
-        }
-        if (mBatteryThreshold >= N) {
-            mBatteryThreshold = N-1;
-        }
-    }
-
     private final void updateBattery(Intent intent) {
         mBatteryData.iconId = intent.getIntExtra("icon-small", 0);
         mBatteryData.iconLevel = intent.getIntExtra("level", 0);
         mService.updateIcon(mBatteryIcon, mBatteryData, null);
 
-        int plugged = intent.getIntExtra("plugged", 0);
+        boolean plugged = intent.getIntExtra("plugged", 0) != 0;
         int level = intent.getIntExtra("level", -1);
         if (false) {
             Log.d(TAG, "updateBattery level=" + level
                     + " plugged=" + plugged
                     + " mBatteryPlugged=" + mBatteryPlugged
                     + " mBatteryLevel=" + mBatteryLevel
-                    + " mBatteryThreshold=" + mBatteryThreshold
                     + " mBatteryFirst=" + mBatteryFirst);
         }
 
-        int oldPlugged = mBatteryPlugged;
-        int oldThreshold = mBatteryThreshold;
-        pickNextBatteryLevel(level);
+        boolean oldPlugged = mBatteryPlugged;
 
         mBatteryPlugged = plugged;
         mBatteryLevel = level;
@@ -617,45 +599,31 @@
         }
         */
         if (false) {
-            Log.d(TAG, "plugged=" + plugged + " oldPlugged=" + oldPlugged + " level=" + level
-                    + " mBatteryThreshold=" + mBatteryThreshold + " oldThreshold=" + oldThreshold);
+            Log.d(TAG, "plugged=" + plugged + " oldPlugged=" + oldPlugged + " level=" + level);
         }
-        if (plugged == 0
-                && ((oldPlugged != 0 && level < mBatteryThresholds[BATTERY_THRESHOLD_WARNING])
-                    || (mBatteryThreshold > oldThreshold
-                        && mBatteryThreshold > BATTERY_THRESHOLD_WARNING))) {
-            // Broadcast the low battery warning
-            mSentLowBatteryBroadcast = true;
-            Intent batIntent = new Intent(Intent.ACTION_BATTERY_LOW);
-            batIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
-            mContext.sendBroadcast(batIntent);
+    }
 
-            if (SHOW_LOW_BATTERY_WARNING) {
-                if (false) {
-                    Log.d(TAG, "mPhoneState=" + mPhoneState
-                            + " mLowBatteryDialog=" + mLowBatteryDialog
-                            + " mBatteryShowLowOnEndCall=" + mBatteryShowLowOnEndCall);
-                }
+    private void onBatteryLow(Intent intent) {
+        if (SHOW_LOW_BATTERY_WARNING) {
+            if (false) {
+                Log.d(TAG, "mPhoneState=" + mPhoneState
+                      + " mLowBatteryDialog=" + mLowBatteryDialog
+                      + " mBatteryShowLowOnEndCall=" + mBatteryShowLowOnEndCall);
+            }
 
-                if (mPhoneState == TelephonyManager.CALL_STATE_IDLE) {
-                    showLowBatteryWarning();
-                } else {
-                    mBatteryShowLowOnEndCall = true;
-                }
+            if (mPhoneState == TelephonyManager.CALL_STATE_IDLE) {
+                showLowBatteryWarning();
+            } else {
+                mBatteryShowLowOnEndCall = true;
             }
-        } else if (mBatteryThreshold < BATTERY_THRESHOLD_WARNING) {
-            if (mSentLowBatteryBroadcast == true) {
-                mSentLowBatteryBroadcast = false;
-                Intent batIntent = new Intent(Intent.ACTION_BATTERY_OKAY);
-                batIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
-                mContext.sendBroadcast(batIntent);
-            }
-            if (SHOW_LOW_BATTERY_WARNING) {
-                if (mLowBatteryDialog != null) {
-                    mLowBatteryDialog.dismiss();
-                    mBatteryShowLowOnEndCall = false;
-                }
-            }
+        }
+    }
+
+    private void onBatteryOkay(Intent intent) {
+        if (mLowBatteryDialog != null
+                && SHOW_LOW_BATTERY_WARNING) {
+            mLowBatteryDialog.dismiss();
+            mBatteryShowLowOnEndCall = false;
         }
     }
 
@@ -720,9 +688,11 @@
     private void showLowBatteryWarning() {
         closeLastBatteryView();
 
-        int level = mBatteryThresholds[mBatteryThreshold > 1 ? mBatteryThreshold - 1 : 0];
+        /* Show exact battery level.
+         * Add 1 because the text says "less than X%".
+         */
         CharSequence levelText = mContext.getString(
-                    com.android.internal.R.string.battery_low_percent_format, level);
+                    com.android.internal.R.string.battery_low_percent_format, mBatteryLevel + 1);
 
         if (mBatteryLevelTextView != null) {
             mBatteryLevelTextView.setText(levelText);
@@ -773,7 +743,7 @@
         }
         if (mPhoneState == TelephonyManager.CALL_STATE_IDLE) {
             if (mBatteryShowLowOnEndCall) {
-                if (mBatteryPlugged == 0) {
+                if (!mBatteryPlugged) {
                     showLowBatteryWarning();
                 }
                 mBatteryShowLowOnEndCall = false;
diff --git a/services/jni/com_android_server_AlarmManagerService.cpp b/services/jni/com_android_server_AlarmManagerService.cpp
index 1d66fb1..85d63c9 100644
--- a/services/jni/com_android_server_AlarmManagerService.cpp
+++ b/services/jni/com_android_server_AlarmManagerService.cpp
@@ -19,8 +19,8 @@
 
 #include "JNIHelp.h"
 #include "jni.h"
-#include "utils/Log.h"
-#include "utils/misc.h"
+#include <utils/Log.h>
+#include <utils/misc.h>
 
 #include <fcntl.h>
 #include <stdio.h>
diff --git a/services/jni/com_android_server_BatteryService.cpp b/services/jni/com_android_server_BatteryService.cpp
index 2524966..e4f001f 100644
--- a/services/jni/com_android_server_BatteryService.cpp
+++ b/services/jni/com_android_server_BatteryService.cpp
@@ -18,8 +18,8 @@
 
 #include "JNIHelp.h"
 #include "jni.h"
-#include "utils/Log.h"
-#include "utils/misc.h"
+#include <utils/Log.h>
+#include <utils/misc.h>
 
 #include <fcntl.h>
 #include <stdio.h>
diff --git a/services/jni/com_android_server_KeyInputQueue.cpp b/services/jni/com_android_server_KeyInputQueue.cpp
index 63830d5..f27596c 100644
--- a/services/jni/com_android_server_KeyInputQueue.cpp
+++ b/services/jni/com_android_server_KeyInputQueue.cpp
@@ -110,6 +110,23 @@
     return NULL;
 }
 
+static void
+android_server_KeyInputQueue_addExcludedDevice(JNIEnv* env, jobject clazz,
+                                              jstring deviceName)
+{
+    gLock.lock();
+    sp<EventHub> hub = gHub;
+    if (hub == NULL) {
+        hub = new EventHub;
+        gHub = hub;
+    }
+    gLock.unlock();
+
+    const char* nameStr = env->GetStringUTFChars(deviceName, NULL);
+    gHub->addExcludedDevice(nameStr);
+    env->ReleaseStringUTFChars(deviceName, nameStr);
+}
+
 static jboolean
 android_server_KeyInputQueue_getAbsoluteInfo(JNIEnv* env, jobject clazz,
                                              jint deviceId, jint axis,
@@ -205,6 +222,23 @@
     return st;
 }
 
+static jint
+android_server_KeyInputQueue_scancodeToKeycode(JNIEnv* env, jobject clazz,
+                                            jint deviceId, jint scancode)
+{
+    jint res = 0;
+    gLock.lock();
+    if (gHub != NULL) {
+        int32_t keycode;
+        uint32_t flags;
+        gHub->scancodeToKeycode(deviceId, scancode, &keycode, &flags);
+        res = keycode;
+    }
+    gLock.unlock();
+    
+    return res;
+}
+
 static jboolean
 android_server_KeyInputQueue_hasKeys(JNIEnv* env, jobject clazz,
                                      jintArray keyCodes, jbooleanArray outFlags)
@@ -238,6 +272,8 @@
         (void*) android_server_KeyInputQueue_getDeviceClasses },
     { "getDeviceName", "(I)Ljava/lang/String;",
         (void*) android_server_KeyInputQueue_getDeviceName },
+    { "addExcludedDevice", "(Ljava/lang/String;)V",
+        (void*) android_server_KeyInputQueue_addExcludedDevice },
     { "getAbsoluteInfo", "(IILcom/android/server/InputDevice$AbsoluteInfo;)Z",
         (void*) android_server_KeyInputQueue_getAbsoluteInfo },
     { "getSwitchState", "(I)I",
@@ -254,6 +290,8 @@
         (void*) android_server_KeyInputQueue_getKeycodeStateDevice },
     { "hasKeys", "([I[Z)Z",
         (void*) android_server_KeyInputQueue_hasKeys },
+    { "scancodeToKeycode", "(II)I",
+        (void*) android_server_KeyInputQueue_scancodeToKeycode },
 };
 
 int register_android_server_KeyInputQueue(JNIEnv* env)
diff --git a/telephony/java/android/telephony/PhoneNumberUtils.java b/telephony/java/android/telephony/PhoneNumberUtils.java
index dbe8431..4ed0a5c6 100644
--- a/telephony/java/android/telephony/PhoneNumberUtils.java
+++ b/telephony/java/android/telephony/PhoneNumberUtils.java
@@ -990,6 +990,7 @@
      * as:
      *
      * <p><code>
+     * xxxxx
      * xxx-xxxx
      * xxx-xxx-xxxx
      * 1-xxx-xxx-xxxx
@@ -1003,7 +1004,11 @@
         if (length > "+1-nnn-nnn-nnnn".length()) {
             // The string is too long to be formatted
             return;
+        } else if (length <= 5) {
+            // The string is either a shortcode or too short to be formatted
+            return;
         }
+
         CharSequence saved = text.subSequence(0, length);
 
         // Strip the dashes first, as we're going to add them back
diff --git a/telephony/java/com/android/internal/telephony/CommandsInterface.java b/telephony/java/com/android/internal/telephony/CommandsInterface.java
index e583110..ebdac4e 100644
--- a/telephony/java/com/android/internal/telephony/CommandsInterface.java
+++ b/telephony/java/com/android/internal/telephony/CommandsInterface.java
@@ -82,15 +82,6 @@
         }
     }
 
-    enum IccStatus {
-        ICC_ABSENT,
-        ICC_NOT_READY,
-        ICC_READY,
-        ICC_PIN,
-        ICC_PUK,
-        ICC_NETWORK_PERSONALIZATION
-    }
-
     //***** Constants
 
     // Used as parameter to dial() and setCLIR() below
@@ -534,15 +525,6 @@
      void unregisterForCdmaOtaProvision(Handler h);
 
     /**
-     * Returns current ICC status.
-     *
-     * AsyncResult.result is IccStatus
-     *
-     */
-
-    void getIccStatus(Message result);
-
-    /**
      * Supply the ICC PIN to the ICC card
      *
      *  returned message
@@ -1243,8 +1225,8 @@
      * Request the device MDN / H_SID / H_NID / MIN.
      * "response" is const char **
      *   [0] is MDN if CDMA subscription is available
-     *   [1] is H_SID (Home SID) if CDMA subscription is available
-     *   [2] is H_NID (Home NID) if CDMA subscription is available
+     *   [1] is H_SID (Home SID) in hexadecimal if CDMA subscription is available
+     *   [2] is H_NID (Home NID) in hexadecimal if CDMA subscription is available
      *   [3] is MIN (10 digits, MIN2+MIN1) if CDMA subscription is available
      */
     public void getCDMASubscription(Message response);
@@ -1366,4 +1348,12 @@
      * @param response callback message
      */
     public void exitEmergencyCallbackMode(Message response);
+
+    /**
+     * Request the status of the ICC and UICC cards.
+     *
+     * @param response
+     *          Callback message containing {@link IccCardStatus} structure for the card.
+     */
+    public void getIccCardStatus(Message result);
 }
diff --git a/telephony/java/com/android/internal/telephony/Connection.java b/telephony/java/com/android/internal/telephony/Connection.java
index 92f6cb8..e6fd0a0 100644
--- a/telephony/java/com/android/internal/telephony/Connection.java
+++ b/telephony/java/com/android/internal/telephony/Connection.java
@@ -56,7 +56,8 @@
         CDMA_RETRY_ORDER,               /* requeseted service is rejected, retry delay is set */
         CDMA_ACCESS_FAILURE,
         CDMA_PREEMPTED,
-        CDMA_NOT_EMERGENCY              /* not an emergency call */
+        CDMA_NOT_EMERGENCY,              /* not an emergency call */
+        ERROR_UNSPECIFIED
     }
 
     Object userData;
diff --git a/telephony/java/com/android/internal/telephony/IccCard.java b/telephony/java/com/android/internal/telephony/IccCard.java
index d7ad492..c2bed88 100644
--- a/telephony/java/com/android/internal/telephony/IccCard.java
+++ b/telephony/java/com/android/internal/telephony/IccCard.java
@@ -16,13 +16,40 @@
 
 package com.android.internal.telephony;
 
-import android.os.Message;
+import static android.Manifest.permission.READ_PHONE_STATE;
+import android.app.ActivityManagerNative;
+import android.content.Intent;
+import android.os.AsyncResult;
 import android.os.Handler;
+import android.os.Message;
+import android.os.Registrant;
+import android.os.RegistrantList;
+import android.util.Log;
+
+import com.android.internal.telephony.PhoneBase;
+import com.android.internal.telephony.CommandsInterface.RadioState;
 
 /**
  * {@hide}
  */
-public interface IccCard {
+public abstract class IccCard {
+    protected String mLogTag;
+    protected boolean mDbg;
+
+    private IccCardStatus mIccCardStatus = null;
+    protected State mState = null;
+    protected PhoneBase mPhone;
+    private RegistrantList mAbsentRegistrants = new RegistrantList();
+    private RegistrantList mPinLockedRegistrants = new RegistrantList();
+    private RegistrantList mNetworkLockedRegistrants = new RegistrantList();
+
+    private boolean mDesiredPinLocked;
+    private boolean mDesiredFdnEnabled;
+    private boolean mIccPinLocked = true; // Default to locked
+    private boolean mIccFdnEnabled = false; // Default to disabled.
+                                            // Will be updated when SIM_READY.
+
+
     /* The extra data for broacasting intent INTENT_ICC_STATE_CHANGE */
     static public final String INTENT_KEY_ICC_STATE = "ss";
     /* NOT_READY means the ICC interface is not ready (eg, radio is off or powering on) */
@@ -46,6 +73,17 @@
     /* NETWORK means ICC is locked on NETWORK PERSONALIZATION */
     static public final String INTENT_VALUE_LOCKED_NETWORK = "NETWORK";
 
+    protected static final int EVENT_ICC_LOCKED_OR_ABSENT = 1;
+    private static final int EVENT_GET_ICC_STATUS_DONE = 2;
+    protected static final int EVENT_RADIO_OFF_OR_NOT_AVAILABLE = 3;
+    private static final int EVENT_PINPUK_DONE = 4;
+    private static final int EVENT_REPOLL_STATUS_DONE = 5;
+    protected static final int EVENT_ICC_READY = 6;
+    private static final int EVENT_QUERY_FACILITY_LOCK_DONE = 7;
+    private static final int EVENT_CHANGE_FACILITY_LOCK_DONE = 8;
+    private static final int EVENT_CHANGE_ICC_PASSWORD_DONE = 9;
+    private static final int EVENT_QUERY_FACILITY_FDN_DONE = 10;
+    private static final int EVENT_CHANGE_FACILITY_FDN_DONE = 11;
 
     /*
       UNKNOWN is a transient state, for example, after uesr inputs ICC pin under
@@ -58,33 +96,108 @@
         PIN_REQUIRED,
         PUK_REQUIRED,
         NETWORK_LOCKED,
-        READY;
+        READY,
+        NOT_READY;
 
         public boolean isPinLocked() {
             return ((this == PIN_REQUIRED) || (this == PUK_REQUIRED));
         }
     }
 
-    State getState();
+    public State getState() {
+        if (mState == null) {
+            switch(mPhone.mCM.getRadioState()) {
+                /* This switch block must not return anything in
+                 * State.isLocked() or State.ABSENT.
+                 * If it does, handleSimStatus() may break
+                 */
+                case RADIO_OFF:
+                case RADIO_UNAVAILABLE:
+                case SIM_NOT_READY:
+                case RUIM_NOT_READY:
+                    return State.UNKNOWN;
+                case SIM_LOCKED_OR_ABSENT:
+                case RUIM_LOCKED_OR_ABSENT:
+                    //this should be transient-only
+                    return State.UNKNOWN;
+                case SIM_READY:
+                case RUIM_READY:
+                case NV_READY:
+                    return State.READY;
+                case NV_NOT_READY:
+                    return State.ABSENT;
+            }
+        } else {
+            return mState;
+        }
 
+        Log.e(mLogTag, "IccCard.getState(): case should never be reached");
+        return State.UNKNOWN;
+    }
+
+    public IccCard(PhoneBase phone, String logTag, Boolean dbg) {
+        mPhone = phone;
+        mLogTag = logTag;
+        mDbg = dbg;
+    }
+
+    abstract public void dispose();
+
+    protected void finalize() {
+        if(mDbg) Log.d(mLogTag, "IccCard finalized");
+    }
 
     /**
      * Notifies handler of any transition into State.ABSENT
      */
-    void registerForAbsent(Handler h, int what, Object obj);
-    void unregisterForAbsent(Handler h);
+    public void registerForAbsent(Handler h, int what, Object obj) {
+        Registrant r = new Registrant (h, what, obj);
 
-    /**
-     * Notifies handler of any transition into State.isPinLocked()
-     */
-    void registerForLocked(Handler h, int what, Object obj);
-    void unregisterForLocked(Handler h);
+        mAbsentRegistrants.add(r);
+
+        if (getState() == State.ABSENT) {
+            r.notifyRegistrant();
+        }
+    }
+
+    public void unregisterForAbsent(Handler h) {
+        mAbsentRegistrants.remove(h);
+    }
 
     /**
      * Notifies handler of any transition into State.NETWORK_LOCKED
      */
-    void registerForNetworkLocked(Handler h, int what, Object obj);
-    void unregisterForNetworkLocked(Handler h);
+    public void registerForNetworkLocked(Handler h, int what, Object obj) {
+        Registrant r = new Registrant (h, what, obj);
+
+        mNetworkLockedRegistrants.add(r);
+
+        if (getState() == State.NETWORK_LOCKED) {
+            r.notifyRegistrant();
+        }
+    }
+
+    public void unregisterForNetworkLocked(Handler h) {
+        mNetworkLockedRegistrants.remove(h);
+    }
+
+    /**
+     * Notifies handler of any transition into State.isPinLocked()
+     */
+    public void registerForLocked(Handler h, int what, Object obj) {
+        Registrant r = new Registrant (h, what, obj);
+
+        mPinLockedRegistrants.add(r);
+
+        if (getState().isPinLocked()) {
+            r.notifyRegistrant();
+        }
+    }
+
+    public void unregisterForLocked(Handler h) {
+        mPinLockedRegistrants.remove(h);
+    }
+
 
     /**
      * Supply the ICC PIN to the ICC
@@ -107,10 +220,30 @@
      *
      */
 
-    void supplyPin (String pin, Message onComplete);
-    void supplyPuk (String puk, String newPin, Message onComplete);
-    void supplyPin2 (String pin2, Message onComplete);
-    void supplyPuk2 (String puk2, String newPin2, Message onComplete);
+    public void supplyPin (String pin, Message onComplete) {
+        mPhone.mCM.supplyIccPin(pin, mHandler.obtainMessage(EVENT_PINPUK_DONE, onComplete));
+    }
+
+    public void supplyPuk (String puk, String newPin, Message onComplete) {
+        mPhone.mCM.supplyIccPuk(puk, newPin,
+                mHandler.obtainMessage(EVENT_PINPUK_DONE, onComplete));
+    }
+
+    public void supplyPin2 (String pin2, Message onComplete) {
+        mPhone.mCM.supplyIccPin2(pin2,
+                mHandler.obtainMessage(EVENT_PINPUK_DONE, onComplete));
+    }
+
+    public void supplyPuk2 (String puk2, String newPin2, Message onComplete) {
+        mPhone.mCM.supplyIccPuk2(puk2, newPin2,
+                mHandler.obtainMessage(EVENT_PINPUK_DONE, onComplete));
+    }
+
+    public void supplyNetworkDepersonalization (String pin, Message onComplete) {
+        if(mDbg) log("Network Despersonalization: " + pin);
+        mPhone.mCM.supplyNetworkDepersonalization(pin,
+                mHandler.obtainMessage(EVENT_PINPUK_DONE, onComplete));
+    }
 
     /**
      * Check whether ICC pin lock is enabled
@@ -119,35 +252,9 @@
      * @return true for ICC locked enabled
      *         false for ICC locked disabled
      */
-    boolean getIccLockEnabled ();
-
-    /**
-     * Set the ICC pin lock enabled or disabled
-     * When the operation is complete, onComplete will be sent to its handler
-     *
-     * @param enabled "true" for locked "false" for unlocked.
-     * @param password needed to change the ICC pin state, aka. Pin1
-     * @param onComplete
-     *        onComplete.obj will be an AsyncResult
-     *        ((AsyncResult)onComplete.obj).exception == null on success
-     *        ((AsyncResult)onComplete.obj).exception != null on fail
-     */
-    void setIccLockEnabled(boolean enabled, String password, Message onComplete);
-
-
-    /**
-     * Change the ICC password used in ICC pin lock
-     * When the operation is complete, onComplete will be sent to its handler
-     *
-     * @param oldPassword is the old password
-     * @param newPassword is the new password
-     * @param onComplete
-     *        onComplete.obj will be an AsyncResult
-     *        ((AsyncResult)onComplete.obj).exception == null on success
-     *        ((AsyncResult)onComplete.obj).exception != null on fail
-     */
-    void changeIccLockPassword(String oldPassword, String newPassword,
-                           Message onComplete);
+    public boolean getIccLockEnabled() {
+        return mIccPinLocked;
+     }
 
     /**
      * Check whether ICC fdn (fixed dialing number) is enabled
@@ -156,36 +263,99 @@
      * @return true for ICC fdn enabled
      *         false for ICC fdn disabled
      */
-    boolean getIccFdnEnabled ();
+     public boolean getIccFdnEnabled() {
+        return mIccFdnEnabled;
+     }
 
-    /**
-     * Set the ICC fdn enabled or disabled
-     * When the operation is complete, onComplete will be sent to its handler
-     *
-     * @param enabled "true" for locked "false" for unlocked.
-     * @param password needed to change the ICC fdn enable, aka Pin2
-     * @param onComplete
-     *        onComplete.obj will be an AsyncResult
-     *        ((AsyncResult)onComplete.obj).exception == null on success
-     *        ((AsyncResult)onComplete.obj).exception != null on fail
-     */
-    void setIccFdnEnabled(boolean enabled, String password, Message onComplete);
+     /**
+      * Set the ICC pin lock enabled or disabled
+      * When the operation is complete, onComplete will be sent to its handler
+      *
+      * @param enabled "true" for locked "false" for unlocked.
+      * @param password needed to change the ICC pin state, aka. Pin1
+      * @param onComplete
+      *        onComplete.obj will be an AsyncResult
+      *        ((AsyncResult)onComplete.obj).exception == null on success
+      *        ((AsyncResult)onComplete.obj).exception != null on fail
+      */
+     public void setIccLockEnabled (boolean enabled,
+             String password, Message onComplete) {
+         int serviceClassX;
+         serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE +
+                 CommandsInterface.SERVICE_CLASS_DATA +
+                 CommandsInterface.SERVICE_CLASS_FAX;
 
-    /**
-     * Change the ICC password used in ICC fdn enable
-     * When the operation is complete, onComplete will be sent to its handler
-     *
-     * @param oldPassword is the old password
-     * @param newPassword is the new password
-     * @param onComplete
-     *        onComplete.obj will be an AsyncResult
-     *        ((AsyncResult)onComplete.obj).exception == null on success
-     *        ((AsyncResult)onComplete.obj).exception != null on fail
-     */
-    void changeIccFdnPassword(String oldPassword, String newPassword,
-                           Message onComplete);
+         mDesiredPinLocked = enabled;
 
-    void supplyNetworkDepersonalization (String pin, Message onComplete);
+         mPhone.mCM.setFacilityLock(CommandsInterface.CB_FACILITY_BA_SIM,
+                 enabled, password, serviceClassX,
+                 mHandler.obtainMessage(EVENT_CHANGE_FACILITY_LOCK_DONE, onComplete));
+     }
+
+     /**
+      * Set the ICC fdn enabled or disabled
+      * When the operation is complete, onComplete will be sent to its handler
+      *
+      * @param enabled "true" for locked "false" for unlocked.
+      * @param password needed to change the ICC fdn enable, aka Pin2
+      * @param onComplete
+      *        onComplete.obj will be an AsyncResult
+      *        ((AsyncResult)onComplete.obj).exception == null on success
+      *        ((AsyncResult)onComplete.obj).exception != null on fail
+      */
+     public void setIccFdnEnabled (boolean enabled,
+             String password, Message onComplete) {
+         int serviceClassX;
+         serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE +
+                 CommandsInterface.SERVICE_CLASS_DATA +
+                 CommandsInterface.SERVICE_CLASS_FAX +
+                 CommandsInterface.SERVICE_CLASS_SMS;
+
+         mDesiredFdnEnabled = enabled;
+
+         mPhone.mCM.setFacilityLock(CommandsInterface.CB_FACILITY_BA_FD,
+                 enabled, password, serviceClassX,
+                 mHandler.obtainMessage(EVENT_CHANGE_FACILITY_FDN_DONE, onComplete));
+     }
+
+     /**
+      * Change the ICC password used in ICC pin lock
+      * When the operation is complete, onComplete will be sent to its handler
+      *
+      * @param oldPassword is the old password
+      * @param newPassword is the new password
+      * @param onComplete
+      *        onComplete.obj will be an AsyncResult
+      *        ((AsyncResult)onComplete.obj).exception == null on success
+      *        ((AsyncResult)onComplete.obj).exception != null on fail
+      */
+     public void changeIccLockPassword(String oldPassword, String newPassword,
+             Message onComplete) {
+         if(mDbg) log("Change Pin1 old: " + oldPassword + " new: " + newPassword);
+         mPhone.mCM.changeIccPin(oldPassword, newPassword,
+                 mHandler.obtainMessage(EVENT_CHANGE_ICC_PASSWORD_DONE, onComplete));
+
+     }
+
+     /**
+      * Change the ICC password used in ICC fdn enable
+      * When the operation is complete, onComplete will be sent to its handler
+      *
+      * @param oldPassword is the old password
+      * @param newPassword is the new password
+      * @param onComplete
+      *        onComplete.obj will be an AsyncResult
+      *        ((AsyncResult)onComplete.obj).exception == null on success
+      *        ((AsyncResult)onComplete.obj).exception != null on fail
+      */
+     public void changeIccFdnPassword(String oldPassword, String newPassword,
+             Message onComplete) {
+         if(mDbg) log("Change Pin2 old: " + oldPassword + " new: " + newPassword);
+         mPhone.mCM.changeIccPin2(oldPassword, newPassword,
+                 mHandler.obtainMessage(EVENT_CHANGE_ICC_PASSWORD_DONE, onComplete));
+
+     }
+
 
     /**
      * Returns service provider name stored in ICC card.
@@ -203,5 +373,301 @@
      *         yet available
      *
      */
-    String getServiceProviderName();
+    public abstract String getServiceProviderName();
+
+    protected void updateStateProperty() {
+        mPhone.setSystemProperty(TelephonyProperties.PROPERTY_SIM_STATE, getState().toString());
+    }
+
+    private void getIccCardStatusDone(AsyncResult ar) {
+        if (ar.exception != null) {
+            Log.e(mLogTag,"Error getting ICC status. "
+                    + "RIL_REQUEST_GET_ICC_STATUS should "
+                    + "never return an error", ar.exception);
+            return;
+        }
+        handleIccCardStatus((IccCardStatus) ar.result);
+    }
+
+    private void handleIccCardStatus(IccCardStatus newCardStatus) {
+        boolean transitionedIntoPinLocked;
+        boolean transitionedIntoAbsent;
+        boolean transitionedIntoNetworkLocked;
+
+        State oldState, newState;
+
+        oldState = mState;
+        mIccCardStatus = newCardStatus;
+        newState = getIccCardState();
+        mState = newState;
+
+        updateStateProperty();
+
+        transitionedIntoPinLocked = (
+                 (oldState != State.PIN_REQUIRED && newState == State.PIN_REQUIRED)
+              || (oldState != State.PUK_REQUIRED && newState == State.PUK_REQUIRED));
+        transitionedIntoAbsent = (oldState != State.ABSENT && newState == State.ABSENT);
+        transitionedIntoNetworkLocked = (oldState != State.NETWORK_LOCKED
+                && newState == State.NETWORK_LOCKED);
+
+        if (transitionedIntoPinLocked) {
+            if(mDbg) log("Notify SIM pin or puk locked.");
+            mPinLockedRegistrants.notifyRegistrants();
+            broadcastIccStateChangedIntent(INTENT_VALUE_ICC_LOCKED,
+                    (newState == State.PIN_REQUIRED) ?
+                       INTENT_VALUE_LOCKED_ON_PIN : INTENT_VALUE_LOCKED_ON_PUK);
+        } else if (transitionedIntoAbsent) {
+            if(mDbg) log("Notify SIM missing.");
+            mAbsentRegistrants.notifyRegistrants();
+            broadcastIccStateChangedIntent(INTENT_VALUE_ICC_ABSENT, null);
+        } else if (transitionedIntoNetworkLocked) {
+            if(mDbg) log("Notify SIM network locked.");
+            mNetworkLockedRegistrants.notifyRegistrants();
+            broadcastIccStateChangedIntent(INTENT_VALUE_ICC_LOCKED,
+                  INTENT_VALUE_LOCKED_NETWORK);
+        }
+    }
+
+    /**
+     * Interperate EVENT_QUERY_FACILITY_LOCK_DONE
+     * @param ar is asyncResult of Query_Facility_Locked
+     */
+    private void onQueryFdnEnabled(AsyncResult ar) {
+        if(ar.exception != null) {
+            if(mDbg) log("Error in querying facility lock:" + ar.exception);
+            return;
+        }
+
+        int[] ints = (int[])ar.result;
+        if(ints.length != 0) {
+            mIccFdnEnabled = (0!=ints[0]);
+            if(mDbg) log("Query facility lock : "  + mIccFdnEnabled);
+        } else {
+            Log.e(mLogTag, "[IccCard] Bogus facility lock response");
+        }
+    }
+
+    /**
+     * Interperate EVENT_QUERY_FACILITY_LOCK_DONE
+     * @param ar is asyncResult of Query_Facility_Locked
+     */
+    private void onQueryFacilityLock(AsyncResult ar) {
+        if(ar.exception != null) {
+            if (mDbg) log("Error in querying facility lock:" + ar.exception);
+            return;
+        }
+
+        int[] ints = (int[])ar.result;
+        if(ints.length != 0) {
+            mIccPinLocked = (0!=ints[0]);
+            if(mDbg) log("Query facility lock : "  + mIccPinLocked);
+        } else {
+            Log.e(mLogTag, "[IccCard] Bogus facility lock response");
+        }
+    }
+
+    public void broadcastIccStateChangedIntent(String value, String reason) {
+        Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
+        intent.putExtra(Phone.PHONE_NAME_KEY, mPhone.getPhoneName());
+        intent.putExtra(INTENT_KEY_ICC_STATE, value);
+        intent.putExtra(INTENT_KEY_LOCKED_REASON, reason);
+        if(mDbg) log("Broadcasting intent ACTION_SIM_STATE_CHANGED " +  value
+                + " reason " + reason);
+        ActivityManagerNative.broadcastStickyIntent(intent, READ_PHONE_STATE);
+    }
+
+    protected Handler mHandler = new Handler() {
+        @Override
+        public void handleMessage(Message msg){
+            AsyncResult ar;
+            int serviceClassX;
+
+            serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE +
+                            CommandsInterface.SERVICE_CLASS_DATA +
+                            CommandsInterface.SERVICE_CLASS_FAX;
+
+            switch (msg.what) {
+                case EVENT_RADIO_OFF_OR_NOT_AVAILABLE:
+                    mState = null;
+                    updateStateProperty();
+                    broadcastIccStateChangedIntent(INTENT_VALUE_ICC_NOT_READY, null);
+                    break;
+                case EVENT_ICC_READY:
+                    //TODO: put facility read in SIM_READY now, maybe in REG_NW
+                    mPhone.mCM.getIccCardStatus(obtainMessage(EVENT_GET_ICC_STATUS_DONE));
+                    mPhone.mCM.queryFacilityLock (
+                            CommandsInterface.CB_FACILITY_BA_SIM, "", serviceClassX,
+                            obtainMessage(EVENT_QUERY_FACILITY_LOCK_DONE));
+                    mPhone.mCM.queryFacilityLock (
+                            CommandsInterface.CB_FACILITY_BA_FD, "", serviceClassX,
+                            obtainMessage(EVENT_QUERY_FACILITY_FDN_DONE));
+                    break;
+                case EVENT_ICC_LOCKED_OR_ABSENT:
+                    mPhone.mCM.getIccCardStatus(obtainMessage(EVENT_GET_ICC_STATUS_DONE));
+                    mPhone.mCM.queryFacilityLock (
+                            CommandsInterface.CB_FACILITY_BA_SIM, "", serviceClassX,
+                            obtainMessage(EVENT_QUERY_FACILITY_LOCK_DONE));
+                    break;
+                case EVENT_GET_ICC_STATUS_DONE:
+                    ar = (AsyncResult)msg.obj;
+
+                    getIccCardStatusDone(ar);
+                    break;
+                case EVENT_PINPUK_DONE:
+                    // a PIN/PUK/PIN2/PUK2/Network Personalization
+                    // request has completed. ar.userObj is the response Message
+                    // Repoll before returning
+                    ar = (AsyncResult)msg.obj;
+                    // TODO should abstract these exceptions
+                    AsyncResult.forMessage(((Message)ar.userObj)).exception
+                                                        = ar.exception;
+                    mPhone.mCM.getIccCardStatus(
+                        obtainMessage(EVENT_REPOLL_STATUS_DONE, ar.userObj));
+                    break;
+                case EVENT_REPOLL_STATUS_DONE:
+                    // Finished repolling status after PIN operation
+                    // ar.userObj is the response messaeg
+                    // ar.userObj.obj is already an AsyncResult with an
+                    // appropriate exception filled in if applicable
+
+                    ar = (AsyncResult)msg.obj;
+                    getIccCardStatusDone(ar);
+                    ((Message)ar.userObj).sendToTarget();
+                    break;
+                case EVENT_QUERY_FACILITY_LOCK_DONE:
+                    ar = (AsyncResult)msg.obj;
+                    onQueryFacilityLock(ar);
+                    break;
+                case EVENT_QUERY_FACILITY_FDN_DONE:
+                    ar = (AsyncResult)msg.obj;
+                    onQueryFdnEnabled(ar);
+                    break;
+                case EVENT_CHANGE_FACILITY_LOCK_DONE:
+                    ar = (AsyncResult)msg.obj;
+                    if (ar.exception == null) {
+                        mIccPinLocked = mDesiredPinLocked;
+                        if (mDbg) log( "EVENT_CHANGE_FACILITY_LOCK_DONE: " +
+                                "mIccPinLocked= " + mIccPinLocked);
+                    } else {
+                        Log.e(mLogTag, "Error change facility lock with exception "
+                            + ar.exception);
+                    }
+                    AsyncResult.forMessage(((Message)ar.userObj)).exception
+                                                        = ar.exception;
+                    ((Message)ar.userObj).sendToTarget();
+                    break;
+                case EVENT_CHANGE_FACILITY_FDN_DONE:
+                    ar = (AsyncResult)msg.obj;
+
+                    if (ar.exception == null) {
+                        mIccFdnEnabled = mDesiredFdnEnabled;
+                        if (mDbg) log("EVENT_CHANGE_FACILITY_FDN_DONE: " +
+                                "mIccFdnEnabled=" + mIccFdnEnabled);
+                    } else {
+                        Log.e(mLogTag, "Error change facility fdn with exception "
+                                + ar.exception);
+                    }
+                    AsyncResult.forMessage(((Message)ar.userObj)).exception
+                                                        = ar.exception;
+                    ((Message)ar.userObj).sendToTarget();
+                    break;
+                case EVENT_CHANGE_ICC_PASSWORD_DONE:
+                    ar = (AsyncResult)msg.obj;
+                    if(ar.exception != null) {
+                        Log.e(mLogTag, "Error in change sim password with exception"
+                            + ar.exception);
+                    }
+                    AsyncResult.forMessage(((Message)ar.userObj)).exception
+                                                        = ar.exception;
+                    ((Message)ar.userObj).sendToTarget();
+                    break;
+                default:
+                    Log.e(mLogTag, "[IccCard] Unknown Event " + msg.what);
+            }
+        }
+    };
+
+    public State getIccCardState() {
+        if (mIccCardStatus == null) {
+            Log.e(mLogTag, "[IccCard] IccCardStatus is null");
+            return IccCard.State.ABSENT;
+        }
+
+        // this is common for all radio technologies
+        if (!mIccCardStatus.getCardState().isCardPresent()) {
+            return IccCard.State.NOT_READY;
+        }
+
+        RadioState currentRadioState = mPhone.mCM.getRadioState();
+        // check radio technology
+        if( currentRadioState == RadioState.RADIO_OFF         ||
+            currentRadioState == RadioState.RADIO_UNAVAILABLE ||
+            currentRadioState == RadioState.SIM_NOT_READY     ||
+            currentRadioState == RadioState.RUIM_NOT_READY    ||
+            currentRadioState == RadioState.NV_NOT_READY      ||
+            currentRadioState == RadioState.NV_READY) {
+            return IccCard.State.NOT_READY;
+        }
+
+        if( currentRadioState == RadioState.SIM_LOCKED_OR_ABSENT  ||
+            currentRadioState == RadioState.SIM_READY             ||
+            currentRadioState == RadioState.RUIM_LOCKED_OR_ABSENT ||
+            currentRadioState == RadioState.RUIM_READY) {
+
+            int index;
+
+            // check for CDMA radio technology
+            if (currentRadioState == RadioState.RUIM_LOCKED_OR_ABSENT ||
+                currentRadioState == RadioState.RUIM_READY) {
+                index = mIccCardStatus.getCdmaSubscriptionAppIndex();
+            }
+            else {
+                index = mIccCardStatus.getGsmUmtsSubscriptionAppIndex();
+            }
+
+            IccCardApplication app = mIccCardStatus.getApplication(index);
+
+            if (app == null) {
+                Log.e(mLogTag, "[IccCard] Subscription Application in not present");
+                return IccCard.State.ABSENT;
+            }
+
+            // check if PIN required
+            if (app.app_state.isPinRequired()) {
+                return IccCard.State.PIN_REQUIRED;
+            }
+            if (app.app_state.isPukRequired()) {
+                return IccCard.State.PUK_REQUIRED;
+            }
+            if (app.app_state.isSubscriptionPersoEnabled()) {
+                return IccCard.State.NETWORK_LOCKED;
+            }
+            if (app.app_state.isAppReady()) {
+                return IccCard.State.READY;
+            }
+            if (app.app_state.isAppNotReady()) {
+                return IccCard.State.NOT_READY;
+            }
+            return IccCard.State.NOT_READY;
+        }
+
+        return IccCard.State.ABSENT;
+    }
+
+
+    public boolean hasApplicationType(IccCardApplication.AppType type) {
+        if (mIccCardStatus == null) return false;
+
+        for (int i = 0 ; i < mIccCardStatus.getNumApplications(); i++) {
+            IccCardApplication app = mIccCardStatus.getApplication(i);
+            if (app != null && app.app_type == type) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private void log(String msg) {
+        Log.d(mLogTag, "[IccCard] " + msg);
+    }
 }
diff --git a/telephony/java/com/android/internal/telephony/IccCardStatus.java b/telephony/java/com/android/internal/telephony/IccCardStatus.java
index b602b1c..0e7bad7 100644
--- a/telephony/java/com/android/internal/telephony/IccCardStatus.java
+++ b/telephony/java/com/android/internal/telephony/IccCardStatus.java
@@ -45,42 +45,89 @@
         PINSTATE_ENABLED_PERM_BLOCKED
     };
 
-    public CardState  card_state;
-    public PinState   universal_pin_state;
-    public int        gsm_umts_subscription_app_index;
-    public int        cdma_subscription_app_index;
-    public int        num_applications;
+    private CardState  mCardState;
+    private PinState   mUniversalPinState;
+    private int        mGsmUmtsSubscriptionAppIndex;
+    private int        mCdmaSubscriptionAppIndex;
+    private int        mNumApplications;
 
-    ArrayList<IccCardApplication> application = new ArrayList<IccCardApplication>(CARD_MAX_APPS);
+    private ArrayList<IccCardApplication> mApplications =
+            new ArrayList<IccCardApplication>(CARD_MAX_APPS);
 
-    CardState CardStateFromRILInt(int state) {
-        CardState newState;
-        /* RIL_CardState ril.h */
-        switch(state) {
-            case 0: newState = CardState.CARDSTATE_ABSENT; break;
-            case 1: newState = CardState.CARDSTATE_PRESENT; break;
-            case 2: newState = CardState.CARDSTATE_ERROR; break;
-            default:
-                throw new RuntimeException(
-                            "Unrecognized RIL_CardState: " +state);
-        }
-        return newState;
+    public CardState getCardState() {
+        return mCardState;
     }
 
-    PinState PinStateFromRILInt(int state) {
-        PinState newState;
-        /* RIL_PinState ril.h */
+    public void setCardState(int state) {
         switch(state) {
-            case 0: newState = PinState.PINSTATE_UNKNOWN; break;
-            case 1: newState = PinState.PINSTATE_ENABLED_NOT_VERIFIED; break;
-            case 2: newState = PinState.PINSTATE_ENABLED_VERIFIED; break;
-            case 3: newState = PinState.PINSTATE_DISABLED; break;
-            case 4: newState = PinState.PINSTATE_ENABLED_BLOCKED; break;
-            case 5: newState = PinState.PINSTATE_ENABLED_PERM_BLOCKED; break;
-            default:
-                throw new RuntimeException(
-                            "Unrecognized RIL_PinState: " +state);
+        case 0:
+            mCardState = CardState.CARDSTATE_ABSENT;
+            break;
+        case 1:
+            mCardState = CardState.CARDSTATE_PRESENT;
+            break;
+        case 2:
+            mCardState = CardState.CARDSTATE_ERROR;
+            break;
+        default:
+            throw new RuntimeException("Unrecognized RIL_CardState: " + state);
         }
-        return newState;
+    }
+
+    public void setUniversalPinState(int state) {
+        switch(state) {
+        case 0:
+            mUniversalPinState = PinState.PINSTATE_UNKNOWN;
+            break;
+        case 1:
+            mUniversalPinState = PinState.PINSTATE_ENABLED_NOT_VERIFIED;
+            break;
+        case 2:
+            mUniversalPinState = PinState.PINSTATE_ENABLED_VERIFIED;
+            break;
+        case 3:
+            mUniversalPinState = PinState.PINSTATE_DISABLED;
+            break;
+        case 4:
+            mUniversalPinState = PinState.PINSTATE_ENABLED_BLOCKED;
+            break;
+        case 5:
+            mUniversalPinState = PinState.PINSTATE_ENABLED_PERM_BLOCKED;
+            break;
+        default:
+            throw new RuntimeException("Unrecognized RIL_PinState: " + state);
+        }
+    }
+
+    public int getGsmUmtsSubscriptionAppIndex() {
+        return mGsmUmtsSubscriptionAppIndex;
+    }
+
+    public void setGsmUmtsSubscriptionAppIndex(int gsmUmtsSubscriptionAppIndex) {
+        mGsmUmtsSubscriptionAppIndex = gsmUmtsSubscriptionAppIndex;
+    }
+
+    public int getCdmaSubscriptionAppIndex() {
+        return mCdmaSubscriptionAppIndex;
+    }
+
+    public void setCdmaSubscriptionAppIndex(int cdmaSubscriptionAppIndex) {
+        mCdmaSubscriptionAppIndex = cdmaSubscriptionAppIndex;
+    }
+
+    public int getNumApplications() {
+        return mNumApplications;
+    }
+
+    public void setNumApplications(int numApplications) {
+        mNumApplications = numApplications;
+    }
+
+    public void addApplication(IccCardApplication application) {
+        mApplications.add(application);
+    }
+
+    public IccCardApplication getApplication(int index) {
+        return mApplications.get(index);
     }
 }
diff --git a/telephony/java/com/android/internal/telephony/Phone.java b/telephony/java/com/android/internal/telephony/Phone.java
index 7f2b849..769226e 100644
--- a/telephony/java/com/android/internal/telephony/Phone.java
+++ b/telephony/java/com/android/internal/telephony/Phone.java
@@ -22,6 +22,7 @@
 import android.os.Message;
 import android.preference.PreferenceManager;
 import android.telephony.CellLocation;
+import android.telephony.PhoneStateListener;
 import android.telephony.ServiceState;
 import android.telephony.SignalStrength;
 
@@ -260,8 +261,8 @@
 
     /**
      * Get current coarse-grained voice call state.
-     * Use {@link #registerForPhoneStateChanged(Handler, int, Object)
-     * registerForPhoneStateChanged()} for change notification. <p>
+     * Use {@link #registerForPreciseCallStateChanged(Handler, int, Object)
+     * registerForPreciseCallStateChanged()} for change notification. <p>
      * If the phone has an active call and call waiting occurs,
      * then the phone state is RINGING not OFFHOOK
      * <strong>Note:</strong>
@@ -315,18 +316,21 @@
     void unregisterForUnknownConnection(Handler h);
 
     /**
-     * Notifies when any aspect of the voice call state changes.
+     * Register for getting notifications for change in the Call State {@link Call.State}
+     * This is called PreciseCallState because the call state is more precise than the
+     * {@link Phone.State} which can be obtained using the {@link PhoneStateListener}
+     *
      * Resulting events will have an AsyncResult in <code>Message.obj</code>.
      * AsyncResult.userData will be set to the obj argument here.
      * The <em>h</em> parameter is held only by a weak reference.
      */
-    void registerForPhoneStateChanged(Handler h, int what, Object obj);
+    void registerForPreciseCallStateChanged(Handler h, int what, Object obj);
 
     /**
      * Unregisters for voice call state change notifications.
      * Extraneous calls are tolerated silently.
      */
-    void unregisterForPhoneStateChanged(Handler h);
+    void unregisterForPreciseCallStateChanged(Handler h);
 
 
     /**
@@ -556,8 +560,8 @@
     /**
      * Answers a ringing or waiting call. Active calls, if any, go on hold.
      * Answering occurs asynchronously, and final notification occurs via
-     * {@link #registerForPhoneStateChanged(android.os.Handler, int,
-     * java.lang.Object) registerForPhoneStateChanged()}.
+     * {@link #registerForPreciseCallStateChanged(android.os.Handler, int,
+     * java.lang.Object) registerForPreciseCallStateChanged()}.
      *
      * @exception CallStateException when no call is ringing or waiting
      */
@@ -567,8 +571,8 @@
      * Reject (ignore) a ringing call. In GSM, this means UDUB
      * (User Determined User Busy). Reject occurs asynchronously,
      * and final notification occurs via
-     * {@link #registerForPhoneStateChanged(android.os.Handler, int,
-     * java.lang.Object) registerForPhoneStateChanged()}.
+     * {@link #registerForPreciseCallStateChanged(android.os.Handler, int,
+     * java.lang.Object) registerForPreciseCallStateChanged()}.
      *
      * @exception CallStateException when no call is ringing or waiting
      */
@@ -578,8 +582,8 @@
      * Places any active calls on hold, and makes any held calls
      *  active. Switch occurs asynchronously and may fail.
      * Final notification occurs via
-     * {@link #registerForPhoneStateChanged(android.os.Handler, int,
-     * java.lang.Object) registerForPhoneStateChanged()}.
+     * {@link #registerForPreciseCallStateChanged(android.os.Handler, int,
+     * java.lang.Object) registerForPreciseCallStateChanged()}.
      *
      * @exception CallStateException if a call is ringing, waiting, or
      * dialing/alerting. In these cases, this operation may not be performed.
@@ -596,8 +600,8 @@
     /**
      * Conferences holding and active. Conference occurs asynchronously
      * and may fail. Final notification occurs via
-     * {@link #registerForPhoneStateChanged(android.os.Handler, int,
-     * java.lang.Object) registerForPhoneStateChanged()}.
+     * {@link #registerForPreciseCallStateChanged(android.os.Handler, int,
+     * java.lang.Object) registerForPreciseCallStateChanged()}.
      *
      * @exception CallStateException if canConference() would return false.
      * In these cases, this operation may not be performed.
@@ -631,8 +635,8 @@
      * Connects the two calls and disconnects the subscriber from both calls
      * Explicit Call Transfer occurs asynchronously
      * and may fail. Final notification occurs via
-     * {@link #registerForPhoneStateChanged(android.os.Handler, int,
-     * java.lang.Object) registerForPhoneStateChanged()}.
+     * {@link #registerForPreciseCallStateChanged(android.os.Handler, int,
+     * java.lang.Object) registerForPreciseCallStateChanged()}.
      *
      * @exception CallStateException if canTransfer() would return false.
      * In these cases, this operation may not be performed.
@@ -659,8 +663,8 @@
      * IDLE, ACTIVE, DIALING, ALERTING, or DISCONNECTED.
      *
      * State change notification is available via
-     * {@link #registerForPhoneStateChanged(android.os.Handler, int,
-     * java.lang.Object) registerForPhoneStateChanged()}.
+     * {@link #registerForPreciseCallStateChanged(android.os.Handler, int,
+     * java.lang.Object) registerForPreciseCallStateChanged()}.
      */
     Call getForegroundCall();
 
@@ -676,8 +680,8 @@
      * IDLE, HOLDING or DISCONNECTED.
      *
      * State change notification is available via
-     * {@link #registerForPhoneStateChanged(android.os.Handler, int,
-     * java.lang.Object) registerForPhoneStateChanged()}.
+     * {@link #registerForPreciseCallStateChanged(android.os.Handler, int,
+     * java.lang.Object) registerForPreciseCallStateChanged()}.
      */
     Call getBackgroundCall();
 
@@ -693,8 +697,8 @@
      * IDLE, INCOMING, WAITING or DISCONNECTED.
      *
      * State change notification is available via
-     * {@link #registerForPhoneStateChanged(android.os.Handler, int,
-     * java.lang.Object) registerForPhoneStateChanged()}.
+     * {@link #registerForPreciseCallStateChanged(android.os.Handler, int,
+     * java.lang.Object) registerForPreciseCallStateChanged()}.
      */
     Call getRingingCall();
 
@@ -1067,8 +1071,8 @@
 
     /**
      * Gets current mute status. Use
-     * {@link #registerForPhoneStateChanged(android.os.Handler, int,
-     * java.lang.Object) registerForPhoneStateChanged()}
+     * {@link #registerForPreciseCallStateChanged(android.os.Handler, int,
+     * java.lang.Object) registerForPreciseCallStateChanged()}
      * as a change notifcation, although presently phone state changed is not
      * fired when setMute() is called.
      *
@@ -1262,6 +1266,13 @@
     boolean disableDataConnectivity();
 
     /**
+     * Report the current state of data connectivity (enabled or disabled)
+     * @return {@code false} if data connectivity has been explicitly disabled,
+     * {@code true} otherwise.
+     */
+    boolean isDataConnectivityEnabled();
+
+    /**
      * Enables the specified APN type. Only works for "special" APN types,
      * i.e., not the default APN.
      * @param type The desired APN type. Cannot be {@link #APN_TYPE_DEFAULT}.
diff --git a/telephony/java/com/android/internal/telephony/PhoneBase.java b/telephony/java/com/android/internal/telephony/PhoneBase.java
index bcb1ccc..fbda221 100644
--- a/telephony/java/com/android/internal/telephony/PhoneBase.java
+++ b/telephony/java/com/android/internal/telephony/PhoneBase.java
@@ -21,6 +21,7 @@
 import android.content.Context;
 import android.content.res.Configuration;
 import android.content.SharedPreferences;
+import android.net.wifi.WifiManager;
 import android.os.AsyncResult;
 import android.os.Handler;
 import android.os.Looper;
@@ -28,6 +29,7 @@
 import android.os.RegistrantList;
 import android.os.SystemProperties;
 import android.preference.PreferenceManager;
+import android.provider.Settings;
 import android.telephony.ServiceState;
 import android.telephony.SignalStrength;
 import android.text.TextUtils;
@@ -117,7 +119,7 @@
     }
 
 
-    protected final RegistrantList mPhoneStateRegistrants
+    protected final RegistrantList mPreciseCallStateRegistrants
             = new RegistrantList();
 
     protected final RegistrantList mNewRingingConnectionRegistrants
@@ -185,7 +187,7 @@
         this.mContext = context;
         mLooper = Looper.myLooper();
 
-        setLocaleByCarrier();
+        setPropertiesByCarrier();
 
         setUnitTestMode(unitTestMode);
 
@@ -219,25 +221,24 @@
     }
 
     // Inherited documentation suffices.
-    public void registerForPhoneStateChanged(Handler h, int what, Object obj) {
+    public void registerForPreciseCallStateChanged(Handler h, int what, Object obj) {
         checkCorrectThread(h);
 
-        mPhoneStateRegistrants.addUnique(h, what, obj);
+        mPreciseCallStateRegistrants.addUnique(h, what, obj);
     }
 
     // Inherited documentation suffices.
-    public void unregisterForPhoneStateChanged(Handler h) {
-        mPhoneStateRegistrants.remove(h);
+    public void unregisterForPreciseCallStateChanged(Handler h) {
+        mPreciseCallStateRegistrants.remove(h);
     }
 
     /**
-     * Notify registrants of a PhoneStateChanged.
      * Subclasses of Phone probably want to replace this with a
      * version scoped to their packages
      */
-    protected void notifyCallStateChangedP() {
+    protected void notifyPreciseCallStateChangedP() {
         AsyncResult ar = new AsyncResult(null, this, null);
-        mPhoneStateRegistrants.notifyRegistrants(ar);
+        mPreciseCallStateRegistrants.notifyRegistrants(ar);
     }
 
     // Inherited documentation suffices.
@@ -450,10 +451,10 @@
     }
 
     /**
-     * Set the locale by matching the carrier string in
+     * Set the properties by matching the carrier string in
      * a string-array resource
      */
-    private void setLocaleByCarrier() {
+    private void setPropertiesByCarrier() {
         String carrier = SystemProperties.get("ro.carrier");
 
         if (null == carrier || 0 == carrier.length()) {
@@ -461,18 +462,36 @@
         }
 
         CharSequence[] carrierLocales = mContext.
-                getResources().getTextArray(R.array.carrier_locales);
+                getResources().getTextArray(R.array.carrier_properties);
 
-        for (int i = 0; i < carrierLocales.length-1; i+=2) {
+        for (int i = 0; i < carrierLocales.length; i+=3) {
             String c = carrierLocales[i].toString();
-            String l = carrierLocales[i+1].toString();
             if (carrier.equals(c)) {
+                String l = carrierLocales[i+1].toString();
+                int wifiChannels = 0;
+                try {
+                    wifiChannels = Integer.parseInt(
+                            carrierLocales[i+2].toString());
+                } catch (NumberFormatException e) { }
+
                 String language = l.substring(0, 2);
                 String country = "";
                 if (l.length() >=5) {
                     country = l.substring(3, 5);
                 }
                 setSystemLocale(language, country);
+
+                if (wifiChannels != 0) {
+                    try {
+                        Settings.Secure.getInt(mContext.getContentResolver(),
+                                Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS);
+                    } catch (Settings.SettingNotFoundException e) {
+                        // note this is not persisting
+                        WifiManager wM = (WifiManager)
+                                mContext.getSystemService(Context.WIFI_SERVICE);
+                        wM.setNumAllowedChannels(wifiChannels, false);
+                    }
+                }
                 return;
             }
         }
diff --git a/telephony/java/com/android/internal/telephony/PhoneProxy.java b/telephony/java/com/android/internal/telephony/PhoneProxy.java
index da00268..30d56da 100644
--- a/telephony/java/com/android/internal/telephony/PhoneProxy.java
+++ b/telephony/java/com/android/internal/telephony/PhoneProxy.java
@@ -25,6 +25,7 @@
 import android.os.Message;
 import android.preference.PreferenceManager;
 import android.telephony.CellLocation;
+import android.telephony.PhoneStateListener;
 import android.telephony.ServiceState;
 import android.telephony.SignalStrength;
 import android.util.Log;
@@ -210,12 +211,12 @@
         mActivePhone.unregisterForUnknownConnection(h);
     }
 
-    public void registerForPhoneStateChanged(Handler h, int what, Object obj) {
-        mActivePhone.registerForPhoneStateChanged(h, what, obj);
+    public void registerForPreciseCallStateChanged(Handler h, int what, Object obj) {
+        mActivePhone.registerForPreciseCallStateChanged(h, what, obj);
     }
 
-    public void unregisterForPhoneStateChanged(Handler h) {
-        mActivePhone.unregisterForPhoneStateChanged(h);
+    public void unregisterForPreciseCallStateChanged(Handler h) {
+        mActivePhone.unregisterForPreciseCallStateChanged(h);
     }
 
     public void registerForNewRingingConnection(Handler h, int what, Object obj) {
@@ -613,6 +614,10 @@
         return mActivePhone.disableApnType(type);
     }
 
+    public boolean isDataConnectivityEnabled() {
+        return mActivePhone.isDataConnectivityEnabled();
+    }
+
     public boolean isDataConnectivityPossible() {
         return mActivePhone.isDataConnectivityPossible();
     }
diff --git a/telephony/java/com/android/internal/telephony/RIL.java b/telephony/java/com/android/internal/telephony/RIL.java
index 690b38a..2bec9bc 100644
--- a/telephony/java/com/android/internal/telephony/RIL.java
+++ b/telephony/java/com/android/internal/telephony/RIL.java
@@ -630,7 +630,7 @@
     }
 
     public void
-    getIccStatus(Message result) {
+    getIccCardStatus(Message result) {
         //Note: This RIL request has not been renamed to ICC,
         //       but this request is also valid for SIM and RUIM
         RILRequest rr = RILRequest.obtain(RIL_REQUEST_GET_SIM_STATUS, result);
@@ -2735,24 +2735,22 @@
 
     private Object
     responseIccCardStatus(Parcel p) {
-        RadioState currentRadioState;
         IccCardApplication ca;
 
-        currentRadioState = getRadioState();
-
         IccCardStatus status = new IccCardStatus();
-        status.card_state                      = status.CardStateFromRILInt(p.readInt());
-        status.universal_pin_state             = status.PinStateFromRILInt(p.readInt());
-        status.gsm_umts_subscription_app_index = p.readInt();
-        status.cdma_subscription_app_index     = p.readInt();
-        status.num_applications                = p.readInt();
+        status.setCardState(p.readInt());
+        status.setUniversalPinState(p.readInt());
+        status.setGsmUmtsSubscriptionAppIndex(p.readInt());
+        status.setCdmaSubscriptionAppIndex(p.readInt());
+        int numApplications = p.readInt();
 
         // limit to maximum allowed applications
-        if (status.num_applications > IccCardStatus.CARD_MAX_APPS) {
-            status.num_applications = IccCardStatus.CARD_MAX_APPS;
+        if (numApplications > IccCardStatus.CARD_MAX_APPS) {
+            numApplications = IccCardStatus.CARD_MAX_APPS;
         }
+        status.setNumApplications(numApplications);
 
-        for (int i = 0 ; i < status.num_applications ; i++) {
+        for (int i = 0 ; i < numApplications ; i++) {
             ca = new IccCardApplication();
             ca.app_type       = ca.AppTypeFromRILInt(p.readInt());
             ca.app_state      = ca.AppStateFromRILInt(p.readInt());
@@ -2762,62 +2760,9 @@
             ca.pin1_replaced  = p.readInt();
             ca.pin1           = p.readInt();
             ca.pin2           = p.readInt();
-            status.application.add(ca);
+            status.addApplication(ca);
         }
-
-        // this is common for all radio technologies
-        if (!status.card_state.isCardPresent()) {
-            return IccStatus.ICC_ABSENT;
-        }
-
-        // check radio technology
-        if( currentRadioState == RadioState.RADIO_OFF         ||
-            currentRadioState == RadioState.RADIO_UNAVAILABLE ||
-            currentRadioState == RadioState.SIM_NOT_READY     ||
-            currentRadioState == RadioState.RUIM_NOT_READY    ||
-            currentRadioState == RadioState.NV_NOT_READY      ||
-            currentRadioState == RadioState.NV_READY            ) {
-            return IccStatus.ICC_NOT_READY;
-        }
-
-        if( currentRadioState == RadioState.SIM_LOCKED_OR_ABSENT  ||
-            currentRadioState == RadioState.SIM_READY             ||
-            currentRadioState == RadioState.RUIM_LOCKED_OR_ABSENT ||
-            currentRadioState == RadioState.RUIM_READY) {
-
-            int index;
-
-            // check for CDMA radio technology
-            if (currentRadioState == RadioState.RUIM_LOCKED_OR_ABSENT ||
-                currentRadioState == RadioState.RUIM_READY) {
-                index = status.cdma_subscription_app_index;
-            }
-            else {
-                index = status.gsm_umts_subscription_app_index;
-            }
-
-            // check if PIN required
-            if (status.application.get(index).app_state.isPinRequired()) {
-                return IccStatus.ICC_PIN;
-            }
-            if (status.application.get(index).app_state.isPukRequired()) {
-                return IccStatus.ICC_PUK;
-            }
-            if (status.application.get(index).app_state.isSubscriptionPersoEnabled()) {
-                return IccStatus.ICC_NETWORK_PERSONALIZATION;
-            }
-            if (status.application.get(index).app_state.isAppReady()) {
-                return IccStatus.ICC_READY;
-            }
-            if (status.application.get(index).app_state.isAppNotReady()) {
-                return IccStatus.ICC_NOT_READY;
-            }
-            return IccStatus.ICC_NOT_READY;
-        }
-
-        // Unrecognized ICC status. Treat it like a missing ICC.
-        Log.e(LOG_TAG, "Unrecognized RIL_REQUEST_GET_SIM_STATUS result: " + status);
-        return IccStatus.ICC_ABSENT;
+        return status;
     }
 
     private Object
diff --git a/telephony/java/com/android/internal/telephony/ServiceStateTracker.java b/telephony/java/com/android/internal/telephony/ServiceStateTracker.java
index bdcf3f7..8e76cd2 100644
--- a/telephony/java/com/android/internal/telephony/ServiceStateTracker.java
+++ b/telephony/java/com/android/internal/telephony/ServiceStateTracker.java
@@ -116,6 +116,7 @@
     protected static final int EVENT_POLL_STATE_CDMA_SUBSCRIPTION      = 34;
     protected static final int EVENT_NV_READY                          = 35;
     protected static final int EVENT_ERI_FILE_LOADED                   = 36;
+    protected static final int EVENT_OTA_PROVISION_STATUS_CHANGE       = 37;
 
     //***** Time Zones
     protected static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
diff --git a/telephony/java/com/android/internal/telephony/SmsMessageBase.java b/telephony/java/com/android/internal/telephony/SmsMessageBase.java
index 3c7dd45..9c78b98 100644
--- a/telephony/java/com/android/internal/telephony/SmsMessageBase.java
+++ b/telephony/java/com/android/internal/telephony/SmsMessageBase.java
@@ -352,60 +352,36 @@
     }
 
     /**
-     * Try to parse this message as an email gateway message -> Neither
-     * of the standard ways are currently supported: There are two ways
-     * specified in TS 23.040 Section 3.8 (not supported via this mechanism) -
-     * SMS message "may have its TP-PID set for internet electronic mail - MT
+     * Try to parse this message as an email gateway message
+     * There are two ways specified in TS 23.040 Section 3.8 :
+     *  - SMS message "may have its TP-PID set for internet electronic mail - MT
      * SMS format: [<from-address><space>]<message> - "Depending on the
      * nature of the gateway, the destination/origination address is either
      * derived from the content of the SMS TP-OA or TP-DA field, or the
      * TP-OA/TP-DA field contains a generic gateway address and the to/from
-     * address is added at the beginning as shown above." - multiple addreses
-     * separated by commas, no spaces - subject field delimited by '()' or '##'
-     * and '#' Section 9.2.3.24.11
+     * address is added at the beginning as shown above." (which is supported here)
+     * - Multiple addreses separated by commas, no spaces, Subject field delimited
+     * by '()' or '##' and '#' Section 9.2.3.24.11 (which are NOT supported here)
      */
     protected void extractEmailAddressFromMessageBody() {
 
-        /*
-         * a little guesswork here. I haven't found doc for this.
-         * the format could be either
+        /* Some carriers may use " /" delimiter as below
          *
          * 1. [x@y][ ]/[subject][ ]/[body]
          * -or-
          * 2. [x@y][ ]/[body]
          */
-        int slash = 0, slash2 = 0, atSymbol = 0;
-
-        try {
-            slash = messageBody.indexOf(" /");
-            if (slash == -1) {
-                return;
-            }
-
-            atSymbol = messageBody.indexOf('@');
-            if (atSymbol == -1 || atSymbol > slash) {
-                return;
-            }
-
-            emailFrom = messageBody.substring(0, slash);
-
-            slash2 = messageBody.indexOf(" /", slash + 2);
-
-            if (slash2 == -1) {
-                pseudoSubject = null;
-                emailBody = messageBody.substring(slash + 2);
-            } else {
-                pseudoSubject = messageBody.substring(slash + 2, slash2);
-                emailBody = messageBody.substring(slash2 + 2);
-            }
-
-            isEmail = true;
-        } catch (Exception ex) {
-            Log.w(LOG_TAG,
-                    "extractEmailAddressFromMessageBody: exception slash="
-                    + slash + ", atSymbol=" + atSymbol + ", slash2="
-                    + slash2, ex);
-        }
+         String[] parts = messageBody.split("( /)|( )", 3);
+         if (parts.length < 2 || parts[0].indexOf('@') == -1) return;
+         emailFrom = parts[0];
+         if (parts.length == 3) {
+             pseudoSubject = parts[1];
+             emailBody = parts[2];
+         } else {
+             pseudoSubject = null;
+             emailBody = parts[1];
+         }
+         isEmail = true;
     }
 
 }
diff --git a/telephony/java/com/android/internal/telephony/TelephonyIntents.java b/telephony/java/com/android/internal/telephony/TelephonyIntents.java
index 02e9800..2216ec4 100644
--- a/telephony/java/com/android/internal/telephony/TelephonyIntents.java
+++ b/telephony/java/com/android/internal/telephony/TelephonyIntents.java
@@ -220,28 +220,4 @@
      */
     public static final String ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS
             = "android.intent.action.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS";
-
-     /**
-     * Broadcast Action: The MDN changed during the CDMA OTA Process
-     * The intent will have the following extra values:</p>
-     * <ul>
-     *   <li><em>mdn</em> - An Integer of the updated MDN number.</li>
-     * </ul>
-     * 
-     * <p class="note">This is a protected intent that can only be sent
-     * by the system.
-     *
-     * <p class="note">
-     */
-    // TODO(Moto): Generally broadcast intents are for use to allow entities which
-    // may not know about each other to "communicate". This seems quite specific
-    // and maybe using the registrant style would be better.
-
-    // Moto: Since this is used for apps not in the same process of phone, can the
-    // registrant style be used? (Ling Li says: Maybe the "app" can request rather
-    // than save the MDN each time and this intent would not be necessary?)
-    // Moto response: Moto internal discussion is on-going.
-    public static final String ACTION_CDMA_OTA_MDN_CHANGED
-            = "android.intent.action.ACTION_MDN_STATE_CHANGED";
-
 }
diff --git a/telephony/java/com/android/internal/telephony/TelephonyProperties.java b/telephony/java/com/android/internal/telephony/TelephonyProperties.java
index 5ec4020..8a1e928 100644
--- a/telephony/java/com/android/internal/telephony/TelephonyProperties.java
+++ b/telephony/java/com/android/internal/telephony/TelephonyProperties.java
@@ -109,4 +109,10 @@
 
     /** The international dialing prefix conversion string */
     static final String PROPERTY_IDP_STRING = "ro.cdma.idpstring";
+
+    /**
+     * Defines the schema for the carrier specified OTASP number
+     */
+    static final String PROPERTY_OTASP_NUM_SCHEMA = "ro.cdma.otaspnumschema";
+
 }
diff --git a/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java b/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java
index 23eedfe..aec7aee 100755
--- a/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java
@@ -42,6 +42,7 @@
 import android.text.TextUtils;
 import android.util.Log;
 
+import com.android.internal.telephony.Call;
 import com.android.internal.telephony.CallStateException;
 import com.android.internal.telephony.CommandException;
 import com.android.internal.telephony.CommandsInterface;
@@ -73,15 +74,19 @@
 import java.util.List;
 import java.util.Timer;
 import java.util.TimerTask;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
 /**
  * {@hide}
  */
 public class CDMAPhone extends PhoneBase {
     static final String LOG_TAG = "CDMA";
-    private static final boolean LOCAL_DEBUG = true;
+    private static final boolean DBG = true;
 
     // Default Emergency Callback Mode exit timer
-    private static final int DEFAULT_ECM_EXIT_TIMER_VALUE = 30000;
+    private static final int DEFAULT_ECM_EXIT_TIMER_VALUE = 300000;
     static final String VM_COUNT_CDMA = "vm_count_key_cdma";
     private static final String VM_NUMBER_CDMA = "vm_number_key_cdma";
     private String mVmNumber = null;
@@ -113,6 +118,8 @@
     private Registrant mECMExitRespRegistrant;
     private String mEsn;
     private String mMeid;
+    // string to define how the carrier specifies its own ota sp number
+    private String mCarrierOtaSpNumSchema;
 
     // A runnable which is used to automatically exit from ECM after a period of time.
     private Runnable mExitEcmRunnable = new Runnable() {
@@ -168,6 +175,10 @@
         String inEcm=SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE, "false");
         mIsPhoneInECMState = inEcm.equals("true");
 
+        // get the string that specifies the carrier OTA Sp number
+        mCarrierOtaSpNumSchema = SystemProperties.get(
+                TelephonyProperties.PROPERTY_OTASP_NUM_SCHEMA,"");
+
         // Sets operator alpha property by retrieving from build-time system property
         String operatorAlpha = SystemProperties.get("ro.cdma.home.operator.alpha");
         setSystemProperty(PROPERTY_ICC_OPERATOR_ALPHA, operatorAlpha);
@@ -233,7 +244,7 @@
     }
 
     protected void finalize() {
-        if(LOCAL_DEBUG) Log.d(LOG_TAG, "CDMAPhone finalized");
+        if(DBG) Log.d(LOG_TAG, "CDMAPhone finalized");
     }
 
 
@@ -423,10 +434,10 @@
     }
 
     public String getCdmaPrlVersion(){
-        return mRuimRecords.getPrlVersion();
+        return mSST.getPrlVersion();
     }
 
-    public String getCdmaMIN() {
+    public String getCdmaMin() {
         return mSST.getCdmaMin();
     }
 
@@ -497,6 +508,10 @@
         return false;
     }
 
+    public boolean isDataConnectivityEnabled() {
+        return mDataConnection.getDataEnabled();
+    }
+
     public boolean isDataConnectivityPossible() {
         boolean noData = mDataConnection.getDataEnabled() &&
                 getDataConnectionState() == DataState.DISCONNECTED;
@@ -808,19 +823,19 @@
     }
 
    /**
-     * Notify any interested party of a Phone state change.
+     * Notify any interested party of a Phone state change  {@link Phone.State}
      */
     /*package*/ void notifyPhoneStateChanged() {
         mNotifier.notifyPhoneState(this);
     }
 
     /**
-     * Notifies registrants (ie, activities in the Phone app) about
-     * changes to call state (including Phone and Connection changes).
+     * Notify registrants of a change in the call state. This notifies changes in {@link Call.State}
+     * Use this when changes in the precise call state are needed, else use notifyPhoneStateChanged.
      */
-    /*package*/ void notifyCallStateChanged() {
+    /*package*/ void notifyPreciseCallStateChanged() {
         /* we'd love it if this was package-scoped*/
-        super.notifyCallStateChangedP();
+        super.notifyPreciseCallStateChangedP();
     }
 
      void notifyServiceStateChanged(ServiceState ss) {
@@ -959,7 +974,7 @@
                         break;
                     }
 
-                    if (LOCAL_DEBUG) Log.d(LOG_TAG, "Baseband version: " + ar.result);
+                    if (DBG) Log.d(LOG_TAG, "Baseband version: " + ar.result);
                     setSystemProperty(TelephonyProperties.PROPERTY_BASEBAND_VERSION, (String)ar.result);
                 }
                 break;
@@ -1153,10 +1168,10 @@
         mSMS.setCellBroadcastConfig(configValuesArray, response);
     }
 
-    public static final String IS683A_FEATURE_CODE = "*228" ;
-    public static final int IS683A_FEATURE_CODE_NUM_DIGITS = 4 ;
-    public static final int IS683A_SYS_SEL_CODE_NUM_DIGITS = 2 ;
-    public static final int IS683A_SYS_SEL_CODE_OFFSET = 4;
+    private static final String IS683A_FEATURE_CODE = "*228";
+    private static final int IS683A_FEATURE_CODE_NUM_DIGITS = 4;
+    private static final int IS683A_SYS_SEL_CODE_NUM_DIGITS = 2;
+    private static final int IS683A_SYS_SEL_CODE_OFFSET = 4;
 
     private static final int IS683_CONST_800MHZ_A_BAND = 0;
     private static final int IS683_CONST_800MHZ_B_BAND = 1;
@@ -1166,6 +1181,7 @@
     private static final int IS683_CONST_1900MHZ_D_BLOCK = 5;
     private static final int IS683_CONST_1900MHZ_E_BLOCK = 6;
     private static final int IS683_CONST_1900MHZ_F_BLOCK = 7;
+    private static final int INVALID_SYSTEM_SELECTION_CODE = -1;
 
     private boolean isIs683OtaSpDialStr(String dialStr) {
         int sysSelCodeInt;
@@ -1176,39 +1192,147 @@
             if (dialStr.equals(IS683A_FEATURE_CODE)) {
                 isOtaspDialString = true;
             }
-        } else if ((dialStr.regionMatches(0, IS683A_FEATURE_CODE, 0,
-                                          IS683A_FEATURE_CODE_NUM_DIGITS) == true)
-                    && (dialStrLen >=
-                        (IS683A_FEATURE_CODE_NUM_DIGITS + IS683A_SYS_SEL_CODE_NUM_DIGITS))) {
-            StringBuilder sb = new StringBuilder(dialStr);
-            // Separate the System Selection Code into its own string
-            char[] sysSel = new char[2];
-            sb.delete(0, IS683A_SYS_SEL_CODE_OFFSET);
-            sb.getChars(0, IS683A_SYS_SEL_CODE_NUM_DIGITS, sysSel, 0);
-
-            if ((PhoneNumberUtils.isISODigit(sysSel[0]))
-                    && (PhoneNumberUtils.isISODigit(sysSel[1]))) {
-                String sysSelCode = new String(sysSel);
-                sysSelCodeInt = Integer.parseInt((String)sysSelCode);
-                switch (sysSelCodeInt) {
-                    case IS683_CONST_800MHZ_A_BAND:
-                    case IS683_CONST_800MHZ_B_BAND:
-                    case IS683_CONST_1900MHZ_A_BLOCK:
-                    case IS683_CONST_1900MHZ_B_BLOCK:
-                    case IS683_CONST_1900MHZ_C_BLOCK:
-                    case IS683_CONST_1900MHZ_D_BLOCK:
-                    case IS683_CONST_1900MHZ_E_BLOCK:
-                    case IS683_CONST_1900MHZ_F_BLOCK:
-                        isOtaspDialString = true;
-                        break;
-
-                    default:
-                        break;
-                }
+        } else {
+            sysSelCodeInt = extractSelCodeFromOtaSpNum(dialStr);
+            switch (sysSelCodeInt) {
+                case IS683_CONST_800MHZ_A_BAND:
+                case IS683_CONST_800MHZ_B_BAND:
+                case IS683_CONST_1900MHZ_A_BLOCK:
+                case IS683_CONST_1900MHZ_B_BLOCK:
+                case IS683_CONST_1900MHZ_C_BLOCK:
+                case IS683_CONST_1900MHZ_D_BLOCK:
+                case IS683_CONST_1900MHZ_E_BLOCK:
+                case IS683_CONST_1900MHZ_F_BLOCK:
+                    isOtaspDialString = true;
+                    break;
+                default:
+                    break;
             }
         }
         return isOtaspDialString;
     }
+    /**
+     * This function extracts the system selection code from the dial string.
+     */
+    private int extractSelCodeFromOtaSpNum(String dialStr) {
+        int dialStrLen = dialStr.length();
+        int sysSelCodeInt = INVALID_SYSTEM_SELECTION_CODE;
+
+        if ((dialStr.regionMatches(0, IS683A_FEATURE_CODE,
+                                   0, IS683A_FEATURE_CODE_NUM_DIGITS)) &&
+            (dialStrLen >= (IS683A_FEATURE_CODE_NUM_DIGITS +
+                            IS683A_SYS_SEL_CODE_NUM_DIGITS))) {
+                // Since we checked the condition above, the system selection code
+                // extracted from dialStr will not cause any exception
+                sysSelCodeInt = Integer.parseInt (
+                                dialStr.substring (IS683A_FEATURE_CODE_NUM_DIGITS,
+                                IS683A_FEATURE_CODE_NUM_DIGITS + IS683A_SYS_SEL_CODE_NUM_DIGITS));
+        }
+        if (DBG) Log.d(LOG_TAG, "extractSelCodeFromOtaSpNum " + sysSelCodeInt);
+        return sysSelCodeInt;
+    }
+
+    /**
+     * This function checks if the system selection code extracted from
+     * the dial string "sysSelCodeInt' is the system selection code specified
+     * in the carrier ota sp number schema "sch".
+     */
+    private boolean
+    checkOtaSpNumBasedOnSysSelCode (int sysSelCodeInt, String sch[]) {
+        boolean isOtaSpNum = false;
+        try {
+            // Get how many number of system selection code ranges
+            int selRc = Integer.parseInt((String)sch[1]);
+            for (int i = 0; i < selRc; i++) {
+                if (!TextUtils.isEmpty(sch[i+2]) && !TextUtils.isEmpty(sch[i+3])) {
+                    int selMin = Integer.parseInt((String)sch[i+2]);
+                    int selMax = Integer.parseInt((String)sch[i+3]);
+                    // Check if the selection code extracted from the dial string falls
+                    // within any of the range pairs specified in the schema.
+                    if ((sysSelCodeInt >= selMin) && (sysSelCodeInt <= selMax)) {
+                        isOtaSpNum = true;
+                        break;
+                    }
+                }
+            }
+        } catch (NumberFormatException ex) {
+            // If the carrier ota sp number schema is not correct, we still allow dial
+            // and only log the error:
+            Log.e(LOG_TAG, "checkOtaSpNumBasedOnSysSelCode, error", ex);
+        }
+        return isOtaSpNum;
+    }
+
+    // Define the pattern/format for carrier specified OTASP number schema.
+    // It separates by comma and/or whitespace.
+    private static Pattern pOtaSpNumSchema = Pattern.compile("[,\\s]+");
+
+    /**
+     * The following function checks if a dial string is a carrier specified
+     * OTASP number or not by checking against the OTASP number schema stored
+     * in PROPERTY_OTASP_NUM_SCHEMA.
+     *
+     * Currently, there are 2 schemas for carriers to specify the OTASP number:
+     * 1) Use system selection code:
+     *    The schema is:
+     *    SELC,the # of code pairs,min1,max1,min2,max2,...
+     *    e.g "SELC,3,10,20,30,40,60,70" indicates that there are 3 pairs of
+     *    selection codes, and they are {10,20}, {30,40} and {60,70} respectively.
+     *
+     * 2) Use feature code:
+     *    The schema is:
+     *    "FC,length of feature code,feature code".
+     *     e.g "FC,2,*2" indicates that the length of the feature code is 2,
+     *     and the code itself is "*2".
+     */
+    private boolean isCarrierOtaSpNum(String dialStr) {
+        boolean isOtaSpNum = false;
+        int sysSelCodeInt = extractSelCodeFromOtaSpNum(dialStr);
+        if (sysSelCodeInt == INVALID_SYSTEM_SELECTION_CODE) {
+            return isOtaSpNum;
+        }
+        // mCarrierOtaSpNumSchema is retrieved from PROPERTY_OTASP_NUM_SCHEMA:
+        if (!TextUtils.isEmpty(mCarrierOtaSpNumSchema)) {
+            Matcher m = pOtaSpNumSchema.matcher(mCarrierOtaSpNumSchema);
+            if (DBG) {
+                Log.d(LOG_TAG, "isCarrierOtaSpNum,schema" + mCarrierOtaSpNumSchema);
+            }
+
+            if (m.find()) {
+                String sch[] = pOtaSpNumSchema.split(mCarrierOtaSpNumSchema);
+                // If carrier uses system selection code mechanism
+                if (!TextUtils.isEmpty(sch[0]) && sch[0].equals("SELC")) {
+                    if (sysSelCodeInt!=INVALID_SYSTEM_SELECTION_CODE) {
+                        isOtaSpNum=checkOtaSpNumBasedOnSysSelCode(sysSelCodeInt,sch);
+                    } else {
+                        if (DBG) {
+                            Log.d(LOG_TAG, "isCarrierOtaSpNum,sysSelCodeInt is invalid");
+                        }
+                    }
+                } else if (!TextUtils.isEmpty(sch[0]) && sch[0].equals("FC")) {
+                    int fcLen =  Integer.parseInt((String)sch[1]);
+                    String fc = (String)sch[2];
+                    if (dialStr.regionMatches(0,fc,0,fcLen)) {
+                        isOtaSpNum = true;
+                    } else {
+                        if (DBG) Log.d(LOG_TAG, "isCarrierOtaSpNum,not otasp number");
+                    }
+                } else {
+                    if (DBG) {
+                        Log.d(LOG_TAG, "isCarrierOtaSpNum,ota schema not supported" + sch[0]);
+                    }
+                }
+            } else {
+                if (DBG) {
+                    Log.d(LOG_TAG, "isCarrierOtaSpNum,ota schema pattern not right" +
+                          mCarrierOtaSpNumSchema);
+                }
+            }
+        } else {
+            if (DBG) Log.d(LOG_TAG, "isCarrierOtaSpNum,ota schema pattern empty");
+        }
+        return isOtaSpNum;
+    }
 
      /**
       * isOTASPNumber: checks a given number against the IS-683A OTASP dial string and carrier
@@ -1220,12 +1344,13 @@
     @Override
      public  boolean isOtaSpNumber(String dialStr){
          boolean isOtaSpNum = false;
-         if(dialStr != null){
-             isOtaSpNum=isIs683OtaSpDialStr(dialStr);
+         if (dialStr != null) {
+             isOtaSpNum = isIs683OtaSpDialStr(dialStr);
              if(isOtaSpNum == false){
-             //TO DO:Add carrier specific OTASP number detection here.
+                 isOtaSpNum = isCarrierOtaSpNum(dialStr);
              }
          }
+         if (DBG) Log.d(LOG_TAG, "isOtaSpNumber " + isOtaSpNum);
          return isOtaSpNum;
      }
 
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaCallTracker.java b/telephony/java/com/android/internal/telephony/cdma/CdmaCallTracker.java
index ed2ea90..cc456c5 100644
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaCallTracker.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaCallTracker.java
@@ -222,7 +222,7 @@
         }
 
         updatePhoneState();
-        phone.notifyCallStateChanged();
+        phone.notifyPreciseCallStateChanged();
 
         return pendingMO;
     }
@@ -262,6 +262,7 @@
             // triggered by updateParent.
             cwConn.updateParent(ringingCall, foregroundCall);
             cwConn.onConnectedInOrOut();
+            updatePhoneState();
             switchWaitingOrHoldingAndActive();
         } else {
             throw new CallStateException("phone not ringing");
@@ -305,7 +306,7 @@
         internalClearDisconnected();
 
         updatePhoneState();
-        phone.notifyCallStateChanged();
+        phone.notifyPreciseCallStateChanged();
     }
 
     boolean
@@ -531,17 +532,6 @@
                 // Dropped connections are removed from the CallTracker
                 // list but kept in the Call list
                 connections[i] = null;
-            } else if (conn != null && dc != null && !conn.compareTo(dc)) {
-                // Connection in CLCC response does not match what
-                // we were tracking. Assume dropped call and new call
-
-                droppedDuringPoll.add(conn);
-                connections[i] = new CdmaConnection (phone.getContext(), dc, this, i);
-
-                if (connections[i].getCall() == ringingCall) {
-                    newRinging = connections[i];
-                } // else something strange happened
-                hasNonHangupStateChanged = true;
             } else if (conn != null && dc != null) { /* implicit conn.compareTo(dc) */
                 boolean changed;
                 changed = conn.update(dc);
@@ -644,7 +634,7 @@
         }
 
         if (hasNonHangupStateChanged || newRinging != null) {
-            phone.notifyCallStateChanged();
+            phone.notifyPreciseCallStateChanged();
         }
 
         //dumpState();
@@ -678,7 +668,8 @@
             // the hangup reason is user ignoring or timing out. So conn.onDisconnect()
             // is not called here. Instead, conn.onLocalDisconnect() is called.
             conn.onLocalDisconnect();
-            phone.notifyCallStateChanged();
+            phone.notifyPreciseCallStateChanged();
+            updatePhoneState();
             return;
         } else {
             try {
@@ -821,7 +812,7 @@
         // the status of the call is after a call waiting is answered,
         // 3 way call merged or a switch between calls.
         foregroundCall.setGeneric(true);
-        phone.notifyCallStateChanged();
+        phone.notifyPreciseCallStateChanged();
     }
 
     private Phone.SuppService getFailedService(int what) {
@@ -865,6 +856,7 @@
         // Create a new CdmaConnection which attaches itself to ringingCall.
         ringingCall.setGeneric(false);
         new CdmaConnection(phone.getContext(), cw, this, ringingCall);
+        updatePhoneState();
 
         // Finally notify application
         notifyCallWaitingInfo(cw);
@@ -926,7 +918,7 @@
 
                 updatePhoneState();
 
-                phone.notifyCallStateChanged();
+                phone.notifyPreciseCallStateChanged();
                 droppedDuringPoll.clear();
             break;
 
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaConnection.java b/telephony/java/com/android/internal/telephony/cdma/CdmaConnection.java
index 025382d..69ef0e3 100644
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaConnection.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaConnection.java
@@ -161,8 +161,8 @@
 
         isIncoming = false;
         cnapName = null;
-        cnapNamePresentation = 0;
-        numberPresentation = 0;
+        cnapNamePresentation = Connection.PRESENTATION_ALLOWED;
+        numberPresentation = Connection.PRESENTATION_ALLOWED;
         createTime = System.currentTimeMillis();
 
         if (parent != null) {
@@ -435,8 +435,10 @@
                 } else if (phone.mCM.getRadioState() != CommandsInterface.RadioState.NV_READY
                         && phone.getIccCard().getState() != RuimCard.State.READY) {
                     return DisconnectCause.ICC_ERROR;
-                } else {
+                } else if (causeCode==CallFailCause.NORMAL_CLEARING) {
                     return DisconnectCause.NORMAL;
+                } else {
+                    return DisconnectCause.ERROR_UNSPECIFIED;
                 }
         }
     }
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java b/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java
index ecdc8f6..c4db609 100644
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java
@@ -25,12 +25,14 @@
 import android.database.SQLException;
 import android.os.AsyncResult;
 import android.os.Message;
+import android.os.SystemProperties;
 import android.provider.Telephony;
 import android.provider.Telephony.Sms.Intents;
 import android.preference.PreferenceManager;
 import android.util.Config;
 import android.util.Log;
 
+import com.android.internal.telephony.TelephonyProperties;
 import com.android.internal.telephony.CommandsInterface;
 import com.android.internal.telephony.SmsHeader;
 import com.android.internal.telephony.SmsMessageBase;
@@ -75,6 +77,11 @@
             return Intents.RESULT_SMS_GENERIC_ERROR;
         }
 
+        String inEcm=SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE, "false");
+        if (inEcm.equals("true")) {
+            return Intents.RESULT_SMS_GENERIC_ERROR;
+        }
+
         // Decode BD stream and set sms variables.
         SmsMessage sms = (SmsMessage) smsb;
         sms.parseSms();
@@ -343,6 +350,12 @@
     /** {@inheritDoc} */
     protected void acknowledgeLastIncomingSms(boolean success, int result, Message response){
         // FIXME unit test leaves cm == null. this should change
+
+        String inEcm=SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE, "false");
+        if (inEcm.equals("true")) {
+            return;
+        }
+
         if (mCm != null) {
             mCm.acknowledgeLastIncomingCdmaSms(success, resultToCause(result), response);
         }
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java b/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java
index 23a0520..d5da666 100644
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java
@@ -124,6 +124,7 @@
     private int mHomeSystemId;
     private int mHomeNetworkId;
     private String mMin;
+    private String mPrlVersion;
 
     private boolean isEriTextLoaded = false;
     private boolean isSubscriptionFromRuim = false;
@@ -175,6 +176,7 @@
 
         cm.registerForNVReady(this, EVENT_NV_READY, null);
         phone.registerForEriFileLoaded(this, EVENT_ERI_FILE_LOADED, null);
+        cm.registerForCdmaOtaProvision(this,EVENT_OTA_PROVISION_STATUS_CHANGE, null);
 
         // system setting property AIRPLANE_MODE_ON is set in Settings.
         int airplaneMode = Settings.System.getInt(
@@ -198,6 +200,7 @@
         cm.unregisterForNetworkStateChanged(this);
         cm.unregisterForRUIMReady(this);
         cm.unregisterForNVReady(this);
+        cm.unregisterForCdmaOtaProvision(this);
         phone.unregisterForEriFileLoaded(this);
         phone.mRuimRecords.unregisterForRecordsLoaded(this);
         cm.unSetOnSignalStrengthUpdate(this);
@@ -290,6 +293,10 @@
                         EVENT_RUIM_RECORDS_LOADED, null);
                 mNeedToRegForRuimLoaded = false;
             }
+
+            cm.getCDMASubscription(obtainMessage(EVENT_POLL_STATE_CDMA_SUBSCRIPTION));
+            if (DBG) log("Receive EVENT_RUIM_READY and Send Request getCDMASubscription.");
+
             // restore the previous network selection.
             pollState();
 
@@ -299,6 +306,10 @@
 
         case EVENT_NV_READY:
             isSubscriptionFromRuim = false;
+            // For Non-RUIM phones, the subscription information is stored in
+            // Non Volatile. Here when Non-Volatile is ready, we can poll the CDMA
+            // subscription info.
+            cm.getCDMASubscription( obtainMessage(EVENT_POLL_STATE_CDMA_SUBSCRIPTION));
             pollState();
             // Signal strength polling stops when radio is off
             queueNextSignalStrengthPoll();
@@ -376,11 +387,36 @@
 
         case EVENT_POLL_STATE_REGISTRATION_CDMA:
         case EVENT_POLL_STATE_OPERATOR_CDMA:
-        case EVENT_POLL_STATE_CDMA_SUBSCRIPTION:
             ar = (AsyncResult) msg.obj;
             handlePollStateResult(msg.what, ar);
             break;
 
+        case EVENT_POLL_STATE_CDMA_SUBSCRIPTION: // Handle RIL_CDMA_SUBSCRIPTION
+            ar = (AsyncResult) msg.obj;
+
+            if (ar.exception == null) {
+                String cdmaSubscription[] = (String[])ar.result;
+                if (cdmaSubscription != null && cdmaSubscription.length >= 5) {
+                    mMdn = cdmaSubscription[0];
+                    // TODO: Only grabbing the first SID/NID for now.
+                    if (cdmaSubscription[1] != null) {
+                        String[] sid = cdmaSubscription[1].split(",");
+                        mHomeSystemId = sid.length > 0 ? Integer.parseInt(sid[0], 16) : 0;
+                    }
+                    if (cdmaSubscription[2] != null) {
+                        String[] nid = cdmaSubscription[2].split(",");
+                        mHomeNetworkId = nid.length > 0 ? Integer.parseInt(nid[0], 16) : 0;
+                    }
+                    mMin = cdmaSubscription[3];
+                    mPrlVersion = cdmaSubscription[4];
+                    Log.d(LOG_TAG,"GET_CDMA_SUBSCRIPTION MDN=" + mMdn);
+                } else {
+                    Log.w(LOG_TAG,"error parsing cdmaSubscription params num="
+                            + cdmaSubscription.length);
+                }
+            }
+            break;
+
         case EVENT_POLL_SIGNAL_STRENGTH:
             // Just poll signal strength...not part of pollState()
 
@@ -427,6 +463,19 @@
             pollState();
             break;
 
+        case EVENT_OTA_PROVISION_STATUS_CHANGE:
+            ar = (AsyncResult)msg.obj;
+            if (ar.exception == null) {
+                ints = (int[]) ar.result;
+                int otaStatus = ints[0];
+                if (otaStatus == phone.CDMA_OTA_PROVISION_STATUS_COMMITTED
+                    || otaStatus == phone.CDMA_OTA_PROVISION_STATUS_OTAPA_STOPPED) {
+                    Log.d(LOG_TAG, "Received OTA_PROGRAMMING Complete,Reload MDN ");
+                    cm.getCDMASubscription( obtainMessage(EVENT_POLL_STATE_CDMA_SUBSCRIPTION));
+                }
+            }
+            break;
+
         default:
             Log.e(LOG_TAG, "Unhandled message with number: " + msg.what);
         break;
@@ -589,7 +638,10 @@
                 }
 
                 mRegistrationState = registrationState;
-                mCdmaRoaming = regCodeIsRoaming(registrationState);
+                // mCdmaRoaming is true when registration state is roaming and TSB58 roaming
+                // indicator is not in the carrier-specified list of ERIs for home system
+                mCdmaRoaming =
+                        regCodeIsRoaming(registrationState) && !isRoamIndForHomeSystem(states[10]);
                 newSS.setState (regCodeToServiceState(registrationState));
 
                 this.newCdmaDataConnectionState = radioTechnologyToDataServiceState(radioTechnology);
@@ -636,27 +688,6 @@
                 }
                 break;
 
-            case EVENT_POLL_STATE_CDMA_SUBSCRIPTION: // Handle RIL_CDMA_SUBSCRIPTION
-                String cdmaSubscription[] = (String[])ar.result;
-
-                if (cdmaSubscription != null && cdmaSubscription.length >= 4) {
-                    mMdn = cdmaSubscription[0];
-                    // TODO: Only grabbing the first SID/NID for now.
-                    if (cdmaSubscription[1] != null) {
-                        String[] sid = cdmaSubscription[1].split(",");
-                        mHomeSystemId = sid.length > 0 ? Integer.parseInt(sid[0]) : 0;
-                    }
-                    if (cdmaSubscription[2] != null) {
-                        String[] nid = cdmaSubscription[2].split(",");
-                        mHomeNetworkId = nid.length > 0 ? Integer.parseInt(nid[0]) : 0;
-                    }
-                    mMin = cdmaSubscription[3];
-
-                } else {
-                    Log.w(LOG_TAG, "error parsing cdmaSubscription");
-                }
-                break;
-
             default:
                 Log.e(LOG_TAG, "RIL response handle in wrong phone!"
                     + " Expected CDMA RIL request and get GSM RIL request.");
@@ -773,11 +804,6 @@
             // are allowed to arrive out-of-order
 
             pollingContext[0]++;
-            // RIL_REQUEST_CDMA_SUBSCRIPTION is necessary for CDMA
-            cm.getCDMASubscription(
-                    obtainMessage(EVENT_POLL_STATE_CDMA_SUBSCRIPTION, pollingContext));
-
-            pollingContext[0]++;
             // RIL_REQUEST_OPERATOR is necessary for CDMA
             cm.getOperator(
                     obtainMessage(EVENT_POLL_STATE_OPERATOR_CDMA, pollingContext));
@@ -1152,6 +1178,33 @@
     }
 
     /**
+     * Determine whether a roaming indicator is in the carrier-specified list of ERIs for
+     * home system
+     *
+     * @param roamInd roaming indicator in String
+     * @return true if the roamInd is in the carrier-specified list of ERIs for home network
+     */
+    private boolean isRoamIndForHomeSystem(String roamInd) {
+        // retrieve the carrier-specified list of ERIs for home system
+        String homeRoamIndcators = SystemProperties.get("ro.cdma.homesystem");
+
+        if (!TextUtils.isEmpty(homeRoamIndcators)) {
+            // searches through the comma-separated list for a match,
+            // return true if one is found.
+            for (String homeRoamInd : homeRoamIndcators.split(",")) {
+                if (homeRoamInd.equals(roamInd)) {
+                    return true;
+                }
+            }
+            // no matches found against the list!
+            return false;
+        }
+
+        // no system property found for the roaming indicators for home system
+        return false;
+    }
+
+    /**
      * Set roaming state when cdmaRoaming is true and ons is different from spn
      * @param cdmaRoaming TS 27.007 7.2 CREG registered roaming
      * @param s ServiceState hold current ons
@@ -1420,6 +1473,11 @@
          return mMin;
     }
 
+    /** Returns null if NV is not yet ready */
+    public String getPrlVersion() {
+        return mPrlVersion;
+    }
+
     /**
      * Returns IMSI as MCC + MNC + MIN
      */
diff --git a/telephony/java/com/android/internal/telephony/cdma/RuimCard.java b/telephony/java/com/android/internal/telephony/cdma/RuimCard.java
index 9d9f479..734badd 100644
--- a/telephony/java/com/android/internal/telephony/cdma/RuimCard.java
+++ b/telephony/java/com/android/internal/telephony/cdma/RuimCard.java
@@ -16,507 +16,34 @@
 
 package com.android.internal.telephony.cdma;
 
-import android.os.AsyncResult;
-import android.os.Handler;
-import android.os.Message;
-import android.os.Registrant;
-import android.os.RegistrantList;
-import android.os.RemoteException;
-import android.util.Log;
-
-import com.android.internal.telephony.CommandsInterface;
 import com.android.internal.telephony.IccCard;
-import com.android.internal.telephony.Phone;
-import com.android.internal.telephony.PhoneProxy;
-import com.android.internal.telephony.TelephonyIntents;
-import com.android.internal.telephony.TelephonyProperties;
-
-import android.app.ActivityManagerNative;
-import android.content.Intent;
-import android.content.res.Configuration;
-
-import static android.Manifest.permission.READ_PHONE_STATE;
 
 /**
  * Note: this class shares common code with SimCard, consider a base class to minimize code
  * duplication.
  * {@hide}
  */
-public final class RuimCard extends Handler implements IccCard {
-    static final String LOG_TAG="CDMA";
-
-    //***** Instance Variables
-    private static final boolean DBG = true;
-
-    private CDMAPhone phone;
-
-    private CommandsInterface.IccStatus status = null;
-    private boolean mDesiredPinLocked;
-    private boolean mDesiredFdnEnabled;
-    private boolean mRuimPinLocked = true; // default to locked
-    private boolean mRuimFdnEnabled = false; // Default to disabled.
-                                            // Will be updated when RUIM_READY.
-//    //***** Constants
-
-//    // FIXME I hope this doesn't conflict with the Dialer's notifications
-//    Nobody is using this at the moment
-//    static final int NOTIFICATION_ID_ICC_STATUS = 33456;
-
-    //***** Event Constants
-
-    static final int EVENT_RUIM_LOCKED_OR_ABSENT = 1;
-    static final int EVENT_GET_RUIM_STATUS_DONE = 2;
-    static final int EVENT_RADIO_OFF_OR_NOT_AVAILABLE = 3;
-    static final int EVENT_PINPUK_DONE = 4;
-    static final int EVENT_REPOLL_STATUS_DONE = 5;
-    static final int EVENT_RUIM_READY = 6;
-    static final int EVENT_QUERY_FACILITY_LOCK_DONE = 7;
-    static final int EVENT_CHANGE_FACILITY_LOCK_DONE = 8;
-    static final int EVENT_CHANGE_RUIM_PASSWORD_DONE = 9;
-    static final int EVENT_QUERY_FACILITY_FDN_DONE = 10;
-    static final int EVENT_CHANGE_FACILITY_FDN_DONE = 11;
-
-
-    //***** Constructor
+public final class RuimCard extends IccCard {
 
     RuimCard(CDMAPhone phone) {
-        this.phone = phone;
-
-        phone.mCM.registerForRUIMLockedOrAbsent(
-                        this, EVENT_RUIM_LOCKED_OR_ABSENT, null);
-
-        phone.mCM.registerForOffOrNotAvailable(
-                        this, EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
-
-        phone.mCM.registerForRUIMReady(
-                        this, EVENT_RUIM_READY, null);
-
+        super(phone, "CDMA", true);
+        mPhone.mCM.registerForRUIMLockedOrAbsent(mHandler, EVENT_ICC_LOCKED_OR_ABSENT, null);
+        mPhone.mCM.registerForOffOrNotAvailable(mHandler, EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
+        mPhone.mCM.registerForRUIMReady(mHandler, EVENT_ICC_READY, null);
         updateStateProperty();
     }
 
-    //***** RuimCard implementation
-
-    public State
-    getState() {
-        if (status == null) {
-            switch(phone.mCM.getRadioState()) {
-                /* This switch block must not return anything in
-                 * State.isLocked() or State.ABSENT.
-                 * If it does, handleSimStatus() may break
-                 */
-                case RADIO_OFF:
-                case RADIO_UNAVAILABLE:
-                case RUIM_NOT_READY:
-                    return State.UNKNOWN;
-                case RUIM_LOCKED_OR_ABSENT:
-                    //this should be transient-only
-                    return State.UNKNOWN;
-                case RUIM_READY:
-                    return State.READY;
-                case NV_READY:
-                case NV_NOT_READY:
-                    return State.ABSENT;
-            }
-        } else {
-            switch (status) {
-                case ICC_ABSENT:            return State.ABSENT;
-                case ICC_NOT_READY:         return State.UNKNOWN;
-                case ICC_READY:             return State.READY;
-                case ICC_PIN:               return State.PIN_REQUIRED;
-                case ICC_PUK:               return State.PUK_REQUIRED;
-                case ICC_NETWORK_PERSONALIZATION: return State.NETWORK_LOCKED;
-            }
-        }
-
-        Log.e(LOG_TAG, "RuimCard.getState(): case should never be reached");
-        return State.UNKNOWN;
-    }
-
+    @Override
     public void dispose() {
         //Unregister for all events
-        phone.mCM.unregisterForRUIMLockedOrAbsent(this);
-        phone.mCM.unregisterForOffOrNotAvailable(this);
-        phone.mCM.unregisterForRUIMReady(this);
+        mPhone.mCM.unregisterForRUIMLockedOrAbsent(mHandler);
+        mPhone.mCM.unregisterForOffOrNotAvailable(mHandler);
+        mPhone.mCM.unregisterForRUIMReady(mHandler);
     }
 
-    protected void finalize() {
-        if(DBG) Log.d(LOG_TAG, "RuimCard finalized");
-    }
-
-    private RegistrantList absentRegistrants = new RegistrantList();
-    private RegistrantList pinLockedRegistrants = new RegistrantList();
-    private RegistrantList networkLockedRegistrants = new RegistrantList();
-
-
-    public void registerForAbsent(Handler h, int what, Object obj) {
-        Registrant r = new Registrant (h, what, obj);
-
-        absentRegistrants.add(r);
-
-        if (getState() == State.ABSENT) {
-            r.notifyRegistrant();
-        }
-    }
-
-    public void unregisterForAbsent(Handler h) {
-        absentRegistrants.remove(h);
-    }
-
-    public void registerForNetworkLocked(Handler h, int what, Object obj) {
-        Registrant r = new Registrant (h, what, obj);
-
-        networkLockedRegistrants.add(r);
-
-        if (getState() == State.NETWORK_LOCKED) {
-            r.notifyRegistrant();
-        }
-    }
-
-    public void unregisterForNetworkLocked(Handler h) {
-        networkLockedRegistrants.remove(h);
-    }
-
-    public void registerForLocked(Handler h, int what, Object obj) {
-        Registrant r = new Registrant (h, what, obj);
-
-        pinLockedRegistrants.add(r);
-
-        if (getState().isPinLocked()) {
-            r.notifyRegistrant();
-        }
-    }
-
-    public void unregisterForLocked(Handler h) {
-        pinLockedRegistrants.remove(h);
-    }
-
-    public void supplyPin (String pin, Message onComplete) {
-        phone.mCM.supplyIccPin(pin, obtainMessage(EVENT_PINPUK_DONE, onComplete));
-    }
-
-    public void supplyPuk (String puk, String newPin, Message onComplete) {
-        phone.mCM.supplyIccPuk(puk, newPin, obtainMessage(EVENT_PINPUK_DONE, onComplete));
-    }
-
-    public void supplyPin2 (String pin2, Message onComplete) {
-        phone.mCM.supplyIccPin2(pin2, obtainMessage(EVENT_PINPUK_DONE, onComplete));
-    }
-
-    public void supplyPuk2 (String puk2, String newPin2, Message onComplete) {
-        phone.mCM.supplyIccPuk2(puk2, newPin2, obtainMessage(EVENT_PINPUK_DONE, onComplete));
-    }
-
-    public void supplyNetworkDepersonalization (String pin, Message onComplete) {
-        if(DBG) log("Network Despersonalization: " + pin);
-        phone.mCM.supplyNetworkDepersonalization(pin,
-                obtainMessage(EVENT_PINPUK_DONE, onComplete));
-    }
-
-    public boolean getIccLockEnabled() {
-       return mRuimPinLocked;
-    }
-
-    public boolean getIccFdnEnabled() {
-       return mRuimFdnEnabled;
-    }
-
-    public void setIccLockEnabled (boolean enabled,
-            String password, Message onComplete) {
-        int serviceClassX;
-        serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE +
-                CommandsInterface.SERVICE_CLASS_DATA +
-                CommandsInterface.SERVICE_CLASS_FAX;
-
-        mDesiredPinLocked = enabled;
-
-        phone.mCM.setFacilityLock(CommandsInterface.CB_FACILITY_BA_SIM,
-                enabled, password, serviceClassX,
-                obtainMessage(EVENT_CHANGE_FACILITY_LOCK_DONE, onComplete));
-    }
-
-    public void setIccFdnEnabled (boolean enabled,
-            String password, Message onComplete) {
-        int serviceClassX;
-        serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE +
-                CommandsInterface.SERVICE_CLASS_DATA +
-                CommandsInterface.SERVICE_CLASS_FAX +
-                CommandsInterface.SERVICE_CLASS_SMS;
-
-        mDesiredFdnEnabled = enabled;
-
-        phone.mCM.setFacilityLock(CommandsInterface.CB_FACILITY_BA_FD,
-                enabled, password, serviceClassX,
-                obtainMessage(EVENT_CHANGE_FACILITY_FDN_DONE, onComplete));
-    }
-
-    public void changeIccLockPassword(String oldPassword, String newPassword,
-            Message onComplete) {
-        if(DBG) log("Change Pin1 old: " + oldPassword + " new: " + newPassword);
-        phone.mCM.changeIccPin(oldPassword, newPassword,
-                obtainMessage(EVENT_CHANGE_RUIM_PASSWORD_DONE, onComplete));
-    }
-
-    public void changeIccFdnPassword(String oldPassword, String newPassword,
-            Message onComplete) {
-        if(DBG) log("Change Pin2 old: " + oldPassword + " new: " + newPassword);
-        phone.mCM.changeIccPin2(oldPassword, newPassword,
-                obtainMessage(EVENT_CHANGE_RUIM_PASSWORD_DONE, onComplete));
-    }
-
-    public String getServiceProviderName() {
-        return phone.mRuimRecords.getServiceProviderName();
-    }
-
-    //***** Handler implementation
     @Override
-    public void handleMessage(Message msg){
-        AsyncResult ar;
-        int serviceClassX;
-
-        serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE +
-                        CommandsInterface.SERVICE_CLASS_DATA +
-                        CommandsInterface.SERVICE_CLASS_FAX;
-
-        switch (msg.what) {
-            case EVENT_RADIO_OFF_OR_NOT_AVAILABLE:
-                Log.d(LOG_TAG, "Event EVENT_RADIO_OFF_OR_NOT_AVAILABLE Received");
-                status = null;
-                updateStateProperty();
-                broadcastRuimStateChangedIntent(RuimCard.INTENT_VALUE_ICC_NOT_READY, null);
-                break;
-            case EVENT_RUIM_READY:
-                Log.d(LOG_TAG, "Event EVENT_RUIM_READY Received");
-                //TODO: put facility read in SIM_READY now, maybe in REG_NW
-                phone.mCM.getIccStatus(obtainMessage(EVENT_GET_RUIM_STATUS_DONE));
-                phone.mCM.queryFacilityLock (
-                        CommandsInterface.CB_FACILITY_BA_SIM, "", serviceClassX,
-                        obtainMessage(EVENT_QUERY_FACILITY_LOCK_DONE));
-                phone.mCM.queryFacilityLock (
-                        CommandsInterface.CB_FACILITY_BA_FD, "", serviceClassX,
-                        obtainMessage(EVENT_QUERY_FACILITY_FDN_DONE));
-                break;
-            case EVENT_RUIM_LOCKED_OR_ABSENT:
-                Log.d(LOG_TAG, "Event EVENT_RUIM_LOCKED_OR_ABSENT Received");
-                phone.mCM.getIccStatus(obtainMessage(EVENT_GET_RUIM_STATUS_DONE));
-                phone.mCM.queryFacilityLock (
-                        CommandsInterface.CB_FACILITY_BA_SIM, "", serviceClassX,
-                        obtainMessage(EVENT_QUERY_FACILITY_LOCK_DONE));
-                break;
-            case EVENT_GET_RUIM_STATUS_DONE:
-                Log.d(LOG_TAG, "Event EVENT_GET_RUIM_STATUS_DONE Received");
-                ar = (AsyncResult)msg.obj;
-
-                getRuimStatusDone(ar);
-                break;
-            case EVENT_PINPUK_DONE:
-                Log.d(LOG_TAG, "Event EVENT_PINPUK_DONE Received");
-                // a PIN/PUK/PIN2/PUK2/Network Personalization
-                // request has completed. ar.userObj is the response Message
-                // Repoll before returning
-                ar = (AsyncResult)msg.obj;
-                // TODO should abstract these exceptions
-                AsyncResult.forMessage(((Message)ar.userObj)).exception
-                                                    = ar.exception;
-                phone.mCM.getIccStatus(
-                    obtainMessage(EVENT_REPOLL_STATUS_DONE, ar.userObj));
-                break;
-            case EVENT_REPOLL_STATUS_DONE:
-                Log.d(LOG_TAG, "Event EVENT_REPOLL_STATUS_DONE Received");
-                // Finished repolling status after PIN operation
-                // ar.userObj is the response messaeg
-                // ar.userObj.obj is already an AsyncResult with an
-                // appropriate exception filled in if applicable
-
-                ar = (AsyncResult)msg.obj;
-                getRuimStatusDone(ar);
-                ((Message)ar.userObj).sendToTarget();
-                break;
-            case EVENT_QUERY_FACILITY_LOCK_DONE:
-                Log.d(LOG_TAG, "Event EVENT_QUERY_FACILITY_LOCK_DONE Received");
-                ar = (AsyncResult)msg.obj;
-                onQueryFacilityLock(ar);
-                break;
-            case EVENT_QUERY_FACILITY_FDN_DONE:
-                Log.d(LOG_TAG, "Event EVENT_QUERY_FACILITY_FDN_DONE Received");
-                ar = (AsyncResult)msg.obj;
-                onQueryFdnEnabled(ar);
-                break;
-            case EVENT_CHANGE_FACILITY_LOCK_DONE:
-                Log.d(LOG_TAG, "Event EVENT_CHANGE_FACILITY_LOCK_DONE Received");
-                ar = (AsyncResult)msg.obj;
-                if (ar.exception == null) {
-                    mRuimPinLocked = mDesiredPinLocked;
-                    if (DBG) log( "EVENT_CHANGE_FACILITY_LOCK_DONE: " +
-                            "mRuimPinLocked= " + mRuimPinLocked);
-                } else {
-                    Log.e(LOG_TAG, "Error change facility lock with exception "
-                        + ar.exception);
-                }
-                AsyncResult.forMessage(((Message)ar.userObj)).exception
-                                                    = ar.exception;
-                ((Message)ar.userObj).sendToTarget();
-                break;
-            case EVENT_CHANGE_FACILITY_FDN_DONE:
-                Log.d(LOG_TAG, "Event EVENT_CHANGE_FACILITY_FDN_DONE Received");
-                ar = (AsyncResult)msg.obj;
-
-                if (ar.exception == null) {
-                    mRuimFdnEnabled = mDesiredFdnEnabled;
-                    if (DBG) log("EVENT_CHANGE_FACILITY_FDN_DONE: " +
-                            "mRuimFdnEnabled=" + mRuimFdnEnabled);
-                } else {
-                    Log.e(LOG_TAG, "Error change facility fdn with exception "
-                            + ar.exception);
-                }
-                AsyncResult.forMessage(((Message)ar.userObj)).exception
-                                                    = ar.exception;
-                ((Message)ar.userObj).sendToTarget();
-                break;
-            case EVENT_CHANGE_RUIM_PASSWORD_DONE:
-                Log.d(LOG_TAG, "Event EVENT_CHANGE_RUIM_PASSWORD_DONE Received");
-                ar = (AsyncResult)msg.obj;
-                if(ar.exception != null) {
-                    Log.e(LOG_TAG, "Error in change sim password with exception"
-                        + ar.exception);
-                }
-                AsyncResult.forMessage(((Message)ar.userObj)).exception
-                                                    = ar.exception;
-                ((Message)ar.userObj).sendToTarget();
-                break;
-            default:
-                Log.e(LOG_TAG, "[CdmaRuimCard] Unknown Event " + msg.what);
-        }
+    public String getServiceProviderName () {
+        return ((CDMAPhone)mPhone).mRuimRecords.getServiceProviderName();
     }
-
-    //***** Private methods
-
-    /**
-     * Interpret EVENT_QUERY_FACILITY_LOCK_DONE
-     * @param ar is asyncResult of Query_Facility_Locked
-     */
-    private void onQueryFacilityLock(AsyncResult ar) {
-        if(ar.exception != null) {
-            if (DBG) log("Error in querying facility lock:" + ar.exception);
-            return;
-        }
-
-        int[] ints = (int[])ar.result;
-        if(ints.length != 0) {
-            mRuimPinLocked = (0!=ints[0]);
-            if(DBG) log("Query facility lock : "  + mRuimPinLocked);
-        } else {
-            Log.e(LOG_TAG, "[CdmaRuimCard] Bogus facility lock response");
-        }
-    }
-
-    /**
-     * Interpret EVENT_QUERY_FACILITY_LOCK_DONE
-     * @param ar is asyncResult of Query_Facility_Locked
-     */
-    private void onQueryFdnEnabled(AsyncResult ar) {
-        if(ar.exception != null) {
-            if(DBG) log("Error in querying facility lock:" + ar.exception);
-            return;
-        }
-
-        int[] ints = (int[])ar.result;
-        if(ints.length != 0) {
-            mRuimFdnEnabled = (0!=ints[0]);
-            if(DBG) log("Query facility lock : "  + mRuimFdnEnabled);
-        } else {
-            Log.e(LOG_TAG, "[CdmaRuimCard] Bogus facility lock response");
-        }
-    }
-
-    private void
-    getRuimStatusDone(AsyncResult ar) {
-        if (ar.exception != null) {
-            Log.e(LOG_TAG,"Error getting SIM status. "
-                    + "RIL_REQUEST_GET_SIM_STATUS should "
-                    + "never return an error", ar.exception);
-            return;
-        }
-
-        CommandsInterface.IccStatus newStatus
-            = (CommandsInterface.IccStatus)  ar.result;
-
-        handleRuimStatus(newStatus);
-    }
-
-    private void
-    handleRuimStatus(CommandsInterface.IccStatus newStatus) {
-        boolean transitionedIntoPinLocked;
-        boolean transitionedIntoAbsent;
-        boolean transitionedIntoNetworkLocked;
-
-        RuimCard.State oldState, newState;
-
-        oldState = getState();
-        status = newStatus;
-        newState = getState();
-
-        updateStateProperty();
-
-        transitionedIntoPinLocked = (
-                 (oldState != State.PIN_REQUIRED && newState == State.PIN_REQUIRED)
-              || (oldState != State.PUK_REQUIRED && newState == State.PUK_REQUIRED));
-        transitionedIntoAbsent = (oldState != State.ABSENT && newState == State.ABSENT);
-        transitionedIntoNetworkLocked = (oldState != State.NETWORK_LOCKED
-                && newState == State.NETWORK_LOCKED);
-
-        if (transitionedIntoPinLocked) {
-            if(DBG) log("Notify RUIM pin or puk locked.");
-            pinLockedRegistrants.notifyRegistrants();
-            broadcastRuimStateChangedIntent(RuimCard.INTENT_VALUE_ICC_LOCKED,
-                    (newState == State.PIN_REQUIRED) ?
-                       INTENT_VALUE_LOCKED_ON_PIN : INTENT_VALUE_LOCKED_ON_PUK);
-        } else if (transitionedIntoAbsent) {
-            if(DBG) log("Notify RUIM missing.");
-            absentRegistrants.notifyRegistrants();
-            broadcastRuimStateChangedIntent(RuimCard.INTENT_VALUE_ICC_ABSENT, null);
-        } else if (transitionedIntoNetworkLocked) {
-            if(DBG) log("Notify RUIM network locked.");
-            networkLockedRegistrants.notifyRegistrants();
-            broadcastRuimStateChangedIntent(RuimCard.INTENT_VALUE_ICC_LOCKED,
-                  INTENT_VALUE_LOCKED_NETWORK);
-        }
-    }
-
-    public void broadcastRuimStateChangedIntent(String value, String reason) {
-        Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
-        intent.putExtra(Phone.PHONE_NAME_KEY, phone.getPhoneName());
-        intent.putExtra(RuimCard.INTENT_KEY_ICC_STATE, value);
-        intent.putExtra(RuimCard.INTENT_KEY_LOCKED_REASON, reason);
-        if(DBG) log("Broadcasting intent SIM_STATE_CHANGED_ACTION " +  value
-                + " reason " + reason);
-        ActivityManagerNative.broadcastStickyIntent(intent, READ_PHONE_STATE);
-    }
-
-    public void updateImsiConfiguration(String imsi) {
-        if (imsi.length() >= 6) {
-            Configuration config = new Configuration();
-            config.mcc = ((imsi.charAt(0)-'0')*100)
-                    + ((imsi.charAt(1)-'0')*10)
-                    + (imsi.charAt(2)-'0');
-            config.mnc = ((imsi.charAt(3)-'0')*100)
-                    + ((imsi.charAt(4)-'0')*10)
-                    + (imsi.charAt(5)-'0');
-            try {
-                ActivityManagerNative.getDefault().updateConfiguration(config);
-            } catch (RemoteException e) {
-            }
-        }
-    }
-
-    private void
-    updateStateProperty() {
-        phone.setSystemProperty(
-            TelephonyProperties.PROPERTY_SIM_STATE,
-            getState().toString());
-    }
-
-    private void log(String msg) {
-        Log.d(LOG_TAG, "[RuimCard] " + msg);
-    }
-}
+ }
 
diff --git a/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java b/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java
index 55f48b1..7c74314 100644
--- a/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java
+++ b/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java
@@ -37,10 +37,6 @@
 import com.android.internal.telephony.IccUtils;
 import com.android.internal.telephony.PhoneProxy;
 
-import com.android.internal.telephony.TelephonyIntents;
-import android.app.ActivityManagerNative;
-import android.content.Intent;
-
 
 /**
  * {@hide}
@@ -65,7 +61,6 @@
     private static final int EVENT_RADIO_OFF_OR_NOT_AVAILABLE = 2;
     private static final int EVENT_GET_DEVICE_IDENTITY_DONE = 4;
     private static final int EVENT_GET_ICCID_DONE = 5;
-    private static final int EVENT_NV_READY = 9;
     private static final int EVENT_GET_CDMA_SUBSCRIPTION_DONE = 10;
     private static final int EVENT_UPDATE_DONE = 14;
     private static final int EVENT_GET_SST_DONE = 17;
@@ -76,7 +71,7 @@
     private static final int EVENT_GET_SMS_DONE = 22;
 
     private static final int EVENT_RUIM_REFRESH = 31;
-    private static final int EVENT_OTA_PROVISION_STATUS_CHANGE = 32;
+
 
     RuimRecords(CDMAPhone p) {
         super(p);
@@ -90,14 +85,12 @@
 
 
         p.mCM.registerForRUIMReady(this, EVENT_RUIM_READY, null);
-        p.mCM.registerForNVReady(this, EVENT_NV_READY, null);
         p.mCM.registerForOffOrNotAvailable(this, EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
         // NOTE the EVENT_SMS_ON_RUIM is not registered
         p.mCM.setOnIccRefresh(this, EVENT_RUIM_REFRESH, null);
 
         // Start off by setting empty state
         onRadioOffOrNotAvailable();
-        p.mCM.registerForCdmaOtaProvision(this,EVENT_OTA_PROVISION_STATUS_CHANGE, null);
 
     }
 
@@ -106,8 +99,6 @@
         phone.mCM.unregisterForRUIMReady(this);
         phone.mCM.unregisterForOffOrNotAvailable( this);
         phone.mCM.unSetOnIccRefresh(this);
-        phone.mCM.unregisterForNVReady(this);
-        phone.mCM.unregisterForCdmaOtaProvision(this);
     }
 
     @Override
@@ -202,9 +193,7 @@
             case EVENT_RUIM_READY:
                 onRuimReady();
             break;
-            case EVENT_NV_READY:
-                onNvReady();
-            break;
+
             case EVENT_RADIO_OFF_OR_NOT_AVAILABLE:
                 onRadioOffOrNotAvailable();
             break;
@@ -221,15 +210,7 @@
                 if (ar.exception != null) {
                     break;
                 }
-                if (m_ota_commited) {
-                    if (mMyMobileNumber != localTemp[0]) {
-                        Intent intent = new Intent(TelephonyIntents.ACTION_CDMA_OTA_MDN_CHANGED);
-                        intent.putExtra("mdn", localTemp[0]);
-                        Log.d(LOG_TAG,"Broadcasting intent MDN Change in OTA ");
-                        ActivityManagerNative.broadcastStickyIntent(intent, null);
-                    }
-                    m_ota_commited = false;
-                }
+
                 mMyMobileNumber = localTemp[0];
                 mMin2Min1 = localTemp[3];
                 mPrlVersion = localTemp[4];
@@ -281,21 +262,6 @@
                 }
                 break;
 
-            case EVENT_OTA_PROVISION_STATUS_CHANGE:
-                m_ota_commited=false;
-                ar = (AsyncResult)msg.obj;
-                if (ar.exception == null) {
-                    int[] ints = (int[]) ar.result;
-                    int otaStatus = ints[0];
-                    if (otaStatus == phone.CDMA_OTA_PROVISION_STATUS_COMMITTED) {
-                        m_ota_commited=true;
-                        phone.mCM.getCDMASubscription(obtainMessage(EVENT_GET_CDMA_SUBSCRIPTION_DONE));
-                    } else if (otaStatus == phone.CDMA_OTA_PROVISION_STATUS_OTAPA_STOPPED) {
-                        phone.mCM.getCDMASubscription(obtainMessage(EVENT_GET_CDMA_SUBSCRIPTION_DONE));
-                    }
-                 }
-                 break;
-
         }}catch (RuntimeException exc) {
             // I don't want these exceptions to be fatal
             Log.w(LOG_TAG, "Exception parsing RUIM record", exc);
@@ -329,7 +295,7 @@
 
         recordsLoadedRegistrants.notifyRegistrants(
             new AsyncResult(null, null, null));
-        ((CDMAPhone) phone).mRuimCard.broadcastRuimStateChangedIntent(
+        ((CDMAPhone) phone).mRuimCard.broadcastIccStateChangedIntent(
                 RuimCard.INTENT_VALUE_ICC_LOADED, null);
     }
 
@@ -338,7 +304,7 @@
           READY is sent before IMSI ready
         */
 
-        ((CDMAPhone) phone).mRuimCard.broadcastRuimStateChangedIntent(
+        ((CDMAPhone) phone).mRuimCard.broadcastIccStateChangedIntent(
                 RuimCard.INTENT_VALUE_ICC_READY, null);
 
         fetchRuimRecords();
@@ -347,10 +313,6 @@
 
     }
 
-    private void onNvReady() {
-        phone.mCM.getCDMASubscription(obtainMessage(EVENT_GET_CDMA_SUBSCRIPTION_DONE));
-
-    }
 
     private void fetchRuimRecords() {
         recordsRequested = true;
diff --git a/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java b/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
old mode 100644
new mode 100755
index 3a92064..c085739
--- a/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
+++ b/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
@@ -518,6 +518,7 @@
         originatingAddress = addr;
         env.origAddress = addr;
         mEnvelope = env;
+        mPdu = pdu;
 
         parseSms();
     }
@@ -586,9 +587,24 @@
     private static CdmaSmsAddress parseCdmaSmsAddr(String addrStr) {
         // see C.S0015-B, v2.0, 3.4.3.3
         CdmaSmsAddress addr = new CdmaSmsAddress();
-        addr.digitMode = CdmaSmsAddress.DIGIT_MODE_8BIT_CHAR;
+        addr.digitMode = CdmaSmsAddress.DIGIT_MODE_4BIT_DTMF;
         try {
             addr.origBytes = addrStr.getBytes("UTF-8");
+            for (int index = 0; index < addr.origBytes.length; index++) {
+                if (addr.origBytes[index] >= '0' && addr.origBytes[index] <= '9') {
+                    if (addr.origBytes[index] == '0') {
+                        addr.origBytes[index] = 10;
+                    } else {
+                        addr.origBytes[index] -= '0';
+                    }
+                } else if (addr.origBytes[index] == '*') {
+                    addr.origBytes[index] = 11;
+                } else if (addr.origBytes[index] == '#') {
+                    addr.origBytes[index] = 12;
+                } else {
+                    return null;
+                }
+            }
         } catch  (java.io.UnsupportedEncodingException ex) {
             Log.e(LOG_TAG, "CDMA address parsing failed: " + ex);
             return null;
@@ -596,7 +612,7 @@
         addr.numberOfDigits = (byte)addr.origBytes.length;
         addr.numberMode = CdmaSmsAddress.NUMBER_MODE_NOT_DATA_NETWORK;
         addr.numberPlan = CdmaSmsAddress.NUMBERING_PLAN_ISDN_TELEPHONY;
-        addr.ton = CdmaSmsAddress.TON_INTERNATIONAL_OR_IP;
+        addr.ton = CdmaSmsAddress.TON_UNKNOWN;
         return addr;
     }
 
@@ -728,9 +744,8 @@
             dos.close();
 
             /**
-             * TODO(cleanup) -- This is the only place where mPdu is
-             * defined, and this is not obviously the only place where
-             * it needs to be defined.  It would be much nicer if
+             * TODO(cleanup) -- The mPdu field is managed in
+             * a fragile manner, and it would be much nicer if
              * accessing the serialized representation used a less
              * fragile mechanism.  Maybe the getPdu method could
              * generate a representation if there was not yet one?
diff --git a/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java b/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java
index ef3afff..2b32872 100644
--- a/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java
+++ b/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java
@@ -901,6 +901,16 @@
         return result;
     }
 
+    private static String decodeLatin(byte[] data, int offset, int numFields)
+        throws CodingException
+    {
+        try {
+            return new String(data, offset, numFields - offset, "ISO-8859-1");
+        } catch (java.io.UnsupportedEncodingException ex) {
+            throw new CodingException("ISO-8859-1 decode failed: " + ex);
+        }
+    }
+
     private static void decodeUserDataPayload(UserData userData, boolean hasUserDataHeader)
         throws CodingException
     {
@@ -914,6 +924,19 @@
         }
         switch (userData.msgEncoding) {
         case UserData.ENCODING_OCTET:
+            // Strip off any padding bytes, meaning any differences between the length of the
+            // array and the target length specified by numFields.  This is to avoid any confusion
+            // by code elsewhere that only considers the payload array length.
+            byte[] payload = new byte[userData.numFields];
+            int copyLen = userData.numFields < userData.payload.length
+                    ? userData.numFields : userData.payload.length;
+
+            System.arraycopy(userData.payload, 0, payload, 0, copyLen);
+            userData.payload = payload;
+
+            // There are many devices in the market that send 8bit text sms (latin encoded) as
+            // octet encoded.
+            userData.payloadStr = decodeLatin(userData.payload, offset, userData.numFields);
             break;
         case UserData.ENCODING_7BIT_ASCII:
             userData.payloadStr = decode7bitAscii(userData.payload, offset, userData.numFields);
@@ -927,6 +950,9 @@
         case UserData.ENCODING_GSM_7BIT_ALPHABET:
             userData.payloadStr = decode7bitGsm(userData.payload, offset, userData.numFields);
             break;
+        case UserData.ENCODING_LATIN:
+            userData.payloadStr = decodeLatin(userData.payload, offset, userData.numFields);
+            break;
         default:
             throw new CodingException("unsupported user data encoding ("
                                       + userData.msgEncoding + ")");
diff --git a/telephony/java/com/android/internal/telephony/cdma/sms/UserData.java b/telephony/java/com/android/internal/telephony/cdma/sms/UserData.java
index 34cbbfa..04796b8 100644
--- a/telephony/java/com/android/internal/telephony/cdma/sms/UserData.java
+++ b/telephony/java/com/android/internal/telephony/cdma/sms/UserData.java
@@ -35,7 +35,7 @@
     //public static final int ENCODING_SHIFT_JIS                  = 0x05;
     //public static final int ENCODING_KOREAN                     = 0x06;
     //public static final int ENCODING_LATIN_HEBREW               = 0x07;
-    //public static final int ENCODING_LATIN                      = 0x08;
+    public static final int ENCODING_LATIN                      = 0x08;
     public static final int ENCODING_GSM_7BIT_ALPHABET          = 0x09;
     public static final int ENCODING_GSM_DCS                    = 0x0A;
 
diff --git a/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java b/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java
index d1e4b4f..6f89288 100755
--- a/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java
@@ -51,6 +51,7 @@
 import static com.android.internal.telephony.CommandsInterface.SERVICE_CLASS_VOICE;
 import static com.android.internal.telephony.TelephonyProperties.PROPERTY_BASEBAND_VERSION;
 
+import com.android.internal.telephony.Call;
 import com.android.internal.telephony.CallForwardInfo;
 import com.android.internal.telephony.CallStateException;
 import com.android.internal.telephony.CommandsInterface;
@@ -378,20 +379,19 @@
     }
 
     /**
-     * Notify any interested party of a Phone state change.
+     * Notify any interested party of a Phone state change {@link Phone.State}
      */
     /*package*/ void notifyPhoneStateChanged() {
         mNotifier.notifyPhoneState(this);
     }
 
     /**
-     * Notifies registrants (ie, activities in the Phone app) about
-     * changes to call state (including Phone and Connection changes).
+     * Notify registrants of a change in the call state. This notifies changes in {@link Call.State}
+     * Use this when changes in the precise call state are needed, else use notifyPhoneStateChanged.
      */
-    /*package*/ void
-    notifyCallStateChanged() {
+    /*package*/ void notifyPreciseCallStateChanged() {
         /* we'd love it if this was package-scoped*/
-        super.notifyCallStateChangedP();
+        super.notifyPreciseCallStateChangedP();
     }
 
     /*package*/ void
@@ -1169,6 +1169,10 @@
         return mDataConnection.getDnsServers(apnType);
     }
 
+    public boolean isDataConnectivityEnabled() {
+        return mDataConnection.getDataEnabled();
+    }
+
     /**
      * The only circumstances under which we report that data connectivity is not
      * possible are
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmCallTracker.java b/telephony/java/com/android/internal/telephony/gsm/GsmCallTracker.java
index 5c5090f..f3b7596 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GsmCallTracker.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmCallTracker.java
@@ -212,7 +212,7 @@
         }
 
         updatePhoneState();
-        phone.notifyCallStateChanged();
+        phone.notifyPreciseCallStateChanged();
 
         return pendingMO;
     }
@@ -279,7 +279,7 @@
         internalClearDisconnected();
 
         updatePhoneState();
-        phone.notifyCallStateChanged();
+        phone.notifyPreciseCallStateChanged();
     }
 
     boolean
@@ -600,7 +600,7 @@
         }
 
         if (hasNonHangupStateChanged || newRinging != null) {
-            phone.notifyCallStateChanged();
+            phone.notifyPreciseCallStateChanged();
         }
 
         //dumpState();
@@ -883,7 +883,7 @@
 
                 updatePhoneState();
 
-                phone.notifyCallStateChanged();
+                phone.notifyPreciseCallStateChanged();
                 droppedDuringPoll.clear();
             break;
 
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmConnection.java b/telephony/java/com/android/internal/telephony/gsm/GsmConnection.java
index d93ca1d..2091fb6 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GsmConnection.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmConnection.java
@@ -381,10 +381,14 @@
                     } else if (phone.mSST.rs.isCsNormalRestricted()) {
                         return DisconnectCause.CS_RESTRICTED_NORMAL;
                     } else {
-                        return DisconnectCause.NORMAL;
+                        return DisconnectCause.ERROR_UNSPECIFIED;
                     }
-                } else {
+                } else if (causeCode == CallFailCause.NORMAL_CLEARING) {
                     return DisconnectCause.NORMAL;
+                } else {
+                    // If nothing else matches, report unknown call drop reason
+                    // to app, not NORMAL call end.
+                    return DisconnectCause.ERROR_UNSPECIFIED;
                 }
         }
     }
diff --git a/telephony/java/com/android/internal/telephony/gsm/MccTable.java b/telephony/java/com/android/internal/telephony/gsm/MccTable.java
index e18da56..22b1f4f 100644
--- a/telephony/java/com/android/internal/telephony/gsm/MccTable.java
+++ b/telephony/java/com/android/internal/telephony/gsm/MccTable.java
@@ -35,6 +35,7 @@
         int smallestDigitsMnc;
         String timezone;
         String language;
+        int wifiChannelsAllowed;
 
         MccEntry(int mnc, String iso, int smallestDigitsMCC) {
             this(mnc, iso, smallestDigitsMCC, null);
@@ -45,11 +46,16 @@
         }
 
         MccEntry(int mnc, String iso, int smallestDigitsMCC, String timezone, String language) {
+            this(mnc, iso, smallestDigitsMCC, timezone, language, 0);
+        }
+
+        MccEntry(int mnc, String iso, int smallestDigitsMCC, String timezone, String language, int wifiChannels) {
             this.mcc = mnc;
             this.iso = iso;
             this.smallestDigitsMnc = smallestDigitsMCC;
             this.timezone = timezone;
             this.language = language;
+            this.wifiChannelsAllowed = wifiChannels;
         }
 
         public int compareTo(MccEntry o)
@@ -148,6 +154,23 @@
         }
     }
 
+    /**
+     * Given a GSM Mobile Country Code, returns
+     * the number of wifi channels allowed in that country.
+     * Returns 0 if unavailable
+     */
+    public static int wifiChannelsForMcc(int mcc) {
+        MccEntry entry;
+
+        entry = entryForMcc(mcc);
+
+        if (entry == null) {
+            return 0;
+        } else {
+            return entry.wifiChannelsAllowed;
+        }
+    }
+
     static {
         table = new ArrayList<MccEntry>(240);
 
@@ -169,7 +192,7 @@
          */
 
 		table.add(new MccEntry(202,"gr",2));	//Greece
-		table.add(new MccEntry(204,"nl",2,"Europe/Amsterdam","nl"));	//Netherlands (Kingdom of the)
+		table.add(new MccEntry(204,"nl",2,"Europe/Amsterdam","nl",13)); //Netherlands (Kingdom of the)
 		table.add(new MccEntry(206,"be",2));	//Belgium
 		table.add(new MccEntry(208,"fr",2,"Europe/Paris","fr"));	//France
 		table.add(new MccEntry(212,"mc",2));	//Monaco (Principality of)
@@ -183,11 +206,11 @@
 		table.add(new MccEntry(225,"va",2,"Europe/Rome","it"));	//Vatican City State
 		table.add(new MccEntry(226,"ro",2));	//Romania
 		table.add(new MccEntry(228,"ch",2,"Europe/Zurich","de"));	//Switzerland (Confederation of)
-		table.add(new MccEntry(230,"cz",2,"Europe/Prague","cs"));	//Czech Republic
+		table.add(new MccEntry(230,"cz",2,"Europe/Prague","cs", 13));	//Czech Republic
 		table.add(new MccEntry(231,"sk",2));	//Slovak Republic
-		table.add(new MccEntry(232,"at",2,"Europe/Vienna","de"));	//Austria
-		table.add(new MccEntry(234,"gb",2,"Europe/London","en"));	//United Kingdom of Great Britain and Northern Ireland
-		table.add(new MccEntry(235,"gb",2,"Europe/London","en"));	//United Kingdom of Great Britain and Northern Ireland
+		table.add(new MccEntry(232,"at",2,"Europe/Vienna","de", 13));   //Austria
+		table.add(new MccEntry(234,"gb",2,"Europe/London","en", 13));   //United Kingdom of Great Britain and Northern Ireland
+		table.add(new MccEntry(235,"gb",2,"Europe/London","en", 13));   //United Kingdom of Great Britain and Northern Ireland
 		table.add(new MccEntry(238,"dk",2));	//Denmark
 		table.add(new MccEntry(240,"se",2));	//Sweden
 		table.add(new MccEntry(242,"no",2));	//Norway
@@ -200,7 +223,7 @@
 		table.add(new MccEntry(257,"by",2));	//Belarus (Republic of)
 		table.add(new MccEntry(259,"md",2));	//Moldova (Republic of)
 		table.add(new MccEntry(260,"pl",2,"Europe/Warsaw"));	//Poland (Republic of)
-		table.add(new MccEntry(262,"de",2,"Europe/Berlin","de"));	//Germany (Federal Republic of)
+		table.add(new MccEntry(262,"de",2,"Europe/Berlin","de", 13));   //Germany (Federal Republic of)
 		table.add(new MccEntry(266,"gi",2));	//Gibraltar
 		table.add(new MccEntry(268,"pt",2));	//Portugal
 		table.add(new MccEntry(270,"lu",2));	//Luxembourg
@@ -219,15 +242,15 @@
 		table.add(new MccEntry(293,"sl",2));	//Slovenia (Republic of)
                 table.add(new MccEntry(294,"mk",2));   //The Former Yugoslav Republic of Macedonia
 		table.add(new MccEntry(295,"li",2));	//Liechtenstein (Principality of)
-		table.add(new MccEntry(302,"ca",2));	//Canada
+		table.add(new MccEntry(302,"ca",2, "", "", 11));        //Canada
 		table.add(new MccEntry(308,"pm",2));	//Saint Pierre and Miquelon (Collectivit territoriale de la Rpublique franaise)
-		table.add(new MccEntry(310,"us",3,"","en"));	//United States of America
-		table.add(new MccEntry(311,"us",3,"","en"));	//United States of America
-		table.add(new MccEntry(312,"us",3,"","en"));	//United States of America
-		table.add(new MccEntry(313,"us",3,"","en"));	//United States of America
-		table.add(new MccEntry(314,"us",3,"","en"));	//United States of America
-		table.add(new MccEntry(315,"us",3,"","en"));	//United States of America
-		table.add(new MccEntry(316,"us",3,"","en"));	//United States of America
+		table.add(new MccEntry(310,"us",3,"","en", 11));        //United States of America
+		table.add(new MccEntry(311,"us",3,"","en", 11));        //United States of America
+		table.add(new MccEntry(312,"us",3,"","en", 11));        //United States of America
+		table.add(new MccEntry(313,"us",3,"","en", 11));        //United States of America
+		table.add(new MccEntry(314,"us",3,"","en", 11));        //United States of America
+		table.add(new MccEntry(315,"us",3,"","en", 11));        //United States of America
+		table.add(new MccEntry(316,"us",3,"","en", 11));        //United States of America
 		table.add(new MccEntry(330,"pr",2));	//Puerto Rico
 		table.add(new MccEntry(332,"vi",2));	//United States Virgin Islands
 		table.add(new MccEntry(334,"mx",3));	//Mexico
@@ -283,8 +306,8 @@
 		table.add(new MccEntry(436,"tj",2));	//Tajikistan (Republic of)
 		table.add(new MccEntry(437,"kg",2));	//Kyrgyz Republic
 		table.add(new MccEntry(438,"tm",2));	//Turkmenistan
-		table.add(new MccEntry(440,"jp",2,"Asia/Tokyo","ja"));	//Japan
-		table.add(new MccEntry(441,"jp",2,"Asia/Tokyo","ja"));	//Japan
+		table.add(new MccEntry(440,"jp",2,"Asia/Tokyo","ja", 14));              //Japan
+		table.add(new MccEntry(441,"jp",2,"Asia/Tokyo","ja", 14));              //Japan
 		table.add(new MccEntry(450,"kr",2));	//Korea (Republic of)
 		table.add(new MccEntry(452,"vn",2));	//Viet Nam (Socialist Republic of)
 		table.add(new MccEntry(454,"hk",2));	//"Hong Kong, China"
@@ -298,12 +321,12 @@
 		table.add(new MccEntry(470,"bd",2));	//Bangladesh (People's Republic of)
 		table.add(new MccEntry(472,"mv",2));	//Maldives (Republic of)
 		table.add(new MccEntry(502,"my",2));	//Malaysia
-		table.add(new MccEntry(505,"au",2,"Australia/Sydney","en"));	//Australia
+		table.add(new MccEntry(505,"au",2,"Australia/Sydney","en", 11));        //Australia
 		table.add(new MccEntry(510,"id",2));	//Indonesia (Republic of)
 		table.add(new MccEntry(514,"tl",2));	//Democratic Republic of Timor-Leste
 		table.add(new MccEntry(515,"ph",2));	//Philippines (Republic of the)
 		table.add(new MccEntry(520,"th",2));	//Thailand
-		table.add(new MccEntry(525,"sg",2,"Singapore","en"));	//Singapore (Republic of)
+		table.add(new MccEntry(525,"sg",2,"Singapore","en", 11));               //Singapore (Republic of)
 		table.add(new MccEntry(528,"bn",2));	//Brunei Darussalam
 		table.add(new MccEntry(530,"nz",2,"Pacific/Auckland", "en"));	//New Zealand
 		table.add(new MccEntry(534,"mp",2));	//Northern Mariana Islands (Commonwealth of the)
diff --git a/telephony/java/com/android/internal/telephony/gsm/SIMRecords.java b/telephony/java/com/android/internal/telephony/gsm/SIMRecords.java
index e25de81..4272faa 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SIMRecords.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SIMRecords.java
@@ -16,39 +16,29 @@
 
 package com.android.internal.telephony.gsm;
 
-import android.app.ActivityManagerNative;
+import static com.android.internal.telephony.TelephonyProperties.PROPERTY_ICC_OPERATOR_ALPHA;
+import static com.android.internal.telephony.TelephonyProperties.PROPERTY_ICC_OPERATOR_ISO_COUNTRY;
+import static com.android.internal.telephony.TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC;
 import android.app.AlarmManager;
-import android.app.IActivityManager;
 import android.content.Context;
-import android.content.res.Configuration;
+import android.net.wifi.WifiManager;
 import android.os.AsyncResult;
-import android.os.Handler;
 import android.os.Message;
 import android.os.SystemProperties;
-import android.os.Registrant;
+import android.provider.Settings;
 import android.util.Log;
-import java.util.ArrayList;
-
-
-import static com.android.internal.telephony.TelephonyProperties.*;
 
 import com.android.internal.telephony.AdnRecord;
 import com.android.internal.telephony.AdnRecordCache;
 import com.android.internal.telephony.AdnRecordLoader;
 import com.android.internal.telephony.CommandsInterface;
-import com.android.internal.telephony.gsm.SimCard;
-import com.android.internal.telephony.gsm.SmsMessage;
 import com.android.internal.telephony.IccFileHandler;
 import com.android.internal.telephony.IccRecords;
 import com.android.internal.telephony.IccUtils;
 import com.android.internal.telephony.IccVmFixedException;
 import com.android.internal.telephony.IccVmNotSupportedException;
-import com.android.internal.telephony.PhoneProxy;
 
-
-
-
-
+import java.util.ArrayList;
 
 
 /**
@@ -512,6 +502,29 @@
         phone.setSystemLocale(language, country);
     }
 
+    /**
+     * If the number of allowed wifi channels has not been set, set it based on
+     * the MCC of the SIM.
+     * @param mcc Mobile Country Code of the SIM
+     */
+    private void setWifiChannelsFromMccIfNeeded(int mcc) {
+        int wifiChannels = MccTable.wifiChannelsForMcc(mcc);
+
+        if (wifiChannels != 0) {
+            Context context = phone.getContext();
+            // only set to this default if the user hasn't manually set it
+            try {
+                Settings.Secure.getInt(context.getContentResolver(),
+                        Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS);
+            } catch (Settings.SettingNotFoundException e) {
+                WifiManager wM = (WifiManager)
+                        context.getSystemService(Context.WIFI_SERVICE);
+                // don't persist
+                wM.setNumAllowedChannels(wifiChannels, false);
+            }
+        }
+    }
+
     //***** Overridden from Handler
     public void handleMessage(Message msg) {
         AsyncResult ar;
@@ -552,12 +565,13 @@
 
                 Log.d(LOG_TAG, "IMSI: " + imsi.substring(0, 6) + "xxxxxxxxx");
                 ((GSMPhone) phone).mSimCard.updateImsiConfiguration(imsi);
-                ((GSMPhone) phone).mSimCard.broadcastSimStateChangedIntent(
+                ((GSMPhone) phone).mSimCard.broadcastIccStateChangedIntent(
                         SimCard.INTENT_VALUE_ICC_IMSI, null);
 
                 int mcc = Integer.parseInt(imsi.substring(0, 3));
                 setTimezoneFromMccIfNeeded(mcc);
                 setLocaleFromMccIfNeeded(mcc);
+                setWifiChannelsFromMccIfNeeded(mcc);
             break;
 
             case EVENT_GET_MBI_DONE:
@@ -1178,7 +1192,7 @@
 
         recordsLoadedRegistrants.notifyRegistrants(
             new AsyncResult(null, null, null));
-        ((GSMPhone) phone).mSimCard.broadcastSimStateChangedIntent(
+        ((GSMPhone) phone).mSimCard.broadcastIccStateChangedIntent(
                 SimCard.INTENT_VALUE_ICC_LOADED, null);
     }
 
@@ -1203,7 +1217,7 @@
         /* broadcast intent SIM_READY here so that we can make sure
           READY is sent before IMSI ready
         */
-        ((GSMPhone) phone).mSimCard.broadcastSimStateChangedIntent(
+        ((GSMPhone) phone).mSimCard.broadcastIccStateChangedIntent(
                 SimCard.INTENT_VALUE_ICC_READY, null);
 
         fetchSimRecords();
diff --git a/telephony/java/com/android/internal/telephony/gsm/SimCard.java b/telephony/java/com/android/internal/telephony/gsm/SimCard.java
index 9af3aa6..6c56682 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SimCard.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SimCard.java
@@ -17,469 +17,37 @@
 package com.android.internal.telephony.gsm;
 
 import android.app.ActivityManagerNative;
-import android.content.Intent;
 import android.content.res.Configuration;
-import android.os.AsyncResult;
 import android.os.RemoteException;
-import android.os.Handler;
-import android.os.Message;
-import android.os.Registrant;
-import android.os.RegistrantList;
 import android.util.Log;
 
-import com.android.internal.telephony.CommandsInterface;
 import com.android.internal.telephony.IccCard;
-import com.android.internal.telephony.Phone;
-import com.android.internal.telephony.PhoneProxy;
-import com.android.internal.telephony.TelephonyIntents;
-import com.android.internal.telephony.TelephonyProperties;
-
-import static android.Manifest.permission.READ_PHONE_STATE;
 
 /**
- * Note: this class shares common code with RuimCard, consider a base class to minimize code
- * duplication.
  * {@hide}
  */
-public final class SimCard extends Handler implements IccCard {
-    static final String LOG_TAG="GSM";
-
-    //***** Instance Variables
-    private static final boolean DBG = true;
-
-    private GSMPhone phone;
-    private CommandsInterface.IccStatus status = null;
-    private boolean mDesiredPinLocked;
-    private boolean mDesiredFdnEnabled;
-    private boolean mSimPinLocked = true; // Default to locked
-    private boolean mSimFdnEnabled = false; // Default to disabled.
-                                            // Will be updated when SIM_READY.
-
-    //***** Constants
-
-    // FIXME I hope this doesn't conflict with the Dialer's notifications
-    static final int NOTIFICATION_ID_SIM_STATUS = 33456;
-
-    //***** Event Constants
-
-    static final int EVENT_SIM_LOCKED_OR_ABSENT = 1;
-    static final int EVENT_GET_SIM_STATUS_DONE = 2;
-    static final int EVENT_RADIO_OFF_OR_NOT_AVAILABLE = 3;
-    static final int EVENT_PINPUK_DONE = 4;
-    static final int EVENT_REPOLL_STATUS_DONE = 5;
-    static final int EVENT_SIM_READY = 6;
-    static final int EVENT_QUERY_FACILITY_LOCK_DONE = 7;
-    static final int EVENT_CHANGE_FACILITY_LOCK_DONE = 8;
-    static final int EVENT_CHANGE_SIM_PASSWORD_DONE = 9;
-    static final int EVENT_QUERY_FACILITY_FDN_DONE = 10;
-    static final int EVENT_CHANGE_FACILITY_FDN_DONE = 11;
-
-
-    //***** Constructor
+public final class SimCard extends IccCard {
 
     SimCard(GSMPhone phone) {
-        this.phone = phone;
+        super(phone, "GSM", true);
 
-        phone.mCM.registerForSIMLockedOrAbsent(
-                        this, EVENT_SIM_LOCKED_OR_ABSENT, null);
-
-        phone.mCM.registerForOffOrNotAvailable(
-                        this, EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
-
-        phone.mCM.registerForSIMReady(
-                        this, EVENT_SIM_READY, null);
-
+        mPhone.mCM.registerForSIMLockedOrAbsent(mHandler, EVENT_ICC_LOCKED_OR_ABSENT, null);
+        mPhone.mCM.registerForOffOrNotAvailable(mHandler, EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
+        mPhone.mCM.registerForSIMReady(mHandler, EVENT_ICC_READY, null);
         updateStateProperty();
     }
 
+    @Override
     public void dispose() {
         //Unregister for all events
-        phone.mCM.unregisterForSIMLockedOrAbsent(this);
-        phone.mCM.unregisterForOffOrNotAvailable(this);
-        phone.mCM.unregisterForSIMReady(this);
+        mPhone.mCM.unregisterForSIMLockedOrAbsent(mHandler);
+        mPhone.mCM.unregisterForOffOrNotAvailable(mHandler);
+        mPhone.mCM.unregisterForSIMReady(mHandler);
     }
 
-    protected void finalize() {
-        if(DBG) Log.d(LOG_TAG, "SimCard finalized");
-    }
-
-    //***** SimCard implementation
-
-    public State
-    getState() {
-        if (status == null) {
-            switch(phone.mCM.getRadioState()) {
-                /* This switch block must not return anything in
-                 * State.isLocked() or State.ABSENT.
-                 * If it does, handleSimStatus() may break
-                 */
-                case RADIO_OFF:
-                case RADIO_UNAVAILABLE:
-                case SIM_NOT_READY:
-                    return State.UNKNOWN;
-                case SIM_LOCKED_OR_ABSENT:
-                    //this should be transient-only
-                    return State.UNKNOWN;
-                case SIM_READY:
-                    return State.READY;
-            }
-        } else {
-            switch (status) {
-                case ICC_ABSENT:            return State.ABSENT;
-                case ICC_NOT_READY:         return State.UNKNOWN;
-                case ICC_READY:             return State.READY;
-                case ICC_PIN:               return State.PIN_REQUIRED;
-                case ICC_PUK:               return State.PUK_REQUIRED;
-                case ICC_NETWORK_PERSONALIZATION: return State.NETWORK_LOCKED;
-            }
-        }
-
-        Log.e(LOG_TAG, "GsmSimCard.getState(): case should never be reached");
-        return State.UNKNOWN;
-    }
-
-    private RegistrantList absentRegistrants = new RegistrantList();
-    private RegistrantList pinLockedRegistrants = new RegistrantList();
-    private RegistrantList networkLockedRegistrants = new RegistrantList();
-
-
-    public void registerForAbsent(Handler h, int what, Object obj) {
-        Registrant r = new Registrant (h, what, obj);
-
-        absentRegistrants.add(r);
-
-        if (getState() == State.ABSENT) {
-            r.notifyRegistrant();
-        }
-    }
-
-    public void unregisterForAbsent(Handler h) {
-        absentRegistrants.remove(h);
-    }
-
-    public void registerForNetworkLocked(Handler h, int what, Object obj) {
-        Registrant r = new Registrant (h, what, obj);
-
-        networkLockedRegistrants.add(r);
-
-        if (getState() == State.NETWORK_LOCKED) {
-            r.notifyRegistrant();
-        }
-    }
-
-    public void unregisterForNetworkLocked(Handler h) {
-        networkLockedRegistrants.remove(h);
-    }
-
-    public void registerForLocked(Handler h, int what, Object obj) {
-        Registrant r = new Registrant (h, what, obj);
-
-        pinLockedRegistrants.add(r);
-
-        if (getState().isPinLocked()) {
-            r.notifyRegistrant();
-        }
-    }
-
-    public void unregisterForLocked(Handler h) {
-        pinLockedRegistrants.remove(h);
-    }
-
-
-    public void supplyPin (String pin, Message onComplete) {
-        phone.mCM.supplyIccPin(pin,
-                            obtainMessage(EVENT_PINPUK_DONE, onComplete));
-    }
-
-    public void supplyPuk (String puk, String newPin, Message onComplete) {
-        phone.mCM.supplyIccPuk(puk, newPin,
-                        obtainMessage(EVENT_PINPUK_DONE, onComplete));
-    }
-    public void supplyPin2 (String pin2, Message onComplete) {
-        phone.mCM.supplyIccPin2(pin2,
-                        obtainMessage(EVENT_PINPUK_DONE, onComplete));
-    }
-    public void supplyPuk2 (String puk2, String newPin2, Message onComplete) {
-        phone.mCM.supplyIccPuk2(puk2, newPin2,
-                obtainMessage(EVENT_PINPUK_DONE, onComplete));
-    }
-
-    public void supplyNetworkDepersonalization (String pin, Message onComplete) {
-        if(DBG) log("Network Despersonalization: " + pin);
-        phone.mCM.supplyNetworkDepersonalization(pin,
-                        obtainMessage(EVENT_PINPUK_DONE, onComplete));
-    }
-
-    public boolean getIccLockEnabled() {
-       return mSimPinLocked;
-    }
-
-    public boolean getIccFdnEnabled() {
-       return mSimFdnEnabled;
-    }
-
-    public void setIccLockEnabled (boolean enabled,
-            String password, Message onComplete) {
-        int serviceClassX;
-        serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE +
-                CommandsInterface.SERVICE_CLASS_DATA +
-                CommandsInterface.SERVICE_CLASS_FAX;
-
-        mDesiredPinLocked = enabled;
-
-        phone.mCM.setFacilityLock(CommandsInterface.CB_FACILITY_BA_SIM,
-                enabled, password, serviceClassX,
-                obtainMessage(EVENT_CHANGE_FACILITY_LOCK_DONE, onComplete));
-    }
-
-    public void setIccFdnEnabled (boolean enabled,
-            String password, Message onComplete) {
-        int serviceClassX;
-        serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE +
-                CommandsInterface.SERVICE_CLASS_DATA +
-                CommandsInterface.SERVICE_CLASS_FAX +
-                CommandsInterface.SERVICE_CLASS_SMS;
-
-        mDesiredFdnEnabled = enabled;
-
-        phone.mCM.setFacilityLock(CommandsInterface.CB_FACILITY_BA_FD,
-                enabled, password, serviceClassX,
-                obtainMessage(EVENT_CHANGE_FACILITY_FDN_DONE, onComplete));
-    }
-
-    public void changeIccLockPassword(String oldPassword, String newPassword,
-            Message onComplete) {
-        if(DBG) log("Change Pin1 old: " + oldPassword + " new: " + newPassword);
-        phone.mCM.changeIccPin(oldPassword, newPassword,
-                obtainMessage(EVENT_CHANGE_SIM_PASSWORD_DONE, onComplete));
-
-    }
-
-    public void changeIccFdnPassword(String oldPassword, String newPassword,
-            Message onComplete) {
-        if(DBG) log("Change Pin2 old: " + oldPassword + " new: " + newPassword);
-        phone.mCM.changeIccPin2(oldPassword, newPassword,
-                obtainMessage(EVENT_CHANGE_SIM_PASSWORD_DONE, onComplete));
-
-    }
-
-    public String getServiceProviderName () {
-        return phone.mSIMRecords.getServiceProviderName();
-    }
-
-    //***** Handler implementation
     @Override
-    public void handleMessage(Message msg){
-        AsyncResult ar;
-        int serviceClassX;
-
-        serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE +
-                        CommandsInterface.SERVICE_CLASS_DATA +
-                        CommandsInterface.SERVICE_CLASS_FAX;
-
-        switch (msg.what) {
-            case EVENT_RADIO_OFF_OR_NOT_AVAILABLE:
-                status = null;
-                updateStateProperty();
-                broadcastSimStateChangedIntent(SimCard.INTENT_VALUE_ICC_NOT_READY, null);
-                break;
-            case EVENT_SIM_READY:
-                //TODO: put facility read in SIM_READY now, maybe in REG_NW
-                phone.mCM.getIccStatus(obtainMessage(EVENT_GET_SIM_STATUS_DONE));
-                phone.mCM.queryFacilityLock (
-                        CommandsInterface.CB_FACILITY_BA_SIM, "", serviceClassX,
-                        obtainMessage(EVENT_QUERY_FACILITY_LOCK_DONE));
-                phone.mCM.queryFacilityLock (
-                        CommandsInterface.CB_FACILITY_BA_FD, "", serviceClassX,
-                        obtainMessage(EVENT_QUERY_FACILITY_FDN_DONE));
-                break;
-            case EVENT_SIM_LOCKED_OR_ABSENT:
-                phone.mCM.getIccStatus(obtainMessage(EVENT_GET_SIM_STATUS_DONE));
-                phone.mCM.queryFacilityLock (
-                        CommandsInterface.CB_FACILITY_BA_SIM, "", serviceClassX,
-                        obtainMessage(EVENT_QUERY_FACILITY_LOCK_DONE));
-                break;
-            case EVENT_GET_SIM_STATUS_DONE:
-                ar = (AsyncResult)msg.obj;
-
-                getSimStatusDone(ar);
-                break;
-            case EVENT_PINPUK_DONE:
-                // a PIN/PUK/PIN2/PUK2/Network Personalization
-                // request has completed. ar.userObj is the response Message
-                // Repoll before returning
-                ar = (AsyncResult)msg.obj;
-                // TODO should abstract these exceptions
-                AsyncResult.forMessage(((Message)ar.userObj)).exception
-                                                    = ar.exception;
-                phone.mCM.getIccStatus(
-                    obtainMessage(EVENT_REPOLL_STATUS_DONE, ar.userObj));
-                break;
-            case EVENT_REPOLL_STATUS_DONE:
-                // Finished repolling status after PIN operation
-                // ar.userObj is the response messaeg
-                // ar.userObj.obj is already an AsyncResult with an
-                // appropriate exception filled in if applicable
-
-                ar = (AsyncResult)msg.obj;
-                getSimStatusDone(ar);
-                ((Message)ar.userObj).sendToTarget();
-                break;
-            case EVENT_QUERY_FACILITY_LOCK_DONE:
-                ar = (AsyncResult)msg.obj;
-                onQueryFacilityLock(ar);
-                break;
-            case EVENT_QUERY_FACILITY_FDN_DONE:
-                ar = (AsyncResult)msg.obj;
-                onQueryFdnEnabled(ar);
-                break;
-            case EVENT_CHANGE_FACILITY_LOCK_DONE:
-                ar = (AsyncResult)msg.obj;
-                if (ar.exception == null) {
-                    mSimPinLocked = mDesiredPinLocked;
-                    if (DBG) log( "EVENT_CHANGE_FACILITY_LOCK_DONE: " +
-                            "mSimPinLocked= " + mSimPinLocked);
-                } else {
-                    Log.e(LOG_TAG, "Error change facility lock with exception "
-                        + ar.exception);
-                }
-                AsyncResult.forMessage(((Message)ar.userObj)).exception
-                                                    = ar.exception;
-                ((Message)ar.userObj).sendToTarget();
-                break;
-            case EVENT_CHANGE_FACILITY_FDN_DONE:
-                ar = (AsyncResult)msg.obj;
-
-                if (ar.exception == null) {
-                    mSimFdnEnabled = mDesiredFdnEnabled;
-                    if (DBG) log("EVENT_CHANGE_FACILITY_FDN_DONE: " +
-                            "mSimFdnEnabled=" + mSimFdnEnabled);
-                } else {
-                    Log.e(LOG_TAG, "Error change facility fdn with exception "
-                            + ar.exception);
-                }
-                AsyncResult.forMessage(((Message)ar.userObj)).exception
-                                                    = ar.exception;
-                ((Message)ar.userObj).sendToTarget();
-                break;
-            case EVENT_CHANGE_SIM_PASSWORD_DONE:
-                ar = (AsyncResult)msg.obj;
-                if(ar.exception != null) {
-                    Log.e(LOG_TAG, "Error in change sim password with exception"
-                        + ar.exception);
-                }
-                AsyncResult.forMessage(((Message)ar.userObj)).exception
-                                                    = ar.exception;
-                ((Message)ar.userObj).sendToTarget();
-                break;
-            default:
-                Log.e(LOG_TAG, "[GsmSimCard] Unknown Event " + msg.what);
-        }
-    }
-
-
-    //***** Private methods
-
-    /**
-     * Interperate EVENT_QUERY_FACILITY_LOCK_DONE
-     * @param ar is asyncResult of Query_Facility_Locked
-     */
-    private void onQueryFacilityLock(AsyncResult ar) {
-        if(ar.exception != null) {
-            if (DBG) log("Error in querying facility lock:" + ar.exception);
-            return;
-        }
-
-        int[] ints = (int[])ar.result;
-        if(ints.length != 0) {
-            mSimPinLocked = (0!=ints[0]);
-            if(DBG) log("Query facility lock : "  + mSimPinLocked);
-        } else {
-            Log.e(LOG_TAG, "[GsmSimCard] Bogus facility lock response");
-        }
-    }
-
-    /**
-     * Interperate EVENT_QUERY_FACILITY_LOCK_DONE
-     * @param ar is asyncResult of Query_Facility_Locked
-     */
-    private void onQueryFdnEnabled(AsyncResult ar) {
-        if(ar.exception != null) {
-            if(DBG) log("Error in querying facility lock:" + ar.exception);
-            return;
-        }
-
-        int[] ints = (int[])ar.result;
-        if(ints.length != 0) {
-            mSimFdnEnabled = (0!=ints[0]);
-            if(DBG) log("Query facility lock : "  + mSimFdnEnabled);
-        } else {
-            Log.e(LOG_TAG, "[GsmSimCard] Bogus facility lock response");
-        }
-    }
-
-    private void
-    getSimStatusDone(AsyncResult ar) {
-        if (ar.exception != null) {
-            Log.e(LOG_TAG,"Error getting ICC status. "
-                    + "RIL_REQUEST_GET_ICC_STATUS should "
-                    + "never return an error", ar.exception);
-            return;
-        }
-
-        CommandsInterface.IccStatus newStatus
-            = (CommandsInterface.IccStatus)  ar.result;
-
-        handleSimStatus(newStatus);
-    }
-
-    private void
-    handleSimStatus(CommandsInterface.IccStatus newStatus) {
-        boolean transitionedIntoPinLocked;
-        boolean transitionedIntoAbsent;
-        boolean transitionedIntoNetworkLocked;
-
-        SimCard.State oldState, newState;
-
-        oldState = getState();
-        status = newStatus;
-        newState = getState();
-
-        updateStateProperty();
-
-        transitionedIntoPinLocked = (
-                 (oldState != State.PIN_REQUIRED && newState == State.PIN_REQUIRED)
-              || (oldState != State.PUK_REQUIRED && newState == State.PUK_REQUIRED));
-        transitionedIntoAbsent = (oldState != State.ABSENT && newState == State.ABSENT);
-        transitionedIntoNetworkLocked = (oldState != State.NETWORK_LOCKED
-                && newState == State.NETWORK_LOCKED);
-
-        if (transitionedIntoPinLocked) {
-            if(DBG) log("Notify SIM pin or puk locked.");
-            pinLockedRegistrants.notifyRegistrants();
-            broadcastSimStateChangedIntent(SimCard.INTENT_VALUE_ICC_LOCKED,
-                    (newState == State.PIN_REQUIRED) ?
-                       INTENT_VALUE_LOCKED_ON_PIN : INTENT_VALUE_LOCKED_ON_PUK);
-        } else if (transitionedIntoAbsent) {
-            if(DBG) log("Notify SIM missing.");
-            absentRegistrants.notifyRegistrants();
-            broadcastSimStateChangedIntent(SimCard.INTENT_VALUE_ICC_ABSENT, null);
-        } else if (transitionedIntoNetworkLocked) {
-            if(DBG) log("Notify SIM network locked.");
-            networkLockedRegistrants.notifyRegistrants();
-            broadcastSimStateChangedIntent(SimCard.INTENT_VALUE_ICC_LOCKED,
-                  INTENT_VALUE_LOCKED_NETWORK);
-        }
-    }
-
-    public void broadcastSimStateChangedIntent(String value, String reason) {
-        Intent intent = new Intent(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
-        intent.putExtra(Phone.PHONE_NAME_KEY, phone.getPhoneName());
-        intent.putExtra(SimCard.INTENT_KEY_ICC_STATE, value);
-        intent.putExtra(SimCard.INTENT_KEY_LOCKED_REASON, reason);
-        if(DBG) log("Broadcasting intent SIM_STATE_CHANGED_ACTION " +  value
-                + " reason " + reason);
-        ActivityManagerNative.broadcastStickyIntent(intent, READ_PHONE_STATE);
+    public String getServiceProviderName () {
+        return ((GSMPhone)mPhone).mSIMRecords.getServiceProviderName();
     }
 
     public void updateImsiConfiguration(String imsi) {
@@ -494,19 +62,8 @@
             try {
                 ActivityManagerNative.getDefault().updateConfiguration(config);
             } catch (RemoteException e) {
+                Log.e(mLogTag, "[SimCard] Remote Exception when updating imsi configuration");
             }
         }
     }
-
-    private void
-    updateStateProperty() {
-        phone.setSystemProperty(
-            TelephonyProperties.PROPERTY_SIM_STATE,
-            getState().toString());
-    }
-
-    private void log(String msg) {
-        Log.d(LOG_TAG, "[GsmSimCard] " + msg);
-    }
 }
-
diff --git a/telephony/java/com/android/internal/telephony/test/SimulatedCommands.java b/telephony/java/com/android/internal/telephony/test/SimulatedCommands.java
index f71ea48..be5b842 100644
--- a/telephony/java/com/android/internal/telephony/test/SimulatedCommands.java
+++ b/telephony/java/com/android/internal/telephony/test/SimulatedCommands.java
@@ -27,10 +27,11 @@
 import com.android.internal.telephony.CommandException;
 import com.android.internal.telephony.CommandsInterface;
 import com.android.internal.telephony.DataCallState;
+import com.android.internal.telephony.IccCard;
+import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.gsm.CallFailCause;
 import com.android.internal.telephony.gsm.SmsBroadcastConfigInfo;
 import com.android.internal.telephony.gsm.SuppServiceNotification;
-import com.android.internal.telephony.Phone;
 
 import java.util.ArrayList;
 
@@ -103,39 +104,8 @@
 
     //***** CommandsInterface implementation
 
-    public void getIccStatus(Message result) {
-        switch (mState) {
-            case SIM_READY:
-                resultSuccess(result, IccStatus.ICC_READY);
-                break;
-
-            case SIM_LOCKED_OR_ABSENT:
-                returnSimLockedStatus(result);
-                break;
-
-            default:
-                resultSuccess(result, IccStatus.ICC_NOT_READY);
-                break;
-        }
-    }
-
-    private void returnSimLockedStatus(Message result) {
-        switch (mSimLockedState) {
-            case REQUIRE_PIN:
-                Log.i(LOG_TAG, "[SimCmd] returnSimLockedStatus: ICC_PIN");
-                resultSuccess(result, IccStatus.ICC_PIN);
-                break;
-
-            case REQUIRE_PUK:
-                Log.i(LOG_TAG, "[SimCmd] returnSimLockedStatus: ICC_PUK");
-                resultSuccess(result, IccStatus.ICC_PUK);
-                break;
-
-            default:
-                Log.i(LOG_TAG,
-                        "[SimCmd] returnSimLockedStatus: mSimLockedState==NONE !?");
-                break;
-        }
+    public void getIccCardStatus(Message result) {
+        unimplemented(result);
     }
 
     public void supplyIccPin(String pin, Message result)  {
diff --git a/test-runner/android/test/IsolatedContext.java b/test-runner/android/test/IsolatedContext.java
index 2866666..4bd9528 100644
--- a/test-runner/android/test/IsolatedContext.java
+++ b/test-runner/android/test/IsolatedContext.java
@@ -2,6 +2,8 @@
 
 import com.google.android.collect.Lists;
 
+import android.accounts.AccountManager;
+import android.accounts.OnAccountsUpdatedListener;
 import android.content.ContextWrapper;
 import android.content.ContentResolver;
 import android.content.Intent;
@@ -11,8 +13,11 @@
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.net.Uri;
+import android.os.Handler;
+import android.os.Looper;
 
 import java.util.List;
+import java.io.File;
 
 /**
      * A mock context which prevents its users from talking to the rest of the device while
@@ -21,6 +26,7 @@
 public class IsolatedContext extends ContextWrapper {
 
     private ContentResolver mResolver;
+    private final MockAccountManager mMockAccountManager;
 
     private List<Intent> mBroadcastIntents = Lists.newArrayList();
 
@@ -28,6 +34,7 @@
             ContentResolver resolver, Context targetContext) {
         super(targetContext);
         mResolver = resolver;
+        mMockAccountManager = new MockAccountManager();
     }
 
     /** Returns the list of intents that were broadcast since the last call to this method. */
@@ -78,8 +85,25 @@
 
     @Override
     public Object getSystemService(String name) {
-        // No services exist in this context.
+        if (Context.ACCOUNT_SERVICE.equals(name)) {
+            return mMockAccountManager;
+        }
+        // No other services exist in this context.
         return null;
     }
 
+    private class MockAccountManager extends AccountManager {
+        public MockAccountManager() {
+            super(IsolatedContext.this, null /* IAccountManager */, null /* handler */);
+        }
+
+        public void addOnAccountsUpdatedListener(OnAccountsUpdatedListener listener,
+                Handler handler, boolean updateImmediately) {
+            // do nothing
+        }
+    }
+    @Override
+    public File getFilesDir() {
+        return new File("/dev/null");
+    }
 }
diff --git a/test-runner/android/test/RenamingDelegatingContext.java b/test-runner/android/test/RenamingDelegatingContext.java
index 3f64340..0ea43ab 100644
--- a/test-runner/android/test/RenamingDelegatingContext.java
+++ b/test-runner/android/test/RenamingDelegatingContext.java
@@ -6,6 +6,8 @@
 import android.content.ContextWrapper;
 import android.content.ContentProvider;
 import android.database.sqlite.SQLiteDatabase;
+import android.os.FileUtils;
+import android.util.Log;
 
 import java.io.File;
 import java.io.FileInputStream;
@@ -22,6 +24,8 @@
 
     private Context mFileContext;
     private String mFilePrefix = null;
+    private File mCacheDir;
+    private final Object mSync = new Object();
 
     private Set<String> mDatabaseNames = Sets.newHashSet();
     private Set<String> mFileNames = Sets.newHashSet();
@@ -136,6 +140,11 @@
             return false;
         }
     }
+    
+    @Override
+    public File getDatabasePath(String name) {
+        return mFileContext.getDatabasePath(renamedFileName(name));
+    }
 
     @Override
     public String[] databaseList() {
@@ -179,6 +188,32 @@
     public String[] fileList() {
         return mFileNames.toArray(new String[]{});
     }
+    
+    /**
+     * In order to support calls to getCacheDir(), we create a temp cache dir (inside the real
+     * one) and return it instead.  This code is basically getCacheDir(), except it uses the real
+     * cache dir as the parent directory and creates a test cache dir inside that.
+     */
+    @Override
+    public File getCacheDir() {
+        synchronized (mSync) {
+            if (mCacheDir == null) {
+                mCacheDir = new File(mFileContext.getCacheDir(), renamedFileName("cache"));
+            }
+            if (!mCacheDir.exists()) {
+                if(!mCacheDir.mkdirs()) {
+                    Log.w("RenamingDelegatingContext", "Unable to create cache directory");
+                    return null;
+                }
+                FileUtils.setPermissions(
+                        mCacheDir.getPath(),
+                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
+                        -1, -1);
+            }
+        }
+        return mCacheDir;
+    }
+
 
 //    /**
 //     * Given an array of files returns only those whose names indicate that they belong to this
diff --git a/test-runner/android/test/SyncBaseInstrumentation.java b/test-runner/android/test/SyncBaseInstrumentation.java
index 772d75c..a860bb3 100644
--- a/test-runner/android/test/SyncBaseInstrumentation.java
+++ b/test-runner/android/test/SyncBaseInstrumentation.java
@@ -19,9 +19,9 @@
 import android.content.ContentResolver;
 import android.content.Context;
 import android.os.Bundle;
-import android.os.RemoteException;
 import android.os.SystemClock;
 import android.net.Uri;
+import android.accounts.Account;
 
 /**
  * If you would like to test sync a single provider with an
@@ -44,12 +44,12 @@
      * Syncs the specified provider.
      * @throws Exception
      */
-    protected void syncProvider(Uri uri, String account, String authority) throws Exception {
+    protected void syncProvider(Uri uri, String accountName, String authority) throws Exception {
         Bundle extras = new Bundle();
-        extras.putBoolean(ContentResolver.SYNC_EXTRAS_FORCE, true);
-        extras.putString(ContentResolver.SYNC_EXTRAS_ACCOUNT, account);
+        extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
+        Account account = new Account(accountName, "com.google.GAIA");
 
-        mContentResolver.startSync(uri, extras);
+        ContentResolver.requestSync(account, authority, extras);
         long startTimeInMillis = SystemClock.elapsedRealtime();
         long endTimeInMillis = startTimeInMillis + MAX_TIME_FOR_SYNC_IN_MINS * 60000;
 
@@ -64,7 +64,7 @@
                 break;
             }
 
-            if (isSyncActive(account, authority)) {
+            if (ContentResolver.isSyncActive(account, authority)) {
                 counter = 0;
                 continue;
             }
@@ -73,24 +73,7 @@
     }
 
     protected void cancelSyncsandDisableAutoSync() {
-        try {
-            ContentResolver.getContentService().setListenForNetworkTickles(false);
-        } catch (RemoteException e) {
-        }
-        mContentResolver.cancelSync(null);
-    }
-
-    /**
-     * This method tests if any sync is active or not. Sync is considered to be active if the
-     * entry is in either the Pending or Active tables.
-     * @return
-     */
-    private boolean isSyncActive(String account, String authority) {
-        try {
-            return ContentResolver.getContentService().isSyncActive(account,
-                    authority);
-        } catch (RemoteException e) {
-            return false;
-        }
+        ContentResolver.setMasterSyncAutomatically(false);
+        ContentResolver.cancelSync(null /* all accounts */, null /* all authorities */);
     }
 }
diff --git a/test-runner/android/test/mock/MockContentProvider.java b/test-runner/android/test/mock/MockContentProvider.java
index d04fc44..74f86d8 100644
--- a/test-runner/android/test/mock/MockContentProvider.java
+++ b/test-runner/android/test/mock/MockContentProvider.java
@@ -18,7 +18,11 @@
 
 import android.content.ContentValues;
 import android.content.IContentProvider;
-import android.content.ISyncAdapter;
+import android.content.Entity;
+import android.content.EntityIterator;
+import android.content.ContentProviderResult;
+import android.content.ContentProviderOperation;
+import android.content.OperationApplicationException;
 import android.content.res.AssetFileDescriptor;
 import android.database.Cursor;
 import android.database.CursorWindow;
@@ -30,6 +34,7 @@
 import android.os.ParcelFileDescriptor;
 
 import java.io.FileNotFoundException;
+import java.util.ArrayList;
 
 /**
  * Mock implementation of IContentProvider that does nothing.  All methods are non-functional and 
@@ -48,6 +53,10 @@
         return 0;
     }
 
+    public Uri insertEntity(Uri uri, Entity entities) throws RemoteException {
+        throw new UnsupportedOperationException("unimplemented mock method");
+    }
+
     @SuppressWarnings("unused")
     public IBulkCursor bulkQuery(Uri url, String[] projection, String selection,
             String[] selectionArgs, String sortOrder, IContentObserver observer, 
@@ -62,11 +71,6 @@
     }
 
     @SuppressWarnings("unused")
-    public ISyncAdapter getSyncAdapter() throws RemoteException {
-        throw new UnsupportedOperationException("unimplemented mock method");
-    }
-
-    @SuppressWarnings("unused")
     public String getType(Uri url) throws RemoteException {
         throw new UnsupportedOperationException("unimplemented mock method");
     }
@@ -87,19 +91,33 @@
             throws FileNotFoundException {
         throw new UnsupportedOperationException("unimplemented mock method");
     }
-    
+
+    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
+            throws RemoteException, OperationApplicationException {
+        throw new UnsupportedOperationException("unimplemented mock method");
+    }
+
     @SuppressWarnings("unused")
     public Cursor query(Uri url, String[] projection, String selection, String[] selectionArgs,
             String sortOrder) throws RemoteException {
         throw new UnsupportedOperationException("unimplemented mock method");
     }
 
+    public EntityIterator queryEntities(Uri url, String selection, String[] selectionArgs,
+            String sortOrder) throws RemoteException {
+        throw new UnsupportedOperationException("unimplemented mock method");
+    }
+
     @SuppressWarnings("unused")
     public int update(Uri url, ContentValues values, String selection, String[] selectionArgs)
             throws RemoteException {
         throw new UnsupportedOperationException("unimplemented mock method");
     }
 
+    public int updateEntity(Uri uri, Entity entity) throws RemoteException {
+        throw new UnsupportedOperationException("unimplemented mock method");
+    }
+
     public IBinder asBinder() {
         throw new UnsupportedOperationException("unimplemented mock method");
     }
diff --git a/test-runner/android/test/mock/MockPackageManager.java b/test-runner/android/test/mock/MockPackageManager.java
index d5cd6ef..63a177e 100644
--- a/test-runner/android/test/mock/MockPackageManager.java
+++ b/test-runner/android/test/mock/MockPackageManager.java
@@ -292,9 +292,6 @@
         throw new UnsupportedOperationException();
     }
     
-    /**
-     * @hide - to match hiding in superclass
-     */
     @Override
     public String getInstallerPackageName(String packageName) {
         throw new UnsupportedOperationException();
diff --git a/tests/AndroidTests/AndroidManifest.xml b/tests/AndroidTests/AndroidManifest.xml
index 845f547..d94327a 100644
--- a/tests/AndroidTests/AndroidManifest.xml
+++ b/tests/AndroidTests/AndroidManifest.xml
@@ -52,6 +52,7 @@
 
     <uses-permission android:name="com.android.unit_tests.permission.TEST_GRANTED" />
 
+    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
     <uses-permission android:name="com.google.android.googleapps.permission.GOOGLE_AUTH" />
     <uses-permission android:name="com.google.android.googleapps.permission.GOOGLE_AUTH.ALL_SERVICES" />
     <uses-permission android:name="com.google.android.googleapps.permission.ACCESS_GOOGLE_PASSWORD" />
diff --git a/tests/AndroidTests/res/raw/v21_simple_1.vcf b/tests/AndroidTests/res/raw/v21_simple_1.vcf
new file mode 100644
index 0000000..6aabb4c
--- /dev/null
+++ b/tests/AndroidTests/res/raw/v21_simple_1.vcf
@@ -0,0 +1,3 @@
+BEGIN:VCARD

+N:Ando;Roid;

+END:VCARD

diff --git a/tests/AndroidTests/res/raw/v21_simple_2.vcf b/tests/AndroidTests/res/raw/v21_simple_2.vcf
new file mode 100644
index 0000000..f0d5ab5
--- /dev/null
+++ b/tests/AndroidTests/res/raw/v21_simple_2.vcf
@@ -0,0 +1,3 @@
+BEGIN:VCARD

+FN:Ando Roid

+END:VCARD

diff --git a/tests/AndroidTests/res/raw/v21_simple.vcf b/tests/AndroidTests/res/raw/v21_simple_3.vcf
similarity index 100%
rename from tests/AndroidTests/res/raw/v21_simple.vcf
rename to tests/AndroidTests/res/raw/v21_simple_3.vcf
diff --git a/tests/AndroidTests/run_test.sh b/tests/AndroidTests/run_test.sh
index 7ada698..bc06b7e 100755
--- a/tests/AndroidTests/run_test.sh
+++ b/tests/AndroidTests/run_test.sh
@@ -1,4 +1,4 @@
 framework=/system/framework
 bpath=$framework/core.jar:$framework/ext.jar:$framework/framework.jar:$framework/android.test.runner.jar
-adb shell exec dalvikvm  -Xbootclasspath:$bpath -cp /system/app/AndroidTests.apk:/data/app/com.android.unit_tests.apk \
+adb shell exec dalvikvm  -Xbootclasspath:$bpath -cp /system/app/AndroidTests.apk:/data/app/com.android.unit_tests.apk:/data/app/AndroidTests.apk \
       com.android.internal.util.WithFramework junit.textui.TestRunner $*
diff --git a/tests/AndroidTests/src/com/android/unit_tests/accounts/AccountManagerServiceTest.java b/tests/AndroidTests/src/com/android/unit_tests/accounts/AccountManagerServiceTest.java
new file mode 100644
index 0000000..6b8e1f0
--- /dev/null
+++ b/tests/AndroidTests/src/com/android/unit_tests/accounts/AccountManagerServiceTest.java
@@ -0,0 +1,181 @@
+/*
+ * 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.
+ */
+
+package com.android.unit_tests.accounts;
+
+import android.test.AndroidTestCase;
+import android.test.RenamingDelegatingContext;
+import android.test.IsolatedContext;
+import android.test.mock.MockContext;
+import android.test.mock.MockContentResolver;
+import android.content.*;
+import android.accounts.Account;
+import android.accounts.AccountManagerService;
+import android.os.Bundle;
+
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Map;
+
+public class AccountManagerServiceTest extends AndroidTestCase {
+    @Override
+    protected void setUp() throws Exception {
+        final String filenamePrefix = "test.";
+        MockContentResolver resolver = new MockContentResolver();
+        RenamingDelegatingContext targetContextWrapper = new RenamingDelegatingContext(
+                new MockContext(), // The context that most methods are delegated to
+                getContext(), // The context that file methods are delegated to
+                filenamePrefix);
+        Context context = new IsolatedContext(resolver, targetContextWrapper);
+        setContext(context);
+    }
+
+    public class AccountSorter implements Comparator<Account> {
+        public int compare(Account object1, Account object2) {
+            if (object1 == object2) return 0;
+            if (object1 == null) return 1;
+            if (object2 == null) return -1;
+            int result = object1.mType.compareTo(object2.mType);
+            if (result != 0) return result;
+            return object1.mName.compareTo(object2.mName);
+        }
+    }
+
+    public void testCheckAddAccount() throws Exception {
+        AccountManagerService ams = new AccountManagerService(getContext());
+        Account a11 = new Account("account1", "type1");
+        Account a21 = new Account("account2", "type1");
+        Account a31 = new Account("account3", "type1");
+        Account a12 = new Account("account1", "type2");
+        Account a22 = new Account("account2", "type2");
+        Account a32 = new Account("account3", "type2");
+        assertTrue(ams.addAccount(a11, "p11", null));
+        assertTrue(ams.addAccount(a12, "p12", null));
+        assertTrue(ams.addAccount(a21, "p21", null));
+        assertTrue(ams.addAccount(a22, "p22", null));
+        assertTrue(ams.addAccount(a31, "p31", null));
+        assertTrue(ams.addAccount(a32, "p32", null));
+
+        assertFalse("duplicate account insertion should fail", ams.addAccount(a32, "p", null));
+
+        Account[] accounts = ams.getAccounts();
+        Arrays.sort(accounts, new AccountSorter());
+        assertEquals(6, accounts.length);
+        assertEquals(a11, accounts[0]);
+        assertEquals(a21, accounts[1]);
+        assertEquals(a31, accounts[2]);
+        assertEquals(a12, accounts[3]);
+        assertEquals(a22, accounts[4]);
+        assertEquals(a32, accounts[5]);
+
+        accounts = ams.getAccountsByType("type1" );
+        Arrays.sort(accounts, new AccountSorter());
+        assertEquals(3, accounts.length);
+        assertEquals(a11, accounts[0]);
+        assertEquals(a21, accounts[1]);
+        assertEquals(a31, accounts[2]);
+
+        ams.removeAccount(a21);
+
+        accounts = ams.getAccountsByType("type1" );
+        Arrays.sort(accounts, new AccountSorter());
+        assertEquals(2, accounts.length);
+        assertEquals(a11, accounts[0]);
+        assertEquals(a31, accounts[1]);
+    }
+
+    public void testPasswords() throws Exception {
+        AccountManagerService ams = new AccountManagerService(getContext());
+        Account a11 = new Account("account1", "type1");
+        Account a12 = new Account("account1", "type2");
+        assertTrue(ams.addAccount(a11, "p11", null));
+        assertTrue(ams.addAccount(a12, "p12", null));
+
+        assertEquals("p11", ams.getPassword(a11));
+        assertEquals("p12", ams.getPassword(a12));
+
+        ams.setPassword(a11, "p11b");
+
+        assertEquals("p11b", ams.getPassword(a11));
+        assertEquals("p12", ams.getPassword(a12));
+    }
+
+    public void testUserdata() throws Exception {
+        AccountManagerService ams = new AccountManagerService(getContext());
+        Account a11 = new Account("account1", "type1");
+        Bundle u11 = new Bundle();
+        u11.putString("a", "a_a11");
+        u11.putString("b", "b_a11");
+        u11.putString("c", "c_a11");
+        Account a12 = new Account("account1", "type2");
+        Bundle u12 = new Bundle();
+        u12.putString("a", "a_a12");
+        u12.putString("b", "b_a12");
+        u12.putString("c", "c_a12");
+        assertTrue(ams.addAccount(a11, "p11", u11));
+        assertTrue(ams.addAccount(a12, "p12", u12));
+
+        assertEquals("a_a11", ams.getUserData(a11, "a"));
+        assertEquals("b_a11", ams.getUserData(a11, "b"));
+        assertEquals("c_a11", ams.getUserData(a11, "c"));
+        assertEquals("a_a12", ams.getUserData(a12, "a"));
+        assertEquals("b_a12", ams.getUserData(a12, "b"));
+        assertEquals("c_a12", ams.getUserData(a12, "c"));
+
+        ams.setUserData(a11, "b", "b_a11b");
+
+        assertEquals("a_a11", ams.getUserData(a11, "a"));
+        assertEquals("b_a11b", ams.getUserData(a11, "b"));
+        assertEquals("c_a11", ams.getUserData(a11, "c"));
+        assertEquals("a_a12", ams.getUserData(a12, "a"));
+        assertEquals("b_a12", ams.getUserData(a12, "b"));
+        assertEquals("c_a12", ams.getUserData(a12, "c"));
+    }
+
+    public void testAuthtokens() throws Exception {
+        AccountManagerService ams = new AccountManagerService(getContext());
+        Account a11 = new Account("account1", "type1");
+        Account a12 = new Account("account1", "type2");
+        assertTrue(ams.addAccount(a11, "p11", null));
+        assertTrue(ams.addAccount(a12, "p12", null));
+
+        ams.setAuthToken(a11, "att1", "a11_att1");
+        ams.setAuthToken(a11, "att2", "a11_att2");
+        ams.setAuthToken(a11, "att3", "a11_att3");
+        ams.setAuthToken(a12, "att1", "a12_att1");
+        ams.setAuthToken(a12, "att2", "a12_att2");
+        ams.setAuthToken(a12, "att3", "a12_att3");
+
+        assertEquals("a11_att1", ams.peekAuthToken(a11, "att1"));
+        assertEquals("a11_att2", ams.peekAuthToken(a11, "att2"));
+        assertEquals("a11_att3", ams.peekAuthToken(a11, "att3"));
+        assertEquals("a12_att1", ams.peekAuthToken(a12, "att1"));
+        assertEquals("a12_att2", ams.peekAuthToken(a12, "att2"));
+        assertEquals("a12_att3", ams.peekAuthToken(a12, "att3"));
+
+        ams.setAuthToken(a11, "att3", "a11_att3b");
+        ams.invalidateAuthToken(a12.mType, "a12_att2");
+
+        assertEquals("a11_att1", ams.peekAuthToken(a11, "att1"));
+        assertEquals("a11_att2", ams.peekAuthToken(a11, "att2"));
+        assertEquals("a11_att3b", ams.peekAuthToken(a11, "att3"));
+        assertEquals("a12_att1", ams.peekAuthToken(a12, "att1"));
+        assertNull(ams.peekAuthToken(a12, "att2"));
+        assertEquals("a12_att3", ams.peekAuthToken(a12, "att3"));
+
+        assertNull(ams.readAuthTokenFromDatabase(a12, "att2"));
+    }
+}
\ No newline at end of file
diff --git a/tests/AndroidTests/src/com/android/unit_tests/vcard/PropertyNode.java b/tests/AndroidTests/src/com/android/unit_tests/vcard/PropertyNode.java
new file mode 100644
index 0000000..0ee74df
--- /dev/null
+++ b/tests/AndroidTests/src/com/android/unit_tests/vcard/PropertyNode.java
@@ -0,0 +1,322 @@
+/*
+ * 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.
+ */
+package com.android.unit_tests.vcard;
+
+import android.content.ContentValues;
+
+import org.apache.commons.codec.binary.Base64;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.Map.Entry;
+import java.util.regex.Pattern;
+
+/**
+ * @hide old class just for test
+ */
+public class PropertyNode {
+    public String propName;
+    public String propValue;
+    public List<String> propValue_vector;
+
+    /** Store value as byte[],after decode.
+     * Used when propValue is encoded by something like BASE64, QUOTED-PRINTABLE, etc.
+     */
+    public byte[] propValue_bytes;
+
+    /** param store: key=paramType, value=paramValue
+     * Note that currently PropertyNode class does not support multiple param-values
+     * defined in vCard 3.0 (See also RFC 2426). multiple-values are stored as
+     * one String value like "A,B", not ["A", "B"]...
+     * TODO: fix this. 
+     */
+    public ContentValues paramMap;
+
+    /** Only for TYPE=??? param store. */
+    public Set<String> paramMap_TYPE;
+
+    /** Store group values. Used only in VCard. */
+    public Set<String> propGroupSet;
+    
+    public PropertyNode() {
+        propName = "";
+        propValue = "";
+        propValue_vector = new ArrayList<String>();
+        paramMap = new ContentValues();
+        paramMap_TYPE = new HashSet<String>();
+        propGroupSet = new HashSet<String>();
+    }
+    
+    public PropertyNode(
+            String propName, String propValue, List<String> propValue_vector,
+            byte[] propValue_bytes, ContentValues paramMap, Set<String> paramMap_TYPE,
+            Set<String> propGroupSet) {
+        if (propName != null) {
+            this.propName = propName;
+        } else {
+            this.propName = "";
+        }
+        if (propValue != null) {
+            this.propValue = propValue;
+        } else {
+            this.propValue = "";
+        }
+        if (propValue_vector != null) {
+            this.propValue_vector = propValue_vector;
+        } else {
+            this.propValue_vector = new ArrayList<String>();
+        }
+        this.propValue_bytes = propValue_bytes;
+        if (paramMap != null) {
+            this.paramMap = paramMap;
+        } else {
+            this.paramMap = new ContentValues();
+        }
+        if (paramMap_TYPE != null) {
+            this.paramMap_TYPE = paramMap_TYPE;
+        } else {
+            this.paramMap_TYPE = new HashSet<String>();
+        }
+        if (propGroupSet != null) {
+            this.propGroupSet = propGroupSet;
+        } else {
+            this.propGroupSet = new HashSet<String>();
+        }
+    }
+    
+    @Override
+    public boolean equals(Object obj) {
+        if (!(obj instanceof PropertyNode)) {
+            return false;
+        }
+        
+        PropertyNode node = (PropertyNode)obj;
+        
+        if (propName == null || !propName.equals(node.propName)) {
+            return false;
+        } else if (!paramMap.equals(node.paramMap)) {
+            return false;
+        } else if (!paramMap_TYPE.equals(node.paramMap_TYPE)) {
+            return false;
+        } else if (!propGroupSet.equals(node.propGroupSet)) {
+            return false;
+        }
+        
+        if (propValue_bytes != null && Arrays.equals(propValue_bytes, node.propValue_bytes)) {
+            return true;
+        } else {
+            // Log.d("@@@", propValue + ", " + node.propValue);
+            if (!propValue.equals(node.propValue)) {
+                return false;
+            }
+
+            // The value in propValue_vector is not decoded even if it should be
+            // decoded by BASE64 or QUOTED-PRINTABLE. When the size of propValue_vector
+            // is 1, the encoded value is stored in propValue, so we do not have to
+            // check it.
+            return (propValue_vector.equals(node.propValue_vector) ||
+                    propValue_vector.size() == 1 ||
+                    node.propValue_vector.size() == 1);
+        }
+    }
+    
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("propName: ");
+        builder.append(propName);
+        builder.append(", paramMap: ");
+        builder.append(paramMap.toString());
+        builder.append(", propmMap_TYPE: ");
+        builder.append(paramMap_TYPE.toString());
+        builder.append(", propGroupSet: ");
+        builder.append(propGroupSet.toString());
+        if (propValue_vector != null && propValue_vector.size() > 1) {
+            builder.append(", propValue_vector size: ");
+            builder.append(propValue_vector.size());
+        }
+        if (propValue_bytes != null) {
+            builder.append(", propValue_bytes size: ");
+            builder.append(propValue_bytes.length);
+        }
+        builder.append(", propValue: ");
+        builder.append(propValue);
+        return builder.toString();
+    }
+    
+    /**
+     * Encode this object into a string which can be decoded. 
+     */
+    public String encode() {
+        // PropertyNode#toString() is for reading, not for parsing in the future.
+        // We construct appropriate String here.
+        StringBuilder builder = new StringBuilder();
+        if (propName.length() > 0) {
+            builder.append("propName:[");
+            builder.append(propName);
+            builder.append("],");
+        }
+        int size = propGroupSet.size();
+        if (size > 0) {
+            Set<String> set = propGroupSet;
+            builder.append("propGroup:[");
+            int i = 0;
+            for (String group : set) {
+                // We do not need to double quote groups.
+                // group        = 1*(ALPHA / DIGIT / "-")
+                builder.append(group);
+                if (i < size - 1) {
+                    builder.append(",");
+                }
+                i++;
+            }
+            builder.append("],");
+        }
+
+        if (paramMap.size() > 0 || paramMap_TYPE.size() > 0) {
+            ContentValues values = paramMap;
+            builder.append("paramMap:[");
+            size = paramMap.size(); 
+            int i = 0;
+            for (Entry<String, Object> entry : values.valueSet()) {
+                // Assuming param-key does not contain NON-ASCII nor symbols.
+                //
+                // According to vCard 3.0:
+                // param-name   = iana-token / x-name
+                builder.append(entry.getKey());
+
+                // param-value may contain any value including NON-ASCIIs.
+                // We use the following replacing rule.
+                // \ -> \\
+                // , -> \,
+                // In String#replaceAll(), "\\\\" means a single backslash.
+                builder.append("=");
+                builder.append(entry.getValue().toString()
+                        .replaceAll("\\\\", "\\\\\\\\")
+                        .replaceAll(",", "\\\\,"));
+                if (i < size -1) {
+                    builder.append(",");
+                }
+                i++;
+            }
+
+            Set<String> set = paramMap_TYPE;
+            size = paramMap_TYPE.size();
+            if (i > 0 && size > 0) {
+                builder.append(",");
+            }
+            i = 0;
+            for (String type : set) {
+                builder.append("TYPE=");
+                builder.append(type
+                        .replaceAll("\\\\", "\\\\\\\\")
+                        .replaceAll(",", "\\\\,"));
+                if (i < size - 1) {
+                    builder.append(",");
+                }
+                i++;
+            }
+            builder.append("],");
+        }
+
+        size = propValue_vector.size();
+        if (size > 0) {
+            builder.append("propValue:[");
+            List<String> list = propValue_vector;
+            for (int i = 0; i < size; i++) {
+                builder.append(list.get(i)
+                        .replaceAll("\\\\", "\\\\\\\\")
+                        .replaceAll(",", "\\\\,"));
+                if (i < size -1) {
+                    builder.append(",");
+                }
+            }
+            builder.append("],");
+        }
+
+        return builder.toString();
+    }
+
+    public static PropertyNode decode(String encodedString) {
+        PropertyNode propertyNode = new PropertyNode();
+        String trimed = encodedString.trim();
+        if (trimed.length() == 0) {
+            return propertyNode;
+        }
+        String[] elems = trimed.split("],");
+        
+        for (String elem : elems) {
+            int index = elem.indexOf('[');
+            String name = elem.substring(0, index - 1);
+            Pattern pattern = Pattern.compile("(?<!\\\\),");
+            String[] values = pattern.split(elem.substring(index + 1), -1);
+            if (name.equals("propName")) {
+                propertyNode.propName = values[0];
+            } else if (name.equals("propGroupSet")) {
+                for (String value : values) {
+                    propertyNode.propGroupSet.add(value);
+                }
+            } else if (name.equals("paramMap")) {
+                ContentValues paramMap = propertyNode.paramMap;
+                Set<String> paramMap_TYPE = propertyNode.paramMap_TYPE;
+                for (String value : values) {
+                    String[] tmp = value.split("=", 2);
+                    String mapKey = tmp[0];
+                    // \, -> ,
+                    // \\ -> \
+                    // In String#replaceAll(), "\\\\" means a single backslash.
+                    String mapValue =
+                        tmp[1].replaceAll("\\\\,", ",").replaceAll("\\\\\\\\", "\\\\");
+                    if (mapKey.equalsIgnoreCase("TYPE")) {
+                        paramMap_TYPE.add(mapValue);
+                    } else {
+                        paramMap.put(mapKey, mapValue);
+                    }
+                }
+            } else if (name.equals("propValue")) {
+                StringBuilder builder = new StringBuilder();
+                List<String> list = propertyNode.propValue_vector;
+                int length = values.length;
+                for (int i = 0; i < length; i++) {
+                    String normValue = values[i]
+                                              .replaceAll("\\\\,", ",")
+                                              .replaceAll("\\\\\\\\", "\\\\");
+                    list.add(normValue);
+                    builder.append(normValue);
+                    if (i < length - 1) {
+                        builder.append(";");
+                    }
+                }
+                propertyNode.propValue = builder.toString();
+            }
+        }
+        
+        // At this time, QUOTED-PRINTABLE is already decoded to Java String.
+        // We just need to decode BASE64 String to binary.
+        String encoding = propertyNode.paramMap.getAsString("ENCODING");
+        if (encoding != null &&
+                (encoding.equalsIgnoreCase("BASE64") ||
+                        encoding.equalsIgnoreCase("B"))) {
+            propertyNode.propValue_bytes =
+                Base64.decodeBase64(propertyNode.propValue_vector.get(0).getBytes());
+        }
+        
+        return propertyNode;
+    }
+}
diff --git a/tests/AndroidTests/src/com/android/unit_tests/VCardTests.java b/tests/AndroidTests/src/com/android/unit_tests/vcard/VCardTests.java
similarity index 85%
rename from tests/AndroidTests/src/com/android/unit_tests/VCardTests.java
rename to tests/AndroidTests/src/com/android/unit_tests/vcard/VCardTests.java
index b7f562d..af5562ad 100644
--- a/tests/AndroidTests/src/com/android/unit_tests/VCardTests.java
+++ b/tests/AndroidTests/src/com/android/unit_tests/vcard/VCardTests.java
@@ -14,36 +14,132 @@
  * limitations under the License.
  */
 
-package com.android.unit_tests;
+package com.android.unit_tests.vcard;
 
 import android.content.ContentValues;
-import android.syncml.pim.PropertyNode;
-import android.syncml.pim.VDataBuilder;
-import android.syncml.pim.VNode;
-import android.syncml.pim.vcard.VCardException;
-import android.syncml.pim.vcard.VCardParser_V21;
-import android.syncml.pim.vcard.VCardParser_V30;
+import android.pim.vcard.ContactStruct;
+import android.pim.vcard.EntryHandler;
+import android.pim.vcard.VCardBuilder;
+import android.pim.vcard.VCardBuilderCollection;
+import android.pim.vcard.VCardConfig;
+import android.pim.vcard.VCardDataBuilder;
+import android.pim.vcard.VCardParser;
+import android.pim.vcard.VCardParser_V21;
+import android.pim.vcard.VCardParser_V30;
+import android.pim.vcard.exception.VCardException;
 import android.test.AndroidTestCase;
 
+import com.android.unit_tests.R;
+
 import java.io.IOException;
 import java.io.InputStream;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Vector;
+import java.util.List;
+import java.util.Map;
 
 public class VCardTests extends AndroidTestCase {
 
+    // TODO: Use EntityIterator, which is added in Eclair.
+    private static class EntryHolder implements EntryHandler {
+        public List<ContactStruct> contacts = new ArrayList<ContactStruct>();
+        public void onEntryCreated(ContactStruct contactStruct) {
+            contacts.add(contactStruct);
+        }
+        public void onFinal() {
+        }
+    }
+    
+    static void verify(ContactStruct expected, ContactStruct actual) {
+        if (!equalsString(expected.getName(), actual.getName())) {
+            fail(String.format("Names do not equal: \"%s\" != \"%s\"",
+                    expected.getName(), actual.getName()));
+        }
+        if (!equalsString(
+                expected.getPhoneticName(), actual.getPhoneticName())) {
+            fail(String.format("Phonetic names do not equal: \"%s\" != \"%s\"",
+                    expected.getPhoneticName(), actual.getPhoneticName()));
+        }
+        {
+            final byte[] expectedPhotoBytes = expected.getPhotoBytes();
+            final byte[] actualPhotoBytes = actual.getPhotoBytes();
+            if (!((expectedPhotoBytes == null && actualPhotoBytes == null) ||
+                    Arrays.equals(expectedPhotoBytes, actualPhotoBytes))) {
+                fail("photoBytes is not equal.");
+            }
+        }
+        verifyInternal(expected.getNotes(), actual.getNotes(), "notes");
+        verifyInternal(expected.getPhoneList(), actual.getPhoneList(), "phones");
+        verifyInternal(expected.getContactMethodList(), actual.getContactMethodList(),
+                "contact lists");
+        verifyInternal(expected.getOrganizationList(), actual.getOrganizationList(),
+                "organizations");
+        {
+            final Map<String, List<String>> expectedMap =
+                expected.getExtensionMap();
+            final Map<String, List<String>> actualMap =
+                actual.getExtensionMap();
+            if (verifySize((expectedMap == null ? 0 : expectedMap.size()),
+                    (actualMap == null ? 0 : actualMap.size()), "extensions") > 0) {
+                for (String key : expectedMap.keySet()) {
+                    if (!actualMap.containsKey(key)) {
+                        fail(String.format(
+                                "Actual does not have %s extension while expected has",
+                                key));
+                    }
+                    final List<String> expectedList = expectedMap.get(key);
+                    final List<String> actualList = actualMap.get(key);
+                    verifyInternal(expectedList, actualList,
+                            String.format("extension \"%s\"", key));
+                }
+            }
+        }
+    }
+    
+    private static boolean equalsString(String a, String b) {
+        if (a == null || a.length() == 0) {
+            return b == null || b.length() == 0;
+        } else {
+            return a.equals(b);
+        }
+    }
+    
+    private static int verifySize(int expectedSize, int actualSize, String name) {
+        if (expectedSize != actualSize) {
+            fail(String.format("Size of %s is different: %d != %d", 
+                    name, expectedSize, actualSize));
+        }
+        return expectedSize;
+    }
+        
+    private static <T> void verifyInternal(final List<T> expected, final List<T> actual,
+            String name) {
+        if(verifySize((expected == null ? 0 : expected.size()),
+                (actual == null ? 0 : actual.size()), name) > 0) {
+            int size = expected.size();
+            for (int i = 0; i < size; i++) {
+                final T expectedObj = expected.get(i);
+                final T actualObj = actual.get(i);
+                if (!expected.equals(actual)) {
+                    fail(String.format("The %i %s are different: %s != %s",
+                            i, name, expectedObj, actualObj));
+                }
+            }
+        }
+    }
+
     private class PropertyNodesVerifier {
-        private HashMap<String, Vector<PropertyNode>> mPropertyNodeMap;
+        private HashMap<String, ArrayList<PropertyNode>> mPropertyNodeMap;
         public PropertyNodesVerifier(PropertyNode... nodes) {
-            mPropertyNodeMap = new HashMap<String, Vector<PropertyNode>>();
+            mPropertyNodeMap = new HashMap<String, ArrayList<PropertyNode>>();
             for (PropertyNode propertyNode : nodes) {
                 String propName = propertyNode.propName;
-                Vector<PropertyNode> expectedNodes =
+                ArrayList<PropertyNode> expectedNodes =
                     mPropertyNodeMap.get(propName);
                 if (expectedNodes == null) {
-                    expectedNodes = new Vector<PropertyNode>();
+                    expectedNodes = new ArrayList<PropertyNode>();
                     mPropertyNodeMap.put(propName, expectedNodes);
                 }
                 expectedNodes.add(propertyNode);
@@ -53,7 +149,7 @@
         public void verify(VNode vnode) {
             for (PropertyNode propertyNode : vnode.propList) {
                 String propName = propertyNode.propName;
-                Vector<PropertyNode> nodes = mPropertyNodeMap.get(propName);
+                ArrayList<PropertyNode> nodes = mPropertyNodeMap.get(propName);
                 if (nodes == null) {
                     fail("Unexpected propName \"" + propName + "\" exists.");
                 }
@@ -81,8 +177,8 @@
                 }
             }
             if (mPropertyNodeMap.size() != 0) {
-                Vector<String> expectedProps = new Vector<String>();
-                for (Vector<PropertyNode> nodes : mPropertyNodeMap.values()) {
+                ArrayList<String> expectedProps = new ArrayList<String>();
+                for (ArrayList<PropertyNode> nodes : mPropertyNodeMap.values()) {
                     for (PropertyNode node : nodes) {
                         expectedProps.add(node.propName);
                     }
@@ -93,25 +189,82 @@
         }
     }
     
-    public void testV21SimpleCase() throws IOException, VCardException {
-        VCardParser_V21 parser = new VCardParser_V21();
-        VDataBuilder builder = new VDataBuilder();
-        InputStream is = getContext().getResources().openRawResource(R.raw.v21_simple);
+    public void testV21SimpleCase1_1() throws IOException, VCardException {
+        VCardParser parser = new VCardParser_V21();
+        VCardDataBuilder builder = new VCardDataBuilder(VCardConfig.NAME_ORDER_TYPE_ENGLISH);
+        EntryHolder holder = new EntryHolder();
+        builder.addEntryHandler(holder);
+        InputStream is = getContext().getResources().openRawResource(R.raw.v21_simple_1);
         assertEquals(true, parser.parse(is,"ISO-8859-1", builder));
         is.close();
-        assertEquals(1, builder.vNodeList.size());
+        assertEquals(1, holder.contacts.size());
+        verify(new ContactStruct("Roid Ando", null,
+                null, null, null, null, null, null),
+                holder.contacts.get(0));
+    }
+    
+    public void testV21SimpleCase1_2() throws IOException, VCardException {
+        VCardParser parser = new VCardParser_V21();
+        VCardDataBuilder builder = new VCardDataBuilder(VCardConfig.NAME_ORDER_TYPE_JAPANESE);
+        EntryHolder holder = new EntryHolder();
+        builder.addEntryHandler(holder);
+        InputStream is = getContext().getResources().openRawResource(R.raw.v21_simple_1);
+        assertEquals(true, parser.parse(is,"ISO-8859-1", builder));
+        is.close();
+        assertEquals(1, holder.contacts.size());
+        verify(new ContactStruct("Ando Roid", null,
+                null, null, null, null, null, null),
+                holder.contacts.get(0));
+    }
+    
+    public void testV21SimpleCase2() throws IOException, VCardException {
+        VCardParser parser = new VCardParser_V21();
+        VCardDataBuilder builder = new VCardDataBuilder(VCardConfig.NAME_ORDER_TYPE_ENGLISH);
+        EntryHolder holder = new EntryHolder();
+        builder.addEntryHandler(holder);
+        InputStream is = getContext().getResources().openRawResource(R.raw.v21_simple_2);
+        assertEquals(true, parser.parse(is,"ISO-8859-1", builder));
+        is.close();
+        assertEquals(1, holder.contacts.size());
+        verify(new ContactStruct("Ando Roid", null,
+                null, null, null, null, null, null),
+                holder.contacts.get(0));
+    }
+
+    public void testV21SimpleCase3() throws IOException, VCardException {
+        VCardParser parser = new VCardParser_V21();
+        VCardDataBuilder builder1 = new VCardDataBuilder(VCardConfig.NAME_ORDER_TYPE_ENGLISH);
+        EntryHolder holder = new EntryHolder();
+        builder1.addEntryHandler(holder);
+        VNodeBuilder builder2 = new VNodeBuilder();
+        VCardBuilderCollection collection =
+            new VCardBuilderCollection(
+                    new ArrayList<VCardBuilder>(Arrays.asList(builder1, builder2)));
+        InputStream is = getContext().getResources().openRawResource(R.raw.v21_simple_3);
+        assertEquals(true, parser.parse(is,"ISO-8859-1", collection));
+        is.close();
+
+        assertEquals(1, builder2.vNodeList.size());
+        VNode vnode = builder2.vNodeList.get(0); 
         PropertyNodesVerifier verifier = new PropertyNodesVerifier(
                 new PropertyNode("N", "Ando;Roid;",
                         Arrays.asList("Ando", "Roid", ""),
                         null, null, null, null),
                 new PropertyNode("FN", "Ando Roid",
                         null, null, null, null, null));
-        verifier.verify(builder.vNodeList.get(0));
+        verifier.verify(vnode);
+        
+        // FN is prefered.
+        assertEquals(1, holder.contacts.size());
+        ContactStruct actual = holder.contacts.get(0); 
+        verify(new ContactStruct("Ando Roid", null,
+                null, null, null, null, null, null),
+                actual);
     }
-    
+
     public void testV21BackslashCase() throws IOException, VCardException {
         VCardParser_V21 parser = new VCardParser_V21();
-        VDataBuilder builder = new VDataBuilder();
+        VNodeBuilder builder = new VNodeBuilder();
         InputStream is = getContext().getResources().openRawResource(R.raw.v21_backslash);
         assertEquals(true, parser.parse(is,"ISO-8859-1", builder));
         is.close();
@@ -129,7 +282,7 @@
     
     public void testV21ComplicatedCase() throws IOException, VCardException {
         VCardParser_V21 parser = new VCardParser_V21();
-        VDataBuilder builder = new VDataBuilder();
+        VNodeBuilder builder = new VNodeBuilder();
         InputStream is = getContext().getResources().openRawResource(R.raw.v21_complicated);
         assertEquals(true, parser.parse(is,"ISO-8859-1", builder));
         is.close();
@@ -585,7 +738,7 @@
     
     public void testV21Japanese1() throws IOException, VCardException {
         VCardParser_V21 parser = new VCardParser_V21();
-        VDataBuilder builder = new VDataBuilder();
+        VNodeBuilder builder = new VNodeBuilder();
         InputStream is = getContext().getResources().openRawResource(R.raw.v21_japanese_1);
         assertEquals(true, parser.parse(is,"ISO-8859-1", builder));
         is.close();
@@ -616,7 +769,7 @@
     
     public void testV21Japanese2() throws IOException, VCardException {
         VCardParser_V21 parser = new VCardParser_V21();
-        VDataBuilder builder = new VDataBuilder();
+        VNodeBuilder builder = new VNodeBuilder();
         InputStream is = getContext().getResources().openRawResource(R.raw.v21_japanese_2);
         assertEquals(true, parser.parse(is,"ISO-8859-1", builder));
         is.close();
@@ -660,7 +813,7 @@
     
     public void testV21MultipleEntryCase() throws IOException, VCardException {
         VCardParser_V21 parser = new VCardParser_V21();
-        VDataBuilder builder = new VDataBuilder();
+        VNodeBuilder builder = new VNodeBuilder();
         InputStream is = getContext().getResources().openRawResource(R.raw.v21_multiple_entry);
         assertEquals(true, parser.parse(is,"ISO-8859-1", builder));
         is.close();
@@ -741,7 +894,7 @@
     
     public void testV30SimpleCase() throws IOException, VCardException {
         VCardParser_V21 parser = new VCardParser_V30();
-        VDataBuilder builder = new VDataBuilder();
+        VNodeBuilder builder = new VNodeBuilder();
         InputStream is = getContext().getResources().openRawResource(R.raw.v30_simple);
         assertEquals(true, parser.parse(is,"ISO-8859-1", builder));
         is.close();
diff --git a/libs/utils/executablepath_linux.cpp b/tests/AndroidTests/src/com/android/unit_tests/vcard/VNode.java
similarity index 60%
copy from libs/utils/executablepath_linux.cpp
copy to tests/AndroidTests/src/com/android/unit_tests/vcard/VNode.java
index b8d2a3d..3eb827b 100644
--- a/libs/utils/executablepath_linux.cpp
+++ b/tests/AndroidTests/src/com/android/unit_tests/vcard/VNode.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -13,18 +13,18 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+package com.android.unit_tests.vcard;
 
-#include <utils/executablepath.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <limits.h>
-#include <stdio.h>
+import java.util.ArrayList;
 
-void executablepath(char exe[PATH_MAX])
-{
-    char proc[100];
-    sprintf(proc, "/proc/%d/exe", getpid());
-    
-    int err = readlink(proc, exe, PATH_MAX);
+/**
+ * @hide old class. Just for testing
+ */
+public class VNode {
+    public String VName;
+
+    public ArrayList<PropertyNode> propList = new ArrayList<PropertyNode>();
+
+    /** 0:parse over. 1:parsing. */
+    public int parseStatus = 1;
 }
-
diff --git a/tests/AndroidTests/src/com/android/unit_tests/vcard/VNodeBuilder.java b/tests/AndroidTests/src/com/android/unit_tests/vcard/VNodeBuilder.java
new file mode 100644
index 0000000..6d69223
--- /dev/null
+++ b/tests/AndroidTests/src/com/android/unit_tests/vcard/VNodeBuilder.java
@@ -0,0 +1,313 @@
+/*
+ * 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.
+ */
+package com.android.unit_tests.vcard;
+
+import android.content.ContentValues;
+import android.pim.vcard.VCardBuilder;
+import android.pim.vcard.VCardConfig;
+import android.util.CharsetUtils;
+import android.util.Log;
+
+import org.apache.commons.codec.DecoderException;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.codec.net.QuotedPrintableCodec;
+
+import java.io.UnsupportedEncodingException;
+import java.nio.ByteBuffer;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Store the parse result to custom datastruct: VNode, PropertyNode
+ * Maybe several vcard instance, so use vNodeList to store.
+ * VNode: standy by a vcard instance.
+ * PropertyNode: standy by a property line of a card.
+ * @hide old class, just for testing use 
+ */
+public class VNodeBuilder implements VCardBuilder {
+    static private String LOG_TAG = "VDATABuilder"; 
+    
+    /**
+     * If there's no other information available, this class uses this charset for encoding
+     * byte arrays.
+     */
+    static public String TARGET_CHARSET = "UTF-8"; 
+    
+    /** type=VNode */
+    public List<VNode> vNodeList = new ArrayList<VNode>();
+    private int mNodeListPos = 0;
+    private VNode mCurrentVNode;
+    private PropertyNode mCurrentPropNode;
+    private String mCurrentParamType;
+    
+    /**
+     * The charset using which VParser parses the text.
+     */
+    private String mSourceCharset;
+    
+    /**
+     * The charset with which byte array is encoded to String.
+     */
+    private String mTargetCharset;
+    
+    private boolean mStrictLineBreakParsing;
+    
+    public VNodeBuilder() {
+        this(VCardConfig.DEFAULT_CHARSET, TARGET_CHARSET, false);
+    }
+
+    public VNodeBuilder(String charset, boolean strictLineBreakParsing) {
+        this(null, charset, strictLineBreakParsing);
+    }
+    
+    /**
+     * @hide sourceCharset is temporal. 
+     */
+    public VNodeBuilder(String sourceCharset, String targetCharset,
+            boolean strictLineBreakParsing) {
+        if (sourceCharset != null) {
+            mSourceCharset = sourceCharset;
+        } else {
+            mSourceCharset = VCardConfig.DEFAULT_CHARSET;
+        }
+        if (targetCharset != null) {
+            mTargetCharset = targetCharset;
+        } else {
+            mTargetCharset = TARGET_CHARSET;
+        }
+        mStrictLineBreakParsing = strictLineBreakParsing;
+    }
+
+    public void start() {
+    }
+
+    public void end() {
+    }
+
+    // Note: I guess that this code assumes the Record may nest like this:
+    // START:VPOS
+    // ...
+    // START:VPOS2
+    // ...
+    // END:VPOS2
+    // ...
+    // END:VPOS
+    //
+    // However the following code has a bug.
+    // When error occurs after calling startRecord(), the entry which is probably
+    // the cause of the error remains to be in vNodeList, while endRecord() is not called.
+    //
+    // I leave this code as is since I'm not familiar with vcalendar specification.
+    // But I believe we should refactor this code in the future.
+    // Until this, the last entry has to be removed when some error occurs.
+    public void startRecord(String type) {
+        
+        VNode vnode = new VNode();
+        vnode.parseStatus = 1;
+        vnode.VName = type;
+        // I feel this should be done in endRecord(), but it cannot be done because of
+        // the reason above.
+        vNodeList.add(vnode);
+        mNodeListPos = vNodeList.size() - 1;
+        mCurrentVNode = vNodeList.get(mNodeListPos);
+    }
+
+    public void endRecord() {
+        VNode endNode = vNodeList.get(mNodeListPos);
+        endNode.parseStatus = 0;
+        while(mNodeListPos > 0){
+            mNodeListPos--;
+            if((vNodeList.get(mNodeListPos)).parseStatus == 1)
+                break;
+        }
+        mCurrentVNode = vNodeList.get(mNodeListPos);
+    }
+
+    public void startProperty() {
+        mCurrentPropNode = new PropertyNode();
+    }
+
+    public void endProperty() {
+        mCurrentVNode.propList.add(mCurrentPropNode);
+    }
+    
+    public void propertyName(String name) {
+        mCurrentPropNode.propName = name;
+    }
+
+    // Used only in VCard.
+    public void propertyGroup(String group) {
+        mCurrentPropNode.propGroupSet.add(group);
+    }
+    
+    public void propertyParamType(String type) {
+        mCurrentParamType = type;
+    }
+
+    public void propertyParamValue(String value) {
+        if (mCurrentParamType == null ||
+                mCurrentParamType.equalsIgnoreCase("TYPE")) {
+            mCurrentPropNode.paramMap_TYPE.add(value);
+        } else {
+            mCurrentPropNode.paramMap.put(mCurrentParamType, value);
+        }
+
+        mCurrentParamType = null;
+    }
+
+    private String encodeString(String originalString, String targetCharset) {
+        if (mSourceCharset.equalsIgnoreCase(targetCharset)) {
+            return originalString;
+        }
+        Charset charset = Charset.forName(mSourceCharset);
+        ByteBuffer byteBuffer = charset.encode(originalString);
+        // byteBuffer.array() "may" return byte array which is larger than
+        // byteBuffer.remaining(). Here, we keep on the safe side.
+        byte[] bytes = new byte[byteBuffer.remaining()];
+        byteBuffer.get(bytes);
+        try {
+            return new String(bytes, targetCharset);
+        } catch (UnsupportedEncodingException e) {
+            Log.e(LOG_TAG, "Failed to encode: charset=" + targetCharset);
+            return null;
+        }
+    }
+    
+    private String handleOneValue(String value, String targetCharset, String encoding) {
+        if (encoding != null) {
+            if (encoding.equals("BASE64") || encoding.equals("B")) {
+                // Assume BASE64 is used only when the number of values is 1.
+                mCurrentPropNode.propValue_bytes =
+                    Base64.decodeBase64(value.getBytes());
+                return value;
+            } else if (encoding.equals("QUOTED-PRINTABLE")) {
+                String quotedPrintable = value
+                .replaceAll("= ", " ").replaceAll("=\t", "\t");
+                String[] lines;
+                if (mStrictLineBreakParsing) {
+                    lines = quotedPrintable.split("\r\n");
+                } else {
+                    StringBuilder builder = new StringBuilder();
+                    int length = quotedPrintable.length();
+                    ArrayList<String> list = new ArrayList<String>();
+                    for (int i = 0; i < length; i++) {
+                        char ch = quotedPrintable.charAt(i);
+                        if (ch == '\n') {
+                            list.add(builder.toString());
+                            builder = new StringBuilder();
+                        } else if (ch == '\r') {
+                            list.add(builder.toString());
+                            builder = new StringBuilder();
+                            if (i < length - 1) {
+                                char nextCh = quotedPrintable.charAt(i + 1);
+                                if (nextCh == '\n') {
+                                    i++;
+                                }
+                            }
+                        } else {
+                            builder.append(ch);
+                        }
+                    }
+                    String finalLine = builder.toString();
+                    if (finalLine.length() > 0) {
+                        list.add(finalLine);
+                    }
+                    lines = list.toArray(new String[0]);
+                }
+                StringBuilder builder = new StringBuilder();
+                for (String line : lines) {
+                    if (line.endsWith("=")) {
+                        line = line.substring(0, line.length() - 1);
+                    }
+                    builder.append(line);
+                }
+                byte[] bytes;
+                try {
+                    bytes = builder.toString().getBytes(mSourceCharset);
+                } catch (UnsupportedEncodingException e1) {
+                    Log.e(LOG_TAG, "Failed to encode: charset=" + mSourceCharset);
+                    bytes = builder.toString().getBytes();
+                }
+                
+                try {
+                    bytes = QuotedPrintableCodec.decodeQuotedPrintable(bytes);
+                } catch (DecoderException e) {
+                    Log.e(LOG_TAG, "Failed to decode quoted-printable: " + e);
+                    return "";
+                }
+
+                try {
+                    return new String(bytes, targetCharset);
+                } catch (UnsupportedEncodingException e) {
+                    Log.e(LOG_TAG, "Failed to encode: charset=" + targetCharset);
+                    return new String(bytes);
+                }
+            }
+            // Unknown encoding. Fall back to default.
+        }
+        return encodeString(value, targetCharset);
+    }
+    
+    public void propertyValues(List<String> values) {
+        if (values == null || values.size() == 0) {
+            mCurrentPropNode.propValue_bytes = null;
+            mCurrentPropNode.propValue_vector.clear();
+            mCurrentPropNode.propValue_vector.add("");
+            mCurrentPropNode.propValue = "";
+            return;
+        }
+        
+        ContentValues paramMap = mCurrentPropNode.paramMap;
+        
+        String targetCharset = CharsetUtils.nameForDefaultVendor(paramMap.getAsString("CHARSET")); 
+        String encoding = paramMap.getAsString("ENCODING"); 
+        
+        if (targetCharset == null || targetCharset.length() == 0) {
+            targetCharset = mTargetCharset;
+        }
+        
+        for (String value : values) {
+            mCurrentPropNode.propValue_vector.add(
+                    handleOneValue(value, targetCharset, encoding));
+        }
+
+        mCurrentPropNode.propValue = listToString(mCurrentPropNode.propValue_vector);
+    }
+
+    private String listToString(List<String> list){
+        int size = list.size();
+        if (size > 1) {
+            StringBuilder typeListB = new StringBuilder();
+            for (String type : list) {
+                typeListB.append(type).append(";");
+            }
+            int len = typeListB.length();
+            if (len > 0 && typeListB.charAt(len - 1) == ';') {
+                return typeListB.substring(0, len - 1);
+            }
+            return typeListB.toString();
+        } else if (size == 1) {
+            return list.get(0);
+        } else {
+            return "";
+        }
+    }
+    
+    public String getResult(){
+        return null;
+    }
+}
diff --git a/tests/CoreTests/android/content/SyncStorageEngineTest.java b/tests/CoreTests/android/content/SyncStorageEngineTest.java
index dee6e38..533338e 100644
--- a/tests/CoreTests/android/content/SyncStorageEngineTest.java
+++ b/tests/CoreTests/android/content/SyncStorageEngineTest.java
@@ -20,6 +20,7 @@
 import android.test.RenamingDelegatingContext;
 import android.test.mock.MockContext;
 import android.test.mock.MockContentResolver;
+import android.accounts.Account;
 
 public class SyncStorageEngineTest extends AndroidTestCase {
 
@@ -28,7 +29,7 @@
      * correcponding sync is finished. This can happen if the clock changes while we are syncing.
      */
     public void testPurgeActiveSync() throws Exception {
-        final String account = "a@example.com";
+        final Account account = new Account("a@example.com", "example.type");
         final String authority = "testprovider";
 
         MockContentResolver mockResolver = new MockContentResolver();
diff --git a/tests/CoreTests/android/core/RequestAPITest.java b/tests/CoreTests/android/core/RequestAPITest.java
index d89f5ae..94eb23e 100644
--- a/tests/CoreTests/android/core/RequestAPITest.java
+++ b/tests/CoreTests/android/core/RequestAPITest.java
@@ -72,7 +72,7 @@
             RequestHandle handle =
                     mRequestQueue.queueRequest(
                             "http://localhost:8080/test1", "GET", headers, null,
-                            null, 0, false);
+                            null, 0);
 
             handle.waitUntilComplete();
             fail("expected exception not thrown");
@@ -121,7 +121,7 @@
         mTestWebServer.setKeepAlive(false);
         RequestHandle handle = mRequestQueue.queueRequest(
                 "http://localhost:8080/test1", "GET", headers, null,
-                null, 0, false);
+                null, 0);
         handle.waitUntilComplete();
     }
 
@@ -197,7 +197,7 @@
 
         RequestHandle handle = mRequestQueue.queueRequest(
                 "http://localhost:8080/test1", "GET", null, testEventHandler,
-                null, 0, false);
+                null, 0);
 
         Log.d(LOGTAG, "testGet - sent request. Waiting");
         handle.waitUntilComplete();
@@ -231,11 +231,11 @@
 
         RequestHandle handle0 = mRequestQueue.queueRequest(
                 "http://localhost:8080/test1", "GET", null, testEventHandler,
-                null, 0, false);
+                null, 0);
         handle0.waitUntilComplete();
         RequestHandle handle1 = mRequestQueue.queueRequest(
                 "http://localhost:8080/test1", "GET", null, testEventHandler2,
-                null, 0, false);
+                null, 0);
         handle1.waitUntilComplete();
 
         /* It's not correct to use same listener for multiple
@@ -270,7 +270,7 @@
 
         RequestHandle handle = mRequestQueue.queueRequest(
                 "http://localhost:8080/test1", "HEAD", null, testEventHandler,
-                null, 0, false);
+                null, 0);
 
         Log.d(LOGTAG, "testHead - sent request waiting");
         handle.waitUntilComplete();
@@ -297,7 +297,7 @@
 
         RequestHandle handle = mRequestQueue.queueRequest(
                 "http://localhost:8080/test1", "GET", null, testEventHandler,
-                null, 0, false);
+                null, 0);
 
         Log.d(LOGTAG, "testChunked - sent request waiting");
         handle.waitUntilComplete();
@@ -330,7 +330,7 @@
             Log.d(LOGTAG, testName + " start - rq = " + mRequestQueue);
 
             RequestHandle requestHandle = mRequestQueue.queueRequest(
-                    "http://localhost:8080/test1", "GET", null, testEventHandler, null, 0, false);
+                    "http://localhost:8080/test1", "GET", null, testEventHandler, null, 0);
             Log.d(LOGTAG, testName + " - sent request waiting");
 
             requestHandle.waitUntilComplete();
@@ -398,10 +398,10 @@
         leh2.expectHeaders();
 
         RequestHandle handle0 = mRequestQueue.queueRequest(
-                "http://localhost:8080/test1", "GET", null, testEventHandler, null, 0, false);
+                "http://localhost:8080/test1", "GET", null, testEventHandler, null, 0);
         handle0.waitUntilComplete();
         RequestHandle handle1 = mRequestQueue.queueRequest(
-                "http://localhost:8080/test1", "HEAD", null, testEventHandler, null, 0, false);
+                "http://localhost:8080/test1", "HEAD", null, testEventHandler, null, 0);
 
         Log.d(LOGTAG, "testGetAndHead - sent request. Waiting");
         handle1.waitUntilComplete();
@@ -432,7 +432,7 @@
         Log.d(LOGTAG, "testPost start - rq = " + mRequestQueue);
 
         RequestHandle handle = mRequestQueue.queueRequest(
-                "http://localhost:8080/test1", "POST", null, testEventHandler, null, 0, false);
+                "http://localhost:8080/test1", "POST", null, testEventHandler, null, 0);
 
         Log.d(LOGTAG, "testPost - sent request waiting");
         handle.waitUntilComplete();
@@ -470,7 +470,7 @@
         InputStream bodyProvider = new ByteArrayInputStream(mBody.getBytes());
 
         RequestHandle handle = mRequestQueue.queueRequest(
-                "http://localhost:8080/test1", "POST", null, testEventHandler, bodyProvider, bodyLength, false);
+                "http://localhost:8080/test1", "POST", null, testEventHandler, bodyProvider, bodyLength);
 
         Log.d(LOGTAG, "testPostWithData - sent request waiting");
         handle.waitUntilComplete();
diff --git a/tests/CoreTests/com/android/internal/telephony/PhoneNumberUtilsTest.java b/tests/CoreTests/com/android/internal/telephony/PhoneNumberUtilsTest.java
index 577d384..ff73b32 100644
--- a/tests/CoreTests/com/android/internal/telephony/PhoneNumberUtilsTest.java
+++ b/tests/CoreTests/com/android/internal/telephony/PhoneNumberUtilsTest.java
@@ -309,6 +309,11 @@
         number.append("800-55512");
         PhoneNumberUtils.formatNanpNumber(number);
         assertEquals("800-555-12", number.toString());
+
+        number.clear();
+        number.append("46645");
+        PhoneNumberUtils.formatNanpNumber(number);
+        assertEquals("46645", number.toString());
     }
 
     @SmallTest
diff --git a/tests/CoreTests/com/android/internal/telephony/gsm/GSMPhoneTest.java b/tests/CoreTests/com/android/internal/telephony/gsm/GSMPhoneTest.java
index 7107412..b96743a 100644
--- a/tests/CoreTests/com/android/internal/telephony/gsm/GSMPhoneTest.java
+++ b/tests/CoreTests/com/android/internal/telephony/gsm/GSMPhoneTest.java
@@ -81,7 +81,7 @@
         mRadioControl = mGSMTestHandler.getSimulatedCommands();
 
         mHandler = mGSMTestHandler.getHandler();
-        mGSMPhone.registerForPhoneStateChanged(mHandler, EVENT_PHONE_STATE_CHANGED, null);
+        mGSMPhone.registerForPreciseCallStateChanged(mHandler, EVENT_PHONE_STATE_CHANGED, null);
         mGSMPhone.registerForNewRingingConnection(mHandler, EVENT_RINGING, null);
         mGSMPhone.registerForDisconnect(mHandler, EVENT_DISCONNECT, null);
 
@@ -109,7 +109,7 @@
     protected void tearDown() throws Exception {
         mRadioControl.shutdown();
 
-        mGSMPhone.unregisterForPhoneStateChanged(mHandler);
+        mGSMPhone.unregisterForPreciseCallStateChanged(mHandler);
         mGSMPhone.unregisterForNewRingingConnection(mHandler);
         mGSMPhone.unregisterForDisconnect(mHandler);
         mGSMPhone.setOnPostDialCharacter(mHandler, 0, null);
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/CallbackProxy.java b/tests/DumpRenderTree/src/com/android/dumprendertree/CallbackProxy.java
index a389461..97a8b25 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/CallbackProxy.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/CallbackProxy.java
@@ -18,6 +18,7 @@
 
 import android.os.Handler;
 import android.os.Message;
+import android.webkit.WebStorage;
 
 import java.util.HashMap;
 
@@ -25,7 +26,7 @@
     
     private EventSender mEventSender;
     private LayoutTestController mLayoutTestController;
-    
+
     private static final int EVENT_DOM_LOG = 1;
     private static final int EVENT_FIRE_KBD = 2;
     private static final int EVENT_KEY_DOWN_1 = 3;
@@ -57,6 +58,8 @@
     private static final int LAYOUT_SET_WINDOW_KEY = 38;
     private static final int LAYOUT_TEST_REPAINT = 39;
     private static final int LAYOUT_WAIT_UNTIL_DONE = 40;
+    private static final int LAYOUT_DUMP_DATABASE_CALLBACKS = 41;
+    private static final int LAYOUT_SET_CAN_OPEN_WINDOWS = 42;
     
     CallbackProxy(EventSender eventSender, 
             LayoutTestController layoutTestController) {
@@ -190,6 +193,14 @@
         case LAYOUT_WAIT_UNTIL_DONE:
             mLayoutTestController.waitUntilDone();
             break;
+
+        case LAYOUT_DUMP_DATABASE_CALLBACKS:
+            mLayoutTestController.dumpDatabaseCallbacks();
+            break;
+
+        case LAYOUT_SET_CAN_OPEN_WINDOWS:
+            mLayoutTestController.setCanOpenWindows();
+            break;
         }
     }
 
@@ -325,4 +336,20 @@
         obtainMessage(LAYOUT_WAIT_UNTIL_DONE).sendToTarget();
     }
 
+    public void dumpDatabaseCallbacks() {
+        obtainMessage(LAYOUT_DUMP_DATABASE_CALLBACKS).sendToTarget();
+    }
+
+    public void clearAllDatabases() {
+        WebStorage.getInstance().deleteAllData();
+    }
+
+    public void setDatabaseQuota(long quota) {
+        WebStorage.getInstance().setQuotaForOrigin("file://", quota);
+    }
+
+    public void setCanOpenWindows() {
+        obtainMessage(LAYOUT_SET_CAN_OPEN_WINDOWS).sendToTarget();
+    }
+
 }
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java b/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
index 4f162b3..ede5197 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
@@ -83,7 +83,20 @@
     };
         
     static final String [] ignoreTestList = {
-        };
+        // RegExp is exponatal
+        "fast/regex/test1.html",
+        "fast/regex/slow.html",
+        // RegExp is too large, causing OOM
+        "fast/js/regexp-charclass-crash.html",
+        // The Android browser has no notion of private browsing.
+        "storage/private-browsing-readonly.html",
+        "storage/domstorage/localstorage/private-browsing-affects-storage.html",
+        "storage/domstorage/sessionstorage/private-browsing-affects-storage.html",
+        // Android layout tests are stored in "layout_tests". The following two
+        // tests expect "LayoutTests" in their output.
+        "storage/domstorage/localstorage/iframe-events.html",
+        "storage/domstorage/sessionstorage/iframe-events.html"
+    };
     
     static void fillIgnoreResultSet() {
         // need test plugin
@@ -195,11 +208,7 @@
         ignoreResultList.add("fast/loader/local-iFrame-source-from-local.html");
         // extra spacing because iFrames rendered next to each other on Apple
         ignoreResultList.add("fast/loader/opaque-base-url.html");
-        // RegExp is too large, causing OOM
-        ignoreResultList.add("fast/js/regexp-charclass-crash.html");
         ignoreResultList.add("fast/text/plain-text-line-breaks.html");
-        
-        
     }
     
     static void fillBugTable() {
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestController.java b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestController.java
index 6166dd0..e1d802a 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestController.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestController.java
@@ -58,5 +58,8 @@
     public void queueLoad(String Url, String frameTarget);
 
     public void setAcceptsEditing(boolean b);
-	
+
+    // For storage tests
+    public void dumpDatabaseCallbacks();
+    public void setCanOpenWindows();
 }
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java b/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java
index 09f7cbc..48c1e5d 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java
@@ -34,6 +34,7 @@
 import android.webkit.SslErrorHandler;
 import android.webkit.WebChromeClient;
 import android.webkit.WebSettings;
+import android.webkit.WebStorage;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;
 import android.widget.LinearLayout;
@@ -43,6 +44,8 @@
 import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
 import java.util.Vector;
 
 public class TestShellActivity extends Activity implements LayoutTestController {
@@ -88,7 +91,7 @@
     }
 
     public void clearCache() {
-      mWebView.clearCache(true);
+      mWebView.freeMemory();
     }
 
     @Override
@@ -100,48 +103,11 @@
         setContentView(contentView);
 
         mWebView = new WebView(this);
-        mWebView.getSettings().setJavaScriptEnabled(true);
-        mWebView.setWebChromeClient(mChromeClient);
-        mWebView.setWebViewClient(new WebViewClient(){
-
-            @Override
-            public void onPageFinished(WebView view, String url) {
-                Log.v(LOGTAG, "onPageFinished, url=" + url);
-                super.onPageFinished(view, url);
-            }
-
-            @Override
-            public void onPageStarted(WebView view, String url, Bitmap favicon) {
-                Log.v(LOGTAG, "onPageStarted, url=" + url);
-                super.onPageStarted(view, url, favicon);
-            }
-
-            @Override
-            public void onReceivedError(WebView view, int errorCode, String description,
-                    String failingUrl) {
-                Log.v(LOGTAG, "onReceivedError, errorCode=" + errorCode
-                        + ", desc=" + description + ", url=" + failingUrl);
-                super.onReceivedError(view, errorCode, description, failingUrl);
-            }
-
-            @Override
-            public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler,
-                    String host, String realm) {
-                handler.cancel();
-            }
-
-            @Override
-            public void onReceivedSslError(WebView view, SslErrorHandler handler,
-                    SslError error) {
-                handler.proceed();
-            }
-
-        });
         mEventSender = new WebViewEventSender(mWebView);
         mCallbackProxy = new CallbackProxy(mEventSender, this);
 
-        mWebView.addJavascriptInterface(mCallbackProxy, "layoutTestController");
-        mWebView.addJavascriptInterface(mCallbackProxy, "eventSender");
+        setupWebViewForLayoutTests(mWebView, mCallbackProxy);
+
         contentView.addView(mWebView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0f));
 
         mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
@@ -262,8 +228,8 @@
     @Override
     public void onLowMemory() {
         super.onLowMemory();
-        Log.e(LOGTAG, "Low memory, kill self");
-        System.exit(1);
+        Log.e(LOGTAG, "Low memory, clearing caches");
+        mWebView.freeMemory();
     }
 
     // Dump the page
@@ -290,6 +256,12 @@
             if (mDialogStrings != null)
                 os.write(mDialogStrings.toString().getBytes());
             mDialogStrings = null;
+            if (mDatabaseCallbackStrings != null)
+                os.write(mDatabaseCallbackStrings.toString().getBytes());
+            mDatabaseCallbackStrings = null;
+            if (mConsoleMessages != null)
+                os.write(mConsoleMessages.toString().getBytes());
+            mConsoleMessages = null;
             if (webkitData != null)
                 os.write(webkitData.getBytes());
             os.flush();
@@ -438,6 +410,51 @@
         mWebView.invalidate();
     }
 
+    public void dumpDatabaseCallbacks() {
+        Log.v(LOGTAG, "dumpDatabaseCallbacks called.");
+        mDumpDatabaseCallbacks = true;
+    }
+
+    public void setCanOpenWindows() {
+        Log.v(LOGTAG, "setCanOpenWindows called.");
+        mCanOpenWindows = true;
+    }
+
+    private final WebViewClient mViewClient = new WebViewClient(){
+        @Override
+        public void onPageFinished(WebView view, String url) {
+            Log.v(LOGTAG, "onPageFinished, url=" + url);
+            super.onPageFinished(view, url);
+        }
+
+        @Override
+        public void onPageStarted(WebView view, String url, Bitmap favicon) {
+            Log.v(LOGTAG, "onPageStarted, url=" + url);
+            super.onPageStarted(view, url, favicon);
+        }
+
+        @Override
+        public void onReceivedError(WebView view, int errorCode, String description,
+                String failingUrl) {
+            Log.v(LOGTAG, "onReceivedError, errorCode=" + errorCode
+                    + ", desc=" + description + ", url=" + failingUrl);
+            super.onReceivedError(view, errorCode, description, failingUrl);
+        }
+
+        @Override
+        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler,
+                String host, String realm) {
+            handler.cancel();
+        }
+
+        @Override
+        public void onReceivedSslError(WebView view, SslErrorHandler handler,
+                SslError error) {
+            handler.proceed();
+        }
+    };
+
+
     private final WebChromeClient mChromeClient = new WebChromeClient() {
         @Override
         public void onProgressChanged(WebView view, int newProgress) {
@@ -512,6 +529,72 @@
             result.confirm();
             return true;
         }
+
+        @Override
+        public void onExceededDatabaseQuota(String url_str,
+                String databaseIdentifier, long currentQuota,
+                WebStorage.QuotaUpdater callback) {
+            if (mDumpDatabaseCallbacks) {
+                if (mDatabaseCallbackStrings == null) {
+                    mDatabaseCallbackStrings = new StringBuffer();
+                }
+
+                String protocol = "";
+                String host = "";
+                int port = 0;
+
+                try {
+                    URL url = new URL(url_str);
+                    protocol = url.getProtocol();
+                    host = url.getHost();
+                    if (url.getPort() > -1) {
+                        port = url.getPort();
+                    }
+                } catch (MalformedURLException e) {}
+
+                String databaseCallbackString =
+                        "UI DELEGATE DATABASE CALLBACK: " +
+                        "exceededDatabaseQuotaForSecurityOrigin:{" + protocol +
+                        ", " + host + ", " + port + "} database:" +
+                        databaseIdentifier + "\n";
+                Log.v(LOGTAG, "LOG: "+databaseCallbackString);
+                mDatabaseCallbackStrings.append(databaseCallbackString);
+            }
+            // Give 5MB more quota.
+            callback.updateQuota(currentQuota + 1024 * 1024 * 5);
+        }
+
+        @Override
+        public void addMessageToConsole(String message, int lineNumber,
+                String sourceID) {
+            if (mConsoleMessages == null) {
+                mConsoleMessages = new StringBuffer();
+            }
+            String consoleMessage = "CONSOLE MESSAGE: line "
+                    + lineNumber +": "+ message +"\n";
+            mConsoleMessages.append(consoleMessage);
+            Log.v(LOGTAG, "LOG: "+consoleMessage);
+        }
+
+        @Override
+        public boolean onCreateWindow(WebView view, boolean dialog,
+                boolean userGesture, Message resultMsg) {
+            if (!mCanOpenWindows) {
+                return false;
+            }
+
+            // We never display the new window, just create the view and
+            // allow it's content to execute and be recorded by the test
+            // runner.
+
+            WebView newWindowView = new WebView(TestShellActivity.this);
+            setupWebViewForLayoutTests(newWindowView, mCallbackProxy);
+            WebView.WebViewTransport transport =
+                    (WebView.WebViewTransport) resultMsg.obj;
+            transport.setWebView(newWindowView);
+            resultMsg.sendToTarget();
+            return true;
+        }
     };
 
     private void resetTestStatus() {
@@ -520,9 +603,32 @@
         mTimedOut = false;
         mDumpTitleChanges = false;
         mRequestedWebKitData = false;
+        mDumpDatabaseCallbacks = false;
+        mCanOpenWindows = false;
         mEventSender.resetMouse();
     }
 
+    private void setupWebViewForLayoutTests(WebView webview, CallbackProxy callbackProxy) {
+        if (webview == null) {
+            return;
+        }
+
+        WebSettings settings = webview.getSettings();
+        settings.setJavaScriptEnabled(true);
+        settings.setJavaScriptCanOpenWindowsAutomatically(true);
+        settings.setSupportMultipleWindows(true);
+        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
+        settings.setDatabaseEnabled(true);
+        settings.setDatabasePath(getDir("databases",0).getAbsolutePath());
+        settings.setDomStorageEnabled(true);
+
+        webview.addJavascriptInterface(callbackProxy, "layoutTestController");
+        webview.addJavascriptInterface(callbackProxy, "eventSender");
+
+        webview.setWebChromeClient(mChromeClient);
+        webview.setWebViewClient(mViewClient);
+    }
+
     private WebView mWebView;
     private WebViewEventSender mEventSender;
     private AsyncHandler mHandler;
@@ -550,6 +656,10 @@
     private StringBuffer mDialogStrings;
     private boolean mKeepWebHistory;
     private Vector mWebHistory;
+    private boolean mDumpDatabaseCallbacks;
+    private StringBuffer mDatabaseCallbackStrings;
+    private StringBuffer mConsoleMessages;
+    private boolean mCanOpenWindows;
 
     static final String TIMEOUT_STR = "**Test timeout";
 
diff --git a/tests/FrameworkTest/tests/src/android/content/AbstractTableMergerTest.java b/tests/FrameworkTest/tests/src/android/content/AbstractTableMergerTest.java
index aa3d186..42c1e78 100644
--- a/tests/FrameworkTest/tests/src/android/content/AbstractTableMergerTest.java
+++ b/tests/FrameworkTest/tests/src/android/content/AbstractTableMergerTest.java
@@ -8,6 +8,7 @@
 import android.net.Uri;
 import android.test.AndroidTestCase;
 import android.text.TextUtils;
+import android.accounts.Account;
 
 import java.util.ArrayList;
 import java.util.Map;
@@ -26,7 +27,7 @@
     static final Uri TABLE_URI = Uri.withAppendedPath(CONTENT_URI, TABLE_NAME);
     static final Uri DELETED_TABLE_URI = Uri.withAppendedPath(CONTENT_URI, DELETED_TABLE_NAME);
 
-    private final String ACCOUNT = "account@goo.com";
+    private final Account ACCOUNT = new Account("account@goo.com", "example.type");
 
     private final ArrayList<Expectation> mExpectations = Lists.newArrayList();
 
@@ -65,25 +66,31 @@
         mExpectations.clear();
     }
 
-    ContentValues newValues(String data, String syncId, String syncAccount,
+    ContentValues newValues(String data, String syncId, Account syncAccount,
             String syncTime, String syncVersion, Long syncLocalId) {
         ContentValues values = new ContentValues();
         if (data != null) values.put("data", data);
         if (syncTime != null) values.put("_sync_time", syncTime);
         if (syncVersion != null) values.put("_sync_version", syncVersion);
         if (syncId != null) values.put("_sync_id", syncId);
-        if (syncAccount != null) values.put("_sync_account", syncAccount);
+        if (syncAccount != null) {
+            values.put("_sync_account", syncAccount.mName);
+            values.put("_sync_account_type", syncAccount.mType);
+        }
         values.put("_sync_local_id", syncLocalId);
         values.put("_sync_dirty", 0);
         return values;
     }
 
-    ContentValues newDeletedValues(String syncId, String syncAccount, String syncVersion,
+    ContentValues newDeletedValues(String syncId, Account syncAccount, String syncVersion,
             Long syncLocalId) {
         ContentValues values = new ContentValues();
         if (syncVersion != null) values.put("_sync_version", syncVersion);
         if (syncId != null) values.put("_sync_id", syncId);
-        if (syncAccount != null) values.put("_sync_account", syncAccount);
+        if (syncAccount != null) {
+            values.put("_sync_account", syncAccount.mName);
+            values.put("_sync_account_type", syncAccount.mType);
+        }
         if (syncLocalId != null) values.put("_sync_local_id", syncLocalId);
         return values;
     }
@@ -380,6 +387,7 @@
                     + "_sync_local_id INTEGER, "
                     + "_sync_dirty INTEGER NOT NULL DEFAULT 0, "
                     + "_sync_account TEXT, "
+                    + "_sync_account_type TEXT, "
                     + "_sync_mark INTEGER)");
 
             mDb.execSQL("CREATE TABLE deleted_items ("
@@ -388,6 +396,7 @@
                     + "_sync_id TEXT, "
                     + "_sync_local_id INTEGER, "
                     + "_sync_account TEXT, "
+                    + "_sync_account_type TEXT, "
                     + "_sync_mark INTEGER)");
         }
 
@@ -501,7 +510,7 @@
             throw new UnsupportedOperationException();
         }
 
-        public void onSyncStart(SyncContext context, String account) {
+        public void onSyncStart(SyncContext context, Account account) {
             throw new UnsupportedOperationException();
         }
 
@@ -509,7 +518,7 @@
             throw new UnsupportedOperationException();
         }
 
-        public String getSyncingAccount() {
+        public Account getSyncingAccount() {
             throw new UnsupportedOperationException();
         }
 
@@ -544,24 +553,24 @@
             throw new UnsupportedOperationException();
         }
 
-        protected void onAccountsChanged(String[] accountsArray) {
+        protected void onAccountsChanged(Account[] accountsArray) {
             throw new UnsupportedOperationException();
         }
 
-        protected void deleteRowsForRemovedAccounts(Map<String, Boolean> accounts, String table,
-                String accountColumnName) {
+        protected void deleteRowsForRemovedAccounts(Map<Account, Boolean> accounts, String table
+        ) {
             throw new UnsupportedOperationException();
         }
 
-        public void wipeAccount(String account) {
+        public void wipeAccount(Account account) {
             throw new UnsupportedOperationException();
         }
 
-        public byte[] readSyncDataBytes(String account) {
+        public byte[] readSyncDataBytes(Account account) {
             throw new UnsupportedOperationException();
         }
 
-        public void writeSyncDataBytes(String account, byte[] data) {
+        public void writeSyncDataBytes(Account account, byte[] data) {
             throw new UnsupportedOperationException();
         }
     }
diff --git a/tests/FrameworkTest/tests/src/android/content/ContentProviderOperationTest.java b/tests/FrameworkTest/tests/src/android/content/ContentProviderOperationTest.java
new file mode 100644
index 0000000..e9a43d7
--- /dev/null
+++ b/tests/FrameworkTest/tests/src/android/content/ContentProviderOperationTest.java
@@ -0,0 +1,468 @@
+/*
+ * 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.
+ */
+
+package android.content;
+
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.Parcel;
+import android.test.suitebuilder.annotation.SmallTest;
+import android.text.TextUtils;
+import junit.framework.TestCase;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+
+@SmallTest
+public class ContentProviderOperationTest extends TestCase {
+    private final static Uri sTestUri1 = Uri.parse("content://authority/blah");
+    private final static ContentValues sTestValues1;
+
+    private final static Class<ContentProviderOperation.Builder> CLASS_BUILDER =
+            ContentProviderOperation.Builder.class;
+    private final static Class<ContentProviderOperation> CLASS_OPERATION =
+            ContentProviderOperation.class;
+
+    static {
+        sTestValues1 = new ContentValues();
+        sTestValues1.put("a", 1);
+        sTestValues1.put("b", "two");
+    }
+
+    public void testInsert() throws OperationApplicationException {
+        ContentProviderOperation op1 = ContentProviderOperation.newInsert(sTestUri1)
+                .withValues(sTestValues1)
+                .build();
+        ContentProviderResult result = op1.apply(new TestContentProvider() {
+            public Uri insert(Uri uri, ContentValues values) {
+                assertEquals(sTestUri1.toString(), uri.toString());
+                assertEquals(sTestValues1.toString(), values.toString());
+                return uri.buildUpon().appendPath("19").build();
+            }
+        }, null, 0);
+        assertEquals(sTestUri1.buildUpon().appendPath("19").toString(), result.uri.toString());
+    }
+
+    public void testInsertNoValues() throws OperationApplicationException {
+        ContentProviderOperation op1 = ContentProviderOperation.newInsert(sTestUri1)
+                .build();
+        ContentProviderResult result = op1.apply(new TestContentProvider() {
+            public Uri insert(Uri uri, ContentValues values) {
+                assertEquals(sTestUri1.toString(), uri.toString());
+                assertNull(values);
+                return uri.buildUpon().appendPath("19").build();
+            }
+        }, null, 0);
+        assertEquals(sTestUri1.buildUpon().appendPath("19").toString(), result.uri.toString());
+    }
+
+    public void testInsertFailed() {
+        ContentProviderOperation op1 = ContentProviderOperation.newInsert(sTestUri1)
+                .withValues(sTestValues1)
+                .build();
+        try {
+            op1.apply(new TestContentProvider() {
+                public Uri insert(Uri uri, ContentValues values) {
+                    assertEquals(sTestUri1.toString(), uri.toString());
+                    assertEquals(sTestValues1.toString(), values.toString());
+                    return null;
+                }
+            }, null, 0);
+            fail("the apply should have thrown an OperationApplicationException");
+        } catch (OperationApplicationException e) {
+            // this is the expected case
+        }
+    }
+
+    public void testInsertWithBackRefs() throws OperationApplicationException {
+        ContentProviderResult[] previousResults = new ContentProviderResult[4];
+        previousResults[0] = new ContentProviderResult(100);
+        previousResults[1] = new ContentProviderResult(101);
+        previousResults[2] = new ContentProviderResult(102);
+        previousResults[3] = new ContentProviderResult(103);
+        ContentProviderOperation op1 = ContentProviderOperation.newInsert(sTestUri1)
+                .withValues(sTestValues1)
+                .withValueBackReference("a1", 3)
+                .withValueBackReference("a2", 1)
+                .build();
+        ContentProviderResult result = op1.apply(new TestContentProvider() {
+            public Uri insert(Uri uri, ContentValues values) {
+                assertEquals(sTestUri1.toString(), uri.toString());
+                ContentValues expected = new ContentValues(sTestValues1);
+                expected.put("a1", 103);
+                expected.put("a2", 101);
+                assertEquals(expected.toString(), values.toString());
+                return uri.buildUpon().appendPath("19").build();
+            }
+        }, previousResults, previousResults.length);
+        assertEquals(sTestUri1.buildUpon().appendPath("19").toString(), result.uri.toString());
+    }
+
+    public void testUpdate() throws OperationApplicationException {
+        ContentProviderOperation op1 = ContentProviderOperation.newInsert(sTestUri1)
+                .withValues(sTestValues1)
+                .build();
+        ContentProviderResult[] backRefs = new ContentProviderResult[2];
+        ContentProviderResult result = op1.apply(new TestContentProvider() {
+            public Uri insert(Uri uri, ContentValues values) {
+                assertEquals(sTestUri1.toString(), uri.toString());
+                assertEquals(sTestValues1.toString(), values.toString());
+                return uri.buildUpon().appendPath("19").build();
+            }
+        }, backRefs, 1);
+        assertEquals(sTestUri1.buildUpon().appendPath("19").toString(), result.uri.toString());
+    }
+
+    public void testValueBackRefs() {
+        ContentValues values = new ContentValues();
+        values.put("a", "in1");
+        values.put("a2", "in2");
+        values.put("b", "in3");
+        values.put("c", "in4");
+
+        ContentProviderResult[] previousResults = new ContentProviderResult[4];
+        previousResults[0] = new ContentProviderResult(100);
+        previousResults[1] = new ContentProviderResult(101);
+        previousResults[2] = new ContentProviderResult(102);
+        previousResults[3] = new ContentProviderResult(103);
+
+        ContentValues expectedValues = new ContentValues(values);
+        expectedValues.put("a1", "103");
+        expectedValues.put("a2", "101");
+        expectedValues.put("a3", "102");
+
+        ContentProviderOperation op1 = ContentProviderOperation.newInsert(sTestUri1)
+                .withValues(values)
+                .withValueBackReference("a1", 3)
+                .withValueBackReference("a2", 1)
+                .withValueBackReference("a3", 2)
+                .build();
+        ContentValues v2 = op1.resolveValueBackReferences(previousResults, previousResults.length);
+        assertEquals(expectedValues, v2);
+    }
+
+    public void testSelectionBackRefs() {
+        ContentProviderResult[] previousResults = new ContentProviderResult[4];
+        previousResults[0] = new ContentProviderResult(100);
+        previousResults[1] = new ContentProviderResult(101);
+        previousResults[2] = new ContentProviderResult(102);
+        previousResults[3] = new ContentProviderResult(103);
+
+        String[] selectionArgs = new String[]{"a", null, null, "b", null};
+
+        ContentProviderOperation op1 = ContentProviderOperation.newUpdate(sTestUri1)
+                .withSelectionBackReference(1, 3)
+                .withSelectionBackReference(2, 1)
+                .withSelectionBackReference(4, 2)
+                .withSelection("unused", selectionArgs)
+                .build();
+        String[] s2 = op1.resolveSelectionArgsBackReferences(
+                previousResults, previousResults.length);
+        assertEquals("a,103,101,b,102", TextUtils.join(",", s2));
+    }
+
+    public void testParcelingOperation() throws NoSuchFieldException, IllegalAccessException,
+            NoSuchMethodException, InvocationTargetException, InstantiationException {
+        Parcel parcel = Parcel.obtain();
+        ContentProviderOperation op1;
+        ContentProviderOperation op2;
+
+        HashMap<Integer, Integer> selArgsBackRef = new HashMap<Integer, Integer>();
+        selArgsBackRef.put(1, 2);
+        selArgsBackRef.put(3, 4);
+
+        ContentValues values = new ContentValues();
+        values.put("v1", "val1");
+        values.put("v2", "43");
+
+        ContentValues valuesBackRef = new ContentValues();
+        values.put("v3", "val3");
+        values.put("v4", "44");
+
+        try {
+            ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(
+                    Uri.parse("content://goo/bar"));
+
+            builderSetExpectedCount(builder, 42);
+            builderSetSelection(builder, "selection");
+            builderSetSelectionArgs(builder, new String[]{"a", "b"});
+            builderSetSelectionArgsBackReferences(builder, selArgsBackRef);
+            builderSetValues(builder, values);
+            builderSetValuesBackReferences(builder, valuesBackRef);
+
+            op1 = newOperationFromBuilder(builder);
+            op1.writeToParcel(parcel, 0);
+            parcel.setDataPosition(0);
+            op2 = ContentProviderOperation.CREATOR.createFromParcel(parcel);
+
+            assertEquals(1 /* ContentProviderOperation.TYPE_INSERT */, operationGetType(op2));
+            assertEquals("content://goo/bar", operationGetUri(op2).toString());
+            assertEquals(Integer.valueOf(42), operationGetExpectedCount(op2));
+            assertEquals("selection", operationGetSelection(op2));
+            assertEquals(2, operationGetSelectionArgs(op2).length);
+            assertEquals("a", operationGetSelectionArgs(op2)[0]);
+            assertEquals("b", operationGetSelectionArgs(op2)[1]);
+            assertEquals(values, operationGetValues(op2));
+            assertEquals(valuesBackRef, operationGetValuesBackReferences(op2));
+            assertEquals(2, operationGetSelectionArgsBackReferences(op2).size());
+            assertEquals(Integer.valueOf(2), operationGetSelectionArgsBackReferences(op2).get(1));
+            assertEquals(Integer.valueOf(4), operationGetSelectionArgsBackReferences(op2).get(3));
+        } finally {
+            parcel.recycle();
+        }
+
+        try {
+            ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(
+                    Uri.parse("content://goo/bar"));
+
+            builderSetSelectionArgsBackReferences(builder, selArgsBackRef);
+
+            op1 = newOperationFromBuilder(builder);
+            op1.writeToParcel(parcel, 0);
+            parcel.setDataPosition(0);
+            op2 = ContentProviderOperation.CREATOR.createFromParcel(parcel);
+            assertEquals(2 /* ContentProviderOperation.TYPE_UPDATE */, operationGetType(op2));
+            assertEquals("content://goo/bar", operationGetUri(op2).toString());
+            assertNull(operationGetEntity(op2));
+            assertNull(operationGetExpectedCount(op2));
+            assertNull(operationGetSelection(op2));
+            assertNull(operationGetSelectionArgs(op2));
+            assertNull(operationGetValues(op2));
+            assertNull(operationGetValuesBackReferences(op2));
+            assertEquals(2, operationGetSelectionArgsBackReferences(op2).size());
+            assertEquals(Integer.valueOf(2), operationGetSelectionArgsBackReferences(op2).get(1));
+            assertEquals(Integer.valueOf(4), operationGetSelectionArgsBackReferences(op2).get(3));
+        } finally {
+            parcel.recycle();
+        }
+
+        try {
+            ContentProviderOperation.Builder builder = ContentProviderOperation.newDelete(
+                    Uri.parse("content://goo/bar"));
+
+            op1 = newOperationFromBuilder(builder);
+            op1.writeToParcel(parcel, 0);
+            parcel.setDataPosition(0);
+            op2 = ContentProviderOperation.CREATOR.createFromParcel(parcel);
+            assertEquals(3 /* ContentProviderOperation.TYPE_DELETE */, operationGetType(op2));
+            assertEquals("content://goo/bar", operationGetUri(op2).toString());
+            assertNull(operationGetEntity(op2));
+            assertNull(operationGetExpectedCount(op2));
+            assertNull(operationGetSelection(op2));
+            assertNull(operationGetSelectionArgs(op2));
+            assertNull(operationGetValues(op2));
+            assertNull(operationGetValuesBackReferences(op2));
+            assertNull(operationGetSelectionArgsBackReferences(op2));
+        } finally {
+            parcel.recycle();
+        }
+    }
+
+    private static ContentProviderOperation newOperationFromBuilder(
+            ContentProviderOperation.Builder builder)
+            throws NoSuchMethodException, InstantiationException, IllegalAccessException,
+            InvocationTargetException {
+        final Constructor constructor = CLASS_OPERATION.getDeclaredConstructor(CLASS_BUILDER);
+        constructor.setAccessible(true);
+        return (ContentProviderOperation) constructor.newInstance(builder);
+    }
+
+    private void builderSetSelectionArgsBackReferences(
+            ContentProviderOperation.Builder builder, HashMap<Integer, Integer> selArgsBackRef)
+            throws NoSuchFieldException, IllegalAccessException {
+        Field field;
+        field = CLASS_BUILDER.getDeclaredField("mSelectionArgsBackReferences");
+        field.setAccessible(true);
+        field.set(builder, selArgsBackRef);
+    }
+
+    private void builderSetValuesBackReferences(
+            ContentProviderOperation.Builder builder, ContentValues valuesBackReferences)
+            throws NoSuchFieldException, IllegalAccessException {
+        Field field;
+        field = CLASS_BUILDER.getDeclaredField("mValuesBackReferences");
+        field.setAccessible(true);
+        field.set(builder, valuesBackReferences);
+    }
+
+    private void builderSetSelection(
+            ContentProviderOperation.Builder builder, String selection)
+            throws NoSuchFieldException, IllegalAccessException {
+        Field field;
+        field = CLASS_BUILDER.getDeclaredField("mSelection");
+        field.setAccessible(true);
+        field.set(builder, selection);
+    }
+
+    private void builderSetSelectionArgs(
+            ContentProviderOperation.Builder builder, String[] selArgs)
+            throws NoSuchFieldException, IllegalAccessException {
+        Field field;
+        field = CLASS_BUILDER.getDeclaredField("mSelectionArgs");
+        field.setAccessible(true);
+        field.set(builder, selArgs);
+    }
+
+    private void builderSetValues(
+            ContentProviderOperation.Builder builder, ContentValues values)
+            throws NoSuchFieldException, IllegalAccessException {
+        Field field;
+        field = CLASS_BUILDER.getDeclaredField("mValues");
+        field.setAccessible(true);
+        field.set(builder, values);
+    }
+
+    private void builderSetEntity(
+            ContentProviderOperation.Builder builder, Entity entity)
+            throws NoSuchFieldException, IllegalAccessException {
+        Field field;
+        field = CLASS_BUILDER.getDeclaredField("mEntity");
+        field.setAccessible(true);
+        field.set(builder, entity);
+    }
+
+    private void builderSetExpectedCount(
+            ContentProviderOperation.Builder builder, Integer expectedCount)
+            throws NoSuchFieldException, IllegalAccessException {
+        Field field;
+        field = CLASS_BUILDER.getDeclaredField("mExpectedCount");
+        field.setAccessible(true);
+        field.set(builder, expectedCount);
+    }
+
+    private int operationGetType(ContentProviderOperation operation)
+            throws NoSuchFieldException, IllegalAccessException {
+        final Field field = CLASS_OPERATION.getDeclaredField("mType");
+        field.setAccessible(true);
+        return field.getInt(operation);
+    }
+
+    private Uri operationGetUri(ContentProviderOperation operation)
+            throws NoSuchFieldException, IllegalAccessException {
+        final Field field = CLASS_OPERATION.getDeclaredField("mUri");
+        field.setAccessible(true);
+        return (Uri) field.get(operation);
+    }
+
+    private String operationGetSelection(ContentProviderOperation operation)
+            throws NoSuchFieldException, IllegalAccessException {
+        final Field field = CLASS_OPERATION.getDeclaredField("mSelection");
+        field.setAccessible(true);
+        return (String) field.get(operation);
+    }
+
+    private String[] operationGetSelectionArgs(ContentProviderOperation operation)
+            throws NoSuchFieldException, IllegalAccessException {
+        final Field field = CLASS_OPERATION.getDeclaredField("mSelectionArgs");
+        field.setAccessible(true);
+        return (String[]) field.get(operation);
+    }
+
+    private ContentValues operationGetValues(ContentProviderOperation operation)
+            throws NoSuchFieldException, IllegalAccessException {
+        final Field field = CLASS_OPERATION.getDeclaredField("mValues");
+        field.setAccessible(true);
+        return (ContentValues) field.get(operation);
+    }
+
+    private Entity operationGetEntity(ContentProviderOperation operation)
+            throws NoSuchFieldException, IllegalAccessException {
+        final Field field = CLASS_OPERATION.getDeclaredField("mEntity");
+        field.setAccessible(true);
+        return (Entity) field.get(operation);
+    }
+
+    private Integer operationGetExpectedCount(ContentProviderOperation operation)
+            throws NoSuchFieldException, IllegalAccessException {
+        final Field field = CLASS_OPERATION.getDeclaredField("mExpectedCount");
+        field.setAccessible(true);
+        return (Integer) field.get(operation);
+    }
+
+    private ContentValues operationGetValuesBackReferences(ContentProviderOperation operation)
+            throws NoSuchFieldException, IllegalAccessException {
+        final Field field = CLASS_OPERATION.getDeclaredField("mValuesBackReferences");
+        field.setAccessible(true);
+        return (ContentValues) field.get(operation);
+    }
+
+    private Map<Integer, Integer> operationGetSelectionArgsBackReferences(
+            ContentProviderOperation operation)
+            throws NoSuchFieldException, IllegalAccessException {
+        final Field field = CLASS_OPERATION.getDeclaredField("mSelectionArgsBackReferences");
+        field.setAccessible(true);
+        return (Map<Integer, Integer>) field.get(operation);
+    }
+
+    public void testParcelingResult() {
+        Parcel parcel = Parcel.obtain();
+        ContentProviderResult result1;
+        ContentProviderResult result2;
+        try {
+            result1 = new ContentProviderResult(Uri.parse("content://goo/bar"));
+            result1.writeToParcel(parcel, 0);
+            parcel.setDataPosition(0);
+            result2 = ContentProviderResult.CREATOR.createFromParcel(parcel);
+            assertEquals("content://goo/bar", result2.uri.toString());
+            assertNull(result2.count);
+        } finally {
+            parcel.recycle();
+        }
+
+        parcel = Parcel.obtain();
+        try {
+            result1 = new ContentProviderResult(42);
+            result1.writeToParcel(parcel, 0);
+            parcel.setDataPosition(0);
+            result2 = ContentProviderResult.CREATOR.createFromParcel(parcel);
+            assertEquals(Integer.valueOf(42), result2.count);
+            assertNull(result2.uri);
+        } finally {
+            parcel.recycle();
+        }
+    }
+
+    static class TestContentProvider extends ContentProvider {
+        public boolean onCreate() {
+            throw new UnsupportedOperationException();
+        }
+
+        public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
+                String sortOrder) {
+            throw new UnsupportedOperationException();
+        }
+
+        public String getType(Uri uri) {
+            throw new UnsupportedOperationException();
+        }
+
+        public Uri insert(Uri uri, ContentValues values) {
+            throw new UnsupportedOperationException();
+        }
+
+        public int delete(Uri uri, String selection, String[] selectionArgs) {
+            throw new UnsupportedOperationException();
+        }
+
+        public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+            throw new UnsupportedOperationException();
+        }
+    }
+}
\ No newline at end of file
diff --git a/tests/permission/src/com/android/framework/permission/tests/HardwareServicePermissionTest.java b/tests/permission/src/com/android/framework/permission/tests/HardwareServicePermissionTest.java
index 719e758..aebd68c 100644
--- a/tests/permission/src/com/android/framework/permission/tests/HardwareServicePermissionTest.java
+++ b/tests/permission/src/com/android/framework/permission/tests/HardwareServicePermissionTest.java
@@ -46,7 +46,7 @@
      */
     public void testVibrate() throws RemoteException {
         try {
-            mHardwareService.vibrate(2000);
+            mHardwareService.vibrate(2000, new Binder());
             fail("vibrate did not throw SecurityException as expected");
         } catch (SecurityException e) {
             // expected
@@ -77,7 +77,7 @@
      */
     public void testCancelVibrate() throws RemoteException {
         try {
-            mHardwareService.cancelVibrate();
+            mHardwareService.cancelVibrate(new Binder());
             fail("cancelVibrate did not throw SecurityException as expected");
         } catch (SecurityException e) {
             // expected
diff --git a/tools/aapt/AaptAssets.h b/tools/aapt/AaptAssets.h
index 63afe5c..5724349 100644
--- a/tools/aapt/AaptAssets.h
+++ b/tools/aapt/AaptAssets.h
@@ -15,7 +15,7 @@
 #include <utils/String8.h>
 #include <utils/Vector.h>
 #include <utils/RefBase.h>
-#include <utils/ZipFile.h>
+#include "ZipFile.h"
 
 #include "Bundle.h"
 #include "SourcePos.h"
@@ -131,7 +131,9 @@
         {
             //printf("new AaptFile created %s\n", (const char*)sourceFile);
         }
-    virtual ~AaptFile() { }
+    virtual ~AaptFile() {
+        free(mData);
+    }
 
     const String8& getPath() const { return mPath; }
     const AaptGroupEntry& getGroupEntry() const { return mGroupEntry; }
@@ -447,7 +449,13 @@
     AaptSymbolEntry                                 mDefSymbol;
 };
 
-class ResourceTypeSet;
+class ResourceTypeSet : public RefBase,
+                        public KeyedVector<String8,sp<AaptGroup> >
+{
+public:
+    ResourceTypeSet();
+};
+
 
 /**
  * Asset hierarchy being operated on.
@@ -455,8 +463,8 @@
 class AaptAssets : public AaptDir
 {
 public:
-    AaptAssets() : AaptDir(String8(), String8()), mHaveIncludedAssets(false) { }
-    virtual ~AaptAssets() { }
+    AaptAssets() : AaptDir(String8(), String8()), mHaveIncludedAssets(false), mRes(NULL) { }
+    virtual ~AaptAssets() { delete mRes; }
 
     const String8& getPackage() const { return mPackage; }
     void setPackage(const String8& package) { mPackage = package; mSymbolsPrivatePackage = package; }
@@ -504,7 +512,7 @@
     
     inline KeyedVector<String8, sp<ResourceTypeSet> >* getResources() { return mRes; }
     inline void 
-        setResources(KeyedVector<String8, sp<ResourceTypeSet> >* res) { mRes = res; }
+        setResources(KeyedVector<String8, sp<ResourceTypeSet> >* res) { delete mRes; mRes = res; }
 
 private:
     String8 mPackage;
diff --git a/tools/aapt/Android.mk b/tools/aapt/Android.mk
index fdc859c..2d8973d 100644
--- a/tools/aapt/Android.mk
+++ b/tools/aapt/Android.mk
@@ -17,7 +17,10 @@
 	ResourceTable.cpp \
 	Images.cpp \
 	Resource.cpp \
-    SourcePos.cpp
+    SourcePos.cpp \
+    ZipEntry.cpp \
+    ZipFile.cpp
+
 
 LOCAL_CFLAGS += -Wno-format-y2k
 
diff --git a/tools/aapt/Bundle.h b/tools/aapt/Bundle.h
index a6fedf3..a671bd7 100644
--- a/tools/aapt/Bundle.h
+++ b/tools/aapt/Bundle.h
@@ -7,7 +7,10 @@
 #define __BUNDLE_H
 
 #include <stdlib.h>
-#include <utils.h>      // android
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 #include <utils/String8.h>
 #include <utils/Vector.h>
 
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index e04491d..c0ae592 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -8,8 +8,10 @@
 #include "ResourceTable.h"
 #include "XMLNode.h"
 
-#include <utils.h>
-#include <utils/ZipFile.h>
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 
 #include <fcntl.h>
 #include <errno.h>
diff --git a/tools/aapt/Images.cpp b/tools/aapt/Images.cpp
index 0a4c68b..f2414dd 100644
--- a/tools/aapt/Images.cpp
+++ b/tools/aapt/Images.cpp
@@ -44,6 +44,9 @@
             }
             free(allocRows);
         }
+        free(info9Patch.xDivs);
+        free(info9Patch.yDivs);
+        free(info9Patch.colors);
     }
 
     png_uint_32 width;
@@ -833,6 +836,7 @@
     int i;
 
     png_unknown_chunk unknowns[1];
+    unknowns[0].data = NULL;
 
     png_bytepp outRows = (png_bytepp) malloc((int) imageInfo.height * png_sizeof(png_bytep));
     if (outRows == (png_bytepp) 0) {
@@ -939,6 +943,7 @@
         free(outRows[i]);
     }
     free(outRows);
+    free(unknowns[0].data);
 
     png_get_IHDR(write_ptr, write_info, &width, &height,
        &bit_depth, &color_type, &interlace_type,
diff --git a/tools/aapt/Main.cpp b/tools/aapt/Main.cpp
index 12a0445..882714c 100644
--- a/tools/aapt/Main.cpp
+++ b/tools/aapt/Main.cpp
@@ -6,8 +6,10 @@
 #include "Main.h"
 #include "Bundle.h"
 
-#include <utils.h>
-#include <utils/ZipFile.h>
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 
 #include <stdlib.h>
 #include <getopt.h>
diff --git a/tools/aapt/Main.h b/tools/aapt/Main.h
index 65c0a8a..34ca5e5 100644
--- a/tools/aapt/Main.h
+++ b/tools/aapt/Main.h
@@ -6,10 +6,13 @@
 #ifndef __MAIN_H
 #define __MAIN_H
 
-#include <utils.h>
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 #include "Bundle.h"
 #include "AaptAssets.h"
-#include <utils/ZipFile.h>
+#include "ZipFile.h"
 
 extern int doVersion(Bundle* bundle);
 extern int doList(Bundle* bundle);
diff --git a/tools/aapt/Package.cpp b/tools/aapt/Package.cpp
index eb7d6f5..999a5cf 100644
--- a/tools/aapt/Package.cpp
+++ b/tools/aapt/Package.cpp
@@ -7,8 +7,10 @@
 #include "AaptAssets.h"
 #include "ResourceTable.h"
 
-#include <utils.h>
-#include <utils/ZipFile.h>
+#include <utils/Log.h>
+#include <utils/threads.h>
+#include <utils/List.h>
+#include <utils/Errors.h>
 
 #include <sys/types.h>
 #include <dirent.h>
@@ -166,7 +168,7 @@
         delete zip;        // close the file so we can remove it in Win32
         zip = NULL;
         if (unlink(outputFile.string()) != 0) {
-            fprintf(stderr, "WARNING: could not unlink '%s'\n", outputFile.string());
+            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string());
         }
     }
 
@@ -179,7 +181,7 @@
             printf("Removing %s due to earlier failures\n", outputFile.string());
         }
         if (unlink(outputFile.string()) != 0) {
-            fprintf(stderr, "WARNING: could not unlink '%s'\n", outputFile.string());
+            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string());
         }
     }
 
@@ -281,7 +283,7 @@
     if (fileNameLen > excludeExtensionLen
             && (0 == strcmp(storageName.string() + (fileNameLen - excludeExtensionLen),
                             kExcludeExtension))) {
-        fprintf(stderr, "WARNING: '%s' not added to Zip\n", storageName.string());
+        fprintf(stderr, "warning: '%s' not added to Zip\n", storageName.string());
         return true;
     }
 
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index 027e3ab..41ee88b 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -45,13 +45,6 @@
     }
 }
 
-class ResourceTypeSet : public RefBase,
-                        public KeyedVector<String8,sp<AaptGroup> >
-{
-public:
-    ResourceTypeSet();
-};
-
 ResourceTypeSet::ResourceTypeSet()
     :RefBase(),
      KeyedVector<String8,sp<AaptGroup> >()
@@ -181,7 +174,7 @@
 static status_t parsePackage(const sp<AaptAssets>& assets, const sp<AaptGroup>& grp)
 {
     if (grp->getFiles().size() != 1) {
-        fprintf(stderr, "WARNING: Multiple AndroidManifest.xml files found, using %s\n",
+        fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
                 grp->getFiles().valueAt(0)->getPrintableSource().string());
     }
 
@@ -426,7 +419,7 @@
         if (code == ResXMLTree::START_TAG) {
             ssize_t index = parser.indexOfAttribute(NULL, "id");
             if (index >= 0) {
-                fprintf(stderr, "%s:%d: WARNING: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
+                fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
                         path.string(), parser.getLineNumber());
             }
         }
@@ -1118,6 +1111,7 @@
                 printf("  Writing public definitions to %s.\n", bundle->getPublicOutputFile());
             }
             table.writePublicDefinitions(String16(assets->getPackage()), fp);
+            fclose(fp);
         }
 
         NOISY(
@@ -1135,7 +1129,6 @@
             return err;
         }
     }
-
     return err;
 }
 
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index b004664..8dbc12e 100644
--- a/tools/aapt/ResourceTable.cpp
+++ b/tools/aapt/ResourceTable.cpp
@@ -3554,26 +3554,26 @@
 
     }
     if (p == NULL) {
-        fprintf(stderr, "WARNING: Package not found for resource #%08x\n", resID);
+        fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
         return NULL;
     }
 
     int tid = Res_GETTYPE(resID);
     if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
-        fprintf(stderr, "WARNING: Type not found for resource #%08x\n", resID);
+        fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
         return NULL;
     }
     sp<Type> t = p->getOrderedTypes()[tid];
 
     int eid = Res_GETENTRY(resID);
     if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
-        fprintf(stderr, "WARNING: Entry not found for resource #%08x\n", resID);
+        fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
         return NULL;
     }
 
     sp<ConfigList> c = t->getOrderedConfigs()[eid];
     if (c == NULL) {
-        fprintf(stderr, "WARNING: Entry not found for resource #%08x\n", resID);
+        fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
         return NULL;
     }
     
@@ -3581,7 +3581,7 @@
     if (config) cdesc = *config;
     sp<Entry> e = c->getEntries().valueFor(cdesc);
     if (c == NULL) {
-        fprintf(stderr, "WARNING: Entry configuration not found for resource #%08x\n", resID);
+        fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
         return NULL;
     }
     
@@ -3599,7 +3599,7 @@
     for (size_t i=0; i<N; i++) {
         const Item& it = e->getBag().valueAt(i);
         if (it.bagKeyId == 0) {
-            fprintf(stderr, "WARNING: ID not yet assigned to '%s' in bag '%s'\n",
+            fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
                     String8(e->getName()).string(),
                     String8(e->getBag().keyAt(i)).string());
         }
@@ -3627,7 +3627,7 @@
                     break;
                 }
             }
-            fprintf(stderr, "WARNING: Circular reference detected in key '%s' of bag '%s'\n",
+            fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
                     String8(e->getName()).string(),
                     String8(e->getBag().keyAt(i)).string());
             return false;
diff --git a/tools/aapt/SourcePos.cpp b/tools/aapt/SourcePos.cpp
index 2761d18..e2a921c 100644
--- a/tools/aapt/SourcePos.cpp
+++ b/tools/aapt/SourcePos.cpp
@@ -86,7 +86,7 @@
 void
 ErrorPos::print(FILE* to) const
 {
-    const char* type = fatal ? "ERROR" : "WARNING";
+    const char* type = fatal ? "error:" : "warning:";
     
     if (this->line >= 0) {
         fprintf(to, "%s:%d: %s %s\n", this->file.string(), this->line, type, this->error.string());
diff --git a/tools/aapt/XMLNode.cpp b/tools/aapt/XMLNode.cpp
index 2a85bc7..6daa0d2 100644
--- a/tools/aapt/XMLNode.cpp
+++ b/tools/aapt/XMLNode.cpp
@@ -220,7 +220,7 @@
             spanStack.pop();
 
             if (empty) {
-                fprintf(stderr, "%s:%d: WARNING: empty '%s' span found in text '%s'\n",
+                fprintf(stderr, "%s:%d: warning: empty '%s' span found in text '%s'\n",
                         fileName, inXml->getLineNumber(),
                         String8(spanTag).string(), String8(*outString).string());
 
@@ -486,6 +486,7 @@
 XMLNode::XMLNode(const String8& filename)
     : mFilename(filename)
 {
+    memset(&mCharsValue, 0, sizeof(mCharsValue));
 }
 
 XMLNode::type XMLNode::getType() const
diff --git a/libs/utils/ZipEntry.cpp b/tools/aapt/ZipEntry.cpp
similarity index 99%
rename from libs/utils/ZipEntry.cpp
rename to tools/aapt/ZipEntry.cpp
index 96f9fc4..a0b54c2 100644
--- a/libs/utils/ZipEntry.cpp
+++ b/tools/aapt/ZipEntry.cpp
@@ -20,7 +20,7 @@
 
 #define LOG_TAG "zip"
 
-#include <utils/ZipEntry.h>
+#include "ZipEntry.h"
 #include <utils/Log.h>
 
 #include <stdio.h>
@@ -90,7 +90,7 @@
      * prefer the CDE values.)
      */
     if (!hasDD && !compareHeaders()) {
-        LOGW("WARNING: header mismatch\n");
+        LOGW("warning: header mismatch\n");
         // keep going?
     }
 
diff --git a/include/utils/ZipEntry.h b/tools/aapt/ZipEntry.h
similarity index 99%
rename from include/utils/ZipEntry.h
rename to tools/aapt/ZipEntry.h
index e4698df..7f721b4 100644
--- a/include/utils/ZipEntry.h
+++ b/tools/aapt/ZipEntry.h
@@ -22,7 +22,7 @@
 #ifndef __LIBS_ZIPENTRY_H
 #define __LIBS_ZIPENTRY_H
 
-#include "Errors.h"
+#include <utils/Errors.h>
 
 #include <stdlib.h>
 #include <stdio.h>
diff --git a/libs/utils/ZipFile.cpp b/tools/aapt/ZipFile.cpp
similarity index 91%
rename from libs/utils/ZipFile.cpp
rename to tools/aapt/ZipFile.cpp
index 6f27d17..62c9383 100644
--- a/libs/utils/ZipFile.cpp
+++ b/tools/aapt/ZipFile.cpp
@@ -20,10 +20,11 @@
 
 #define LOG_TAG "zip"
 
-#include <utils/ZipFile.h>
 #include <utils/ZipUtils.h>
 #include <utils/Log.h>
 
+#include "ZipFile.h"
+
 #include <zlib.h>
 #define DEF_MEM_LEVEL 8                // normally in zutil.h?
 
@@ -94,10 +95,10 @@
     }
     mZipFp = fopen(zipFileName, openflags);
     if (mZipFp == NULL) {
-		int err = errno;
-		LOGD("fopen failed: %d\n", err);
+        int err = errno;
+        LOGD("fopen failed: %d\n", err);
         return errnoToStatus(err);
-	}
+    }
 
     status_t result;
     if (!newArchive) {
@@ -221,8 +222,8 @@
 
     buf = new unsigned char[EndOfCentralDir::kMaxEOCDSearch];
     if (buf == NULL) {
-		LOGD("Failure allocating %d bytes for EOCD search",
-			 EndOfCentralDir::kMaxEOCDSearch);
+        LOGD("Failure allocating %d bytes for EOCD search",
+             EndOfCentralDir::kMaxEOCDSearch);
         result = NO_MEMORY;
         goto bail;
     }
@@ -235,7 +236,7 @@
         readAmount = (long) fileLength;
     }
     if (fseek(mZipFp, seekStart, SEEK_SET) != 0) {
-		LOGD("Failure seeking to end of zip at %ld", (long) seekStart);
+        LOGD("Failure seeking to end of zip at %ld", (long) seekStart);
         result = UNKNOWN_ERROR;
         goto bail;
     }
@@ -265,9 +266,9 @@
     /* extract eocd values */
     result = mEOCD.readBuf(buf + i, readAmount - i);
     if (result != NO_ERROR) {
-		LOGD("Failure reading %ld bytes of EOCD values", readAmount - i);
+        LOGD("Failure reading %ld bytes of EOCD values", readAmount - i);
         goto bail;
-	}
+    }
     //mEOCD.dump();
 
     if (mEOCD.mDiskNumber != 0 || mEOCD.mDiskWithCentralDir != 0 ||
@@ -293,8 +294,8 @@
      * we're hoping to preserve.
      */
     if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
-		LOGD("Failure seeking to central dir offset %ld\n",
-			 mEOCD.mCentralDirOffset);
+        LOGD("Failure seeking to central dir offset %ld\n",
+             mEOCD.mCentralDirOffset);
         result = UNKNOWN_ERROR;
         goto bail;
     }
@@ -743,61 +744,61 @@
     const void* data, size_t size, unsigned long* pCRC32)
 {
     status_t result = NO_ERROR;
-	const size_t kBufSize = 32768;
-	unsigned char* inBuf = NULL;
-	unsigned char* outBuf = NULL;
-	z_stream zstream;
+    const size_t kBufSize = 32768;
+    unsigned char* inBuf = NULL;
+    unsigned char* outBuf = NULL;
+    z_stream zstream;
     bool atEof = false;     // no feof() aviailable yet
-	unsigned long crc;
-	int zerr;
+    unsigned long crc;
+    int zerr;
 
-	/*
-	 * Create an input buffer and an output buffer.
-	 */
-	inBuf = new unsigned char[kBufSize];
-	outBuf = new unsigned char[kBufSize];
-	if (inBuf == NULL || outBuf == NULL) {
-		result = NO_MEMORY;
-		goto bail;
-	}
+    /*
+     * Create an input buffer and an output buffer.
+     */
+    inBuf = new unsigned char[kBufSize];
+    outBuf = new unsigned char[kBufSize];
+    if (inBuf == NULL || outBuf == NULL) {
+        result = NO_MEMORY;
+        goto bail;
+    }
 
-	/*
-	 * Initialize the zlib stream.
-	 */
-	memset(&zstream, 0, sizeof(zstream));
-	zstream.zalloc = Z_NULL;
-	zstream.zfree = Z_NULL;
-	zstream.opaque = Z_NULL;
-	zstream.next_in = NULL;
-	zstream.avail_in = 0;
-	zstream.next_out = outBuf;
-	zstream.avail_out = kBufSize;
-	zstream.data_type = Z_UNKNOWN;
+    /*
+     * Initialize the zlib stream.
+     */
+    memset(&zstream, 0, sizeof(zstream));
+    zstream.zalloc = Z_NULL;
+    zstream.zfree = Z_NULL;
+    zstream.opaque = Z_NULL;
+    zstream.next_in = NULL;
+    zstream.avail_in = 0;
+    zstream.next_out = outBuf;
+    zstream.avail_out = kBufSize;
+    zstream.data_type = Z_UNKNOWN;
 
-	zerr = deflateInit2(&zstream, Z_BEST_COMPRESSION,
-		Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
-	if (zerr != Z_OK) {
-		result = UNKNOWN_ERROR;
-		if (zerr == Z_VERSION_ERROR) {
-			LOGE("Installed zlib is not compatible with linked version (%s)\n",
-				ZLIB_VERSION);
-		} else {
-			LOGD("Call to deflateInit2 failed (zerr=%d)\n", zerr);
-		}
-		goto bail;
-	}
+    zerr = deflateInit2(&zstream, Z_BEST_COMPRESSION,
+        Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
+    if (zerr != Z_OK) {
+        result = UNKNOWN_ERROR;
+        if (zerr == Z_VERSION_ERROR) {
+            LOGE("Installed zlib is not compatible with linked version (%s)\n",
+                ZLIB_VERSION);
+        } else {
+            LOGD("Call to deflateInit2 failed (zerr=%d)\n", zerr);
+        }
+        goto bail;
+    }
 
- 	crc = crc32(0L, Z_NULL, 0);
+    crc = crc32(0L, Z_NULL, 0);
 
-	/*
-	 * Loop while we have data.
-	 */
-	do {
-		size_t getSize;
-		int flush;
+    /*
+     * Loop while we have data.
+     */
+    do {
+        size_t getSize;
+        int flush;
 
-		/* only read if the input buffer is empty */
-		if (zstream.avail_in == 0 && !atEof) {
+        /* only read if the input buffer is empty */
+        if (zstream.avail_in == 0 && !atEof) {
             LOGV("+++ reading %d bytes\n", (int)kBufSize);
             if (data) {
                 getSize = size > kBufSize ? kBufSize : size;
@@ -817,54 +818,54 @@
                 atEof = true;
             }
 
-			crc = crc32(crc, inBuf, getSize);
+            crc = crc32(crc, inBuf, getSize);
 
-			zstream.next_in = inBuf;
-			zstream.avail_in = getSize;
-		}
+            zstream.next_in = inBuf;
+            zstream.avail_in = getSize;
+        }
 
-		if (atEof)
-			flush = Z_FINISH;       /* tell zlib that we're done */
-		else
-			flush = Z_NO_FLUSH;     /* more to come! */
+        if (atEof)
+            flush = Z_FINISH;       /* tell zlib that we're done */
+        else
+            flush = Z_NO_FLUSH;     /* more to come! */
 
-		zerr = deflate(&zstream, flush);
-		if (zerr != Z_OK && zerr != Z_STREAM_END) {
-			LOGD("zlib deflate call failed (zerr=%d)\n", zerr);
-			result = UNKNOWN_ERROR;
-			goto z_bail;
-		}
+        zerr = deflate(&zstream, flush);
+        if (zerr != Z_OK && zerr != Z_STREAM_END) {
+            LOGD("zlib deflate call failed (zerr=%d)\n", zerr);
+            result = UNKNOWN_ERROR;
+            goto z_bail;
+        }
 
-		/* write when we're full or when we're done */
-		if (zstream.avail_out == 0 ||
-			(zerr == Z_STREAM_END && zstream.avail_out != (uInt) kBufSize))
-		{
-			LOGV("+++ writing %d bytes\n", (int) (zstream.next_out - outBuf));
+        /* write when we're full or when we're done */
+        if (zstream.avail_out == 0 ||
+            (zerr == Z_STREAM_END && zstream.avail_out != (uInt) kBufSize))
+        {
+            LOGV("+++ writing %d bytes\n", (int) (zstream.next_out - outBuf));
             if (fwrite(outBuf, 1, zstream.next_out - outBuf, dstFp) !=
                 (size_t)(zstream.next_out - outBuf))
             {
-				LOGD("write %d failed in deflate\n",
+                LOGD("write %d failed in deflate\n",
                     (int) (zstream.next_out - outBuf));
-				goto z_bail;
-			}
+                goto z_bail;
+            }
 
-			zstream.next_out = outBuf;
-			zstream.avail_out = kBufSize;
-		}
-	} while (zerr == Z_OK);
+            zstream.next_out = outBuf;
+            zstream.avail_out = kBufSize;
+        }
+    } while (zerr == Z_OK);
 
-	assert(zerr == Z_STREAM_END);       /* other errors should've been caught */
+    assert(zerr == Z_STREAM_END);       /* other errors should've been caught */
 
-	*pCRC32 = crc;
+    *pCRC32 = crc;
 
 z_bail:
-	deflateEnd(&zstream);        /* free up any allocated structures */
+    deflateEnd(&zstream);        /* free up any allocated structures */
 
 bail:
-	delete[] inBuf;
-	delete[] outBuf;
+    delete[] inBuf;
+    delete[] outBuf;
 
-	return result;
+    return result;
 }
 
 /*
@@ -1206,7 +1207,7 @@
 
 /*
  * ===========================================================================
- *		ZipFile::EndOfCentralDir
+ *      ZipFile::EndOfCentralDir
  * ===========================================================================
  */
 
diff --git a/include/utils/ZipFile.h b/tools/aapt/ZipFile.h
similarity index 98%
rename from include/utils/ZipFile.h
rename to tools/aapt/ZipFile.h
index 44df5bb..dbbd072 100644
--- a/include/utils/ZipFile.h
+++ b/tools/aapt/ZipFile.h
@@ -21,11 +21,12 @@
 #ifndef __LIBS_ZIPFILE_H
 #define __LIBS_ZIPFILE_H
 
-#include "ZipEntry.h"
-#include "Vector.h"
-#include "Errors.h"
+#include <utils/Vector.h>
+#include <utils/Errors.h>
 #include <stdio.h>
 
+#include "ZipEntry.h"
+
 namespace android {
 
 /*
diff --git a/tools/aidl/AST.cpp b/tools/aidl/AST.cpp
index 91802a9..1856cb9 100755
--- a/tools/aidl/AST.cpp
+++ b/tools/aidl/AST.cpp
@@ -841,23 +841,6 @@
         fprintf(to, "package %s;\n", this->package.c_str());
     }
 
-    // gather the types for the import statements
-    set<Type*> types;
-    N = this->classes.size();
-    for (i=0; i<N; i++) {
-        Class* c = this->classes[i];
-        c->GatherTypes(&types);
-    }
-    
-    set<Type*>::iterator it;
-    for (it=types.begin(); it!=types.end(); it++) {
-        Type* t = *it;
-        string pkg = t->Package();
-        if (pkg.length() != 0 && pkg != this->package) {
-            fprintf(to, "import %s;\n", t->ImportType().c_str());
-        }
-    }
-
     N = this->classes.size();
     for (i=0; i<N; i++) {
         Class* c = this->classes[i];
diff --git a/tools/aidl/generate_java.cpp b/tools/aidl/generate_java.cpp
index e3c0af0..da20d1f 100644
--- a/tools/aidl/generate_java.cpp
+++ b/tools/aidl/generate_java.cpp
@@ -1,6 +1,7 @@
 #include "generate_java.h"
 #include "AST.h"
 #include "Type.h"
+#include <string.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -133,7 +134,7 @@
 
     Method* m = new Method;
         m->comment = "/**\n * Cast an IBinder object into an ";
-        m->comment += interfaceType->Name();
+        m->comment += interfaceType->QualifiedName();
         m->comment += " interface,\n";
         m->comment += " * generating a proxy if needed.\n */";
         m->modifiers = PUBLIC | STATIC;
@@ -323,7 +324,7 @@
     transactCodeName += method->name.data;
 
     char transactCodeValue[50];
-    sprintf(transactCodeValue, "(IBinder.FIRST_CALL_TRANSACTION + %d)", index);
+    sprintf(transactCodeValue, "(android.os.IBinder.FIRST_CALL_TRANSACTION + %d)", index);
 
     Field* transactCode = new Field(STATIC | FINAL,
                             new Variable(INT_TYPE, transactCodeName));
@@ -517,7 +518,7 @@
                             new LiteralExpression("Stub." + transactCodeName),
                             _data, _reply ? _reply : NULL_VALUE,
                             new LiteralExpression(
-                                oneway ? "IBinder.FLAG_ONEWAY" : "0"));
+                                oneway ? "android.os.IBinder.FLAG_ONEWAY" : "0"));
     tryStatement->statements->Add(call);
 
     // throw back exceptions.
diff --git a/tools/aidl/options.h b/tools/aidl/options.h
index e9bf0f7..d88d988 100644
--- a/tools/aidl/options.h
+++ b/tools/aidl/options.h
@@ -1,6 +1,7 @@
 #ifndef DEVICE_TOOLS_AIDL_H
 #define DEVICE_TOOLS_AIDL_H
 
+#include <string.h>
 #include <string>
 #include <vector>
 
diff --git a/tools/localize/Perforce.cpp b/tools/localize/Perforce.cpp
index 1c644ed..ae11231 100644
--- a/tools/localize/Perforce.cpp
+++ b/tools/localize/Perforce.cpp
@@ -6,7 +6,10 @@
 #include <sstream>
 #include <sys/types.h>
 #include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
 #include <sys/wait.h>
+#include <cstdio>
 
 using namespace std;
 
diff --git a/tools/localize/SourcePos.cpp b/tools/localize/SourcePos.cpp
index 2533f0a..184bfe0a 100644
--- a/tools/localize/SourcePos.cpp
+++ b/tools/localize/SourcePos.cpp
@@ -3,6 +3,7 @@
 #include <stdarg.h>
 #include <cstdio>
 #include <set>
+#include <cstdio>
 
 using namespace std;
 
diff --git a/tools/localize/XMLHandler.h b/tools/localize/XMLHandler.h
index 1130710..324385f 100644
--- a/tools/localize/XMLHandler.h
+++ b/tools/localize/XMLHandler.h
@@ -3,6 +3,7 @@
 
 #include "SourcePos.h"
 
+#include <algorithm>
 #include <string>
 #include <vector>
 #include <map>
diff --git a/tools/localize/file_utils.cpp b/tools/localize/file_utils.cpp
index 293e50e..775ce2f 100644
--- a/tools/localize/file_utils.cpp
+++ b/tools/localize/file_utils.cpp
@@ -8,6 +8,9 @@
 #include <sys/fcntl.h>
 #include <sys/stat.h>
 #include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <cstdio>
 #include "log.h"
 
 using namespace android;
diff --git a/tools/localize/file_utils.h b/tools/localize/file_utils.h
index 3b3fa21..7706587 100644
--- a/tools/localize/file_utils.h
+++ b/tools/localize/file_utils.h
@@ -4,6 +4,7 @@
 #include "ValuesFile.h"
 #include "Configuration.h"
 #include <string>
+#include <cstdio>
 
 using namespace std;
 
diff --git a/tools/localize/localize.cpp b/tools/localize/localize.cpp
index c0d84cc..68c03b6 100644
--- a/tools/localize/localize.cpp
+++ b/tools/localize/localize.cpp
@@ -15,6 +15,7 @@
 #include <sstream>
 #include <stdio.h>
 #include <string.h>
+#include <stdlib.h>
 
 using namespace std;
 
diff --git a/tools/localize/localize_test.cpp b/tools/localize/localize_test.cpp
index 678cad8..1d0ac9a 100644
--- a/tools/localize/localize_test.cpp
+++ b/tools/localize/localize_test.cpp
@@ -1,3 +1,4 @@
+#include <cstdio>
 #include "XLIFFFile.h"
 #include "ValuesFile.h"
 #include "localize.h"
diff --git a/tools/localize/merge_res_and_xliff_test.cpp b/tools/localize/merge_res_and_xliff_test.cpp
index e4ab562..6fe2629 100644
--- a/tools/localize/merge_res_and_xliff_test.cpp
+++ b/tools/localize/merge_res_and_xliff_test.cpp
@@ -1,3 +1,4 @@
+#include <cstdio>
 #include "merge_res_and_xliff.h"
 #include <stdio.h>
 
diff --git a/wifi/java/android/net/wifi/IWifiManager.aidl b/wifi/java/android/net/wifi/IWifiManager.aidl
index fa328e8..73dbb6f 100644
--- a/wifi/java/android/net/wifi/IWifiManager.aidl
+++ b/wifi/java/android/net/wifi/IWifiManager.aidl
@@ -58,7 +58,7 @@
 
     int getNumAllowedChannels();
 
-    boolean setNumAllowedChannels(int numChannels);
+    boolean setNumAllowedChannels(int numChannels, boolean persist);
 
     int[] getValidChannelCounts();
     
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index 1f73bec..2ee1945 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -565,14 +565,15 @@
      * for some reason.
      * @param numChannels the number of allowed channels. Must be greater than 0
      * and less than or equal to 16.
+     * @param persist {@code true} if you want this remembered
      * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
      * {@code numChannels} is out of range.
      *
      * @hide pending API council
      */
-    public boolean setNumAllowedChannels(int numChannels) {
+    public boolean setNumAllowedChannels(int numChannels, boolean persist) {
         try {
-            return mService.setNumAllowedChannels(numChannels);
+            return mService.setNumAllowedChannels(numChannels, persist);
         } catch (RemoteException e) {
             return false;
         }
diff --git a/wifi/java/android/net/wifi/WifiNative.java b/wifi/java/android/net/wifi/WifiNative.java
index 0799f5f..c3c519f 100644
--- a/wifi/java/android/net/wifi/WifiNative.java
+++ b/wifi/java/android/net/wifi/WifiNative.java
@@ -79,6 +79,8 @@
 
     public native static int getRssiCommand();
 
+    public native static int getRssiApproxCommand();
+
     public native static int getLinkSpeedCommand();
 
     public native static String getMacAddressCommand();
diff --git a/wifi/java/android/net/wifi/WifiStateTracker.java b/wifi/java/android/net/wifi/WifiStateTracker.java
index 3aa31bf..12abce5 100644
--- a/wifi/java/android/net/wifi/WifiStateTracker.java
+++ b/wifi/java/android/net/wifi/WifiStateTracker.java
@@ -183,6 +183,10 @@
     private boolean mUseStaticIp = false;
     private int mReconnectCount;
 
+    // used to store the (non-persisted) num determined during device boot 
+    // (from mcc or other phone info) before the driver is started.
+    private int mNumAllowedChannels = 0;
+
     // Variables relating to the 'available networks' notification
     
     /**
@@ -238,7 +242,6 @@
     private SettingsObserver mSettingsObserver;
     
     private boolean mIsScanModeActive;
-    private boolean mIsScanModeSetDueToAHiddenNetwork;
     private boolean mEnableRssiPolling;
 
     // Wi-Fi run states:
@@ -311,7 +314,6 @@
         mScanResults = new ArrayList<ScanResult>();
         // Allocate DHCP info object once, and fill it in on each request
         mDhcpInfo = new DhcpInfo();
-        mIsScanModeSetDueToAHiddenNetwork = false;
         mRunState = RUN_STATE_STARTING;
 
         // Setting is in seconds
@@ -379,6 +381,14 @@
     }
 
     /**
+     * Return the name of our WLAN network interface.
+     * @return the name of our interface.
+     */
+    public String getInterfaceName() {
+        return mInterfaceName;
+    }
+
+    /**
      * Return the system properties name associated with the tcp buffer sizes
      * for this network.
      */
@@ -576,9 +586,12 @@
         try {
             return setNumAllowedChannels(
                     Settings.Secure.getInt(mContext.getContentResolver(),
-                                           Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS));
+                    Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS));
         } catch (Settings.SettingNotFoundException e) {
-            // if setting doesn't exist, stick with the driver default
+            if (mNumAllowedChannels != 0) {
+                WifiNative.setNumAllowedChannelsCommand(mNumAllowedChannels);
+            }
+            // otherwise, use the driver default
         }
         return true;
     }
@@ -592,6 +605,7 @@
      * {@code numChannels} is outside the valid range.
      */
     public synchronized boolean setNumAllowedChannels(int numChannels) {
+        mNumAllowedChannels = numChannels;
         return WifiNative.setNumAllowedChannelsCommand(numChannels);
     }
 
@@ -790,7 +804,7 @@
                     WifiNative.closeSupplicantConnection();
                 }
                 if (died) {
-                    resetInterface();
+                    resetInterface(false);
                 }
                 // When supplicant dies, kill the DHCP thread
                 if (mDhcpTarget != null) {
@@ -1023,17 +1037,12 @@
                  * On receiving the first scan results after connecting to
                  * the supplicant, switch scan mode over to passive.
                  */
-                if (!mIsScanModeSetDueToAHiddenNetwork) {
-                    // This is the only place at the moment where we set
-                    // the scan mode NOT due to a hidden network. This is
-                    // what the second parameter value (false) stands for.
-                    setScanMode(false, false);
-                }
+                setScanMode(false);
                 break;
 
             case EVENT_POLL_INTERVAL:
                 if (mWifiInfo.getSupplicantState() != SupplicantState.UNINITIALIZED) {
-                    requestPolledInfo(mWifiInfo);
+                    requestPolledInfo(mWifiInfo, true);
                     checkPollTimer();
                 }
                 break;
@@ -1164,9 +1173,7 @@
         return disabledNetwork;
     }
 
-    public synchronized void setScanMode(
-        boolean isScanModeActive, boolean setDueToAHiddenNetwork) {
-        mIsScanModeSetDueToAHiddenNetwork = setDueToAHiddenNetwork;
+    public synchronized void setScanMode(boolean isScanModeActive) {
         if (mIsScanModeActive != isScanModeActive) {
             WifiNative.setScanModeCommand(mIsScanModeActive = isScanModeActive);
         }
@@ -1206,7 +1213,7 @@
             cancelDisconnect();
         }
         mDisconnectExpected = false;
-        resetInterface();
+        resetInterface(true);
         setDetailedState(newState);
         sendNetworkStateChangeBroadcast(mLastBssid);
         mWifiInfo.setBSSID(null);
@@ -1219,7 +1226,7 @@
      * Resets the Wi-Fi interface by clearing any state, resetting any sockets
      * using the interface, stopping DHCP, and disabling the interface.
      */
-    public void resetInterface() {
+    public void resetInterface(boolean reenable) {
         mHaveIpAddress = false;
         mObtainingIpAddress = false;
         mWifiInfo.setIpAddress(0);
@@ -1240,6 +1247,9 @@
         }
         
         NetworkUtils.disableInterface(mInterfaceName);
+        if (reenable) {
+            NetworkUtils.enableInterface(mInterfaceName);
+        }
     }
 
     /**
@@ -1278,7 +1288,7 @@
      */
     public WifiInfo requestConnectionInfo() {
         requestConnectionStatus(mWifiInfo);
-        requestPolledInfo(mWifiInfo);
+        requestPolledInfo(mWifiInfo, false);
         return mWifiInfo;
     }
 
@@ -1333,10 +1343,14 @@
      * Get the dynamic information that is not reported via events.
      * @param info the object into which the information should be captured.
      */
-    private synchronized void requestPolledInfo(WifiInfo info)
+    private synchronized void requestPolledInfo(WifiInfo info, boolean polling)
     {
         int newRssi = WifiNative.getRssiCommand();
-        if (newRssi != -1 && -200 < newRssi && newRssi < 100) { // screen out invalid values
+        if (newRssi != -1 && -200 < newRssi && newRssi < 256) { // screen out invalid values
+            /* some implementations avoid negative values by adding 256
+             * so we need to adjust for that here.
+             */
+            if (newRssi > 0) newRssi -= 256;
             info.setRssi(newRssi);
             /*
              * Rather then sending the raw RSSI out every time it
@@ -1879,7 +1893,7 @@
                         oDns2 != mDhcpInfo.dns2));
 
             if (changed) {
-                resetInterface();
+                resetInterface(true);
                 configureInterface();
                 if (mUseStaticIp) {
                     mTarget.sendEmptyMessage(EVENT_CONFIGURATION_CHANGED);